title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
QlikView - IntervalMatch
QlikView IntervalMatch is a powerful function used to match distinct numeric values to numeric intervals. It is useful in analyzing how the events actually happened versus the planned events. The example of a scenario where it is used is in the assembly lines of the production houses where the belts are planned to run at certain times and for certain duration. However, the actual run can happen at different points in time because of breakdown etc. Consider an assembly line where there are three belts named A, B and C. They are planned to start & stop at specific times of a day. In a given day, we study the actual start and end time and analyze what all happened in that day. For this, we consider two sets of observations as shown below. # Data Set for AssembilyLine. StartTime,EndTime, BeltNo 00:05,4:20, A 1:50,2:45,B 3:15,10:30,C # Data set for the events happened. ActualTime,Product 1:10,Start Belt A 2:24,Stop Belt A 3:25,Restart Belt A 4:35,Stop Belt A 2:20,Start Belt B 3:11, Stop Belt B 3:15,Start Belt C 11:20, Stop Belt C We open the script editor in a new QlikView document using Control+E. The following code creates the required tables as inline data. After creating this script, press control+R to reload the data into the QlikView document. Let us create a Table Box sheet object to show the data generated by the IntervalMatch function. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed. On clicking OK in the above window, a table appears showing the field ActualTime matched to the intervals StartTime and EndTime. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3372, "s": 2920, "text": "QlikView IntervalMatch is a powerful function used to match distinct numeric values to numeric intervals. It is useful in analyzing how the events actually happened versus the planned events. The example of a scenario where it is used is in the assembly lines of the production houses where the belts are planned to run at certain times and for certain duration. However, the actual run can happen at different points in time because of breakdown etc." }, { "code": null, "e": 3666, "s": 3372, "text": "Consider an assembly line where there are three belts named A, B and C. They are planned to start & stop at specific times of a day. In a given day, we study the actual start and end time and analyze what all happened in that day. For this, we consider two sets of observations as shown below." }, { "code": null, "e": 3963, "s": 3666, "text": "# Data Set for AssembilyLine.\nStartTime,EndTime, BeltNo\n00:05,4:20, A\n1:50,2:45,B\n3:15,10:30,C\n\t\n# Data set for the events happened.\nActualTime,Product\n1:10,Start Belt A\n2:24,Stop Belt A\n3:25,Restart Belt A\n4:35,Stop Belt A\n2:20,Start Belt B\n3:11, Stop Belt B\n3:15,Start Belt C\n11:20, Stop Belt C" }, { "code": null, "e": 4187, "s": 3963, "text": "We open the script editor in a new QlikView document using Control+E. The following code creates the required tables as inline data. After creating this script, press control+R to reload the data into the QlikView document." }, { "code": null, "e": 4463, "s": 4187, "text": "Let us create a Table Box sheet object to show the data generated by the IntervalMatch\nfunction. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and select the required fields to be displayed." }, { "code": null, "e": 4592, "s": 4463, "text": "On clicking OK in the above window, a table appears showing the field ActualTime matched to the intervals StartTime and EndTime." }, { "code": null, "e": 4625, "s": 4592, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 4638, "s": 4625, "text": " Arthur Fong" }, { "code": null, "e": 4645, "s": 4638, "text": " Print" }, { "code": null, "e": 4656, "s": 4645, "text": " Add Notes" } ]
Python - Filter Strings within ASCII range - GeeksforGeeks
12 Nov, 2020 Given ASCII or alphabetical range, filter strings found in particular range. Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], strt_asc, end_asc = 105, 115 Output : [‘is’] Explanation : i has 105, and s has 115, which is in range ASCII values.Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], strt_asc, end_asc = 100, 115 Output : [‘gfg’, ‘is’, ‘for’, ‘geeks’] Explanation : Strings with range characters included. Method #1 : Using list comprehension + all() + ord() In this, we check for all characters to be in given ASCII range, computed using ord(), and accordingly, strings are filtered. Python3 # Python3 code to demonstrate working of# Filter Strings within ASCII range# Using list comprehension + ord() + all() # initializing listtest_list = ["gfg", "is", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing ASCII rangestrt_asc, end_asc = 105, 115 # checking for all characters to be in ASCII rangeres = [sub for sub in test_list if all( ord(ele) >= strt_asc and ord(ele) <= end_asc for ele in sub)] # printing resultprint("Filtered Strings : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] Filtered Strings : ['is'] Method #2 : Using filter() + lambda + all() + ord() In this, we perform task of filtering using filter() and lambda function, ord() and all() is used in similar way as above method. Python3 # Python3 code to demonstrate working of# Filter Strings within ASCII range# Using filter() + lambda + all() + ord() # initializing listtest_list = ["gfg", "is", "best", "for", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing ASCII rangestrt_asc, end_asc = 105, 115 # checking for all characters to be in ASCII rangeres = list(filter(lambda sub: all(ord(ele) >= strt_asc and ord( ele) <= end_asc for ele in sub), test_list)) # printing resultprint("Filtered Strings : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeks'] Filtered Strings : ['is'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n12 Nov, 2020" }, { "code": null, "e": 24369, "s": 24292, "text": "Given ASCII or alphabetical range, filter strings found in particular range." }, { "code": null, "e": 24727, "s": 24369, "text": "Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], strt_asc, end_asc = 105, 115 Output : [‘is’] Explanation : i has 105, and s has 115, which is in range ASCII values.Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], strt_asc, end_asc = 100, 115 Output : [‘gfg’, ‘is’, ‘for’, ‘geeks’] Explanation : Strings with range characters included. " }, { "code": null, "e": 24780, "s": 24727, "text": "Method #1 : Using list comprehension + all() + ord()" }, { "code": null, "e": 24906, "s": 24780, "text": "In this, we check for all characters to be in given ASCII range, computed using ord(), and accordingly, strings are filtered." }, { "code": null, "e": 24914, "s": 24906, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Strings within ASCII range# Using list comprehension + ord() + all() # initializing listtest_list = [\"gfg\", \"is\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ASCII rangestrt_asc, end_asc = 105, 115 # checking for all characters to be in ASCII rangeres = [sub for sub in test_list if all( ord(ele) >= strt_asc and ord(ele) <= end_asc for ele in sub)] # printing resultprint(\"Filtered Strings : \" + str(res))", "e": 25447, "s": 24914, "text": null }, { "code": null, "e": 25535, "s": 25447, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeks']\nFiltered Strings : ['is']\n" }, { "code": null, "e": 25587, "s": 25535, "text": "Method #2 : Using filter() + lambda + all() + ord()" }, { "code": null, "e": 25717, "s": 25587, "text": "In this, we perform task of filtering using filter() and lambda function, ord() and all() is used in similar way as above method." }, { "code": null, "e": 25725, "s": 25717, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Filter Strings within ASCII range# Using filter() + lambda + all() + ord() # initializing listtest_list = [\"gfg\", \"is\", \"best\", \"for\", \"geeks\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing ASCII rangestrt_asc, end_asc = 105, 115 # checking for all characters to be in ASCII rangeres = list(filter(lambda sub: all(ord(ele) >= strt_asc and ord( ele) <= end_asc for ele in sub), test_list)) # printing resultprint(\"Filtered Strings : \" + str(res))", "e": 26264, "s": 25725, "text": null }, { "code": null, "e": 26352, "s": 26264, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeks']\nFiltered Strings : ['is']\n" }, { "code": null, "e": 26373, "s": 26352, "text": "Python list-programs" }, { "code": null, "e": 26380, "s": 26373, "text": "Python" }, { "code": null, "e": 26396, "s": 26380, "text": "Python Programs" }, { "code": null, "e": 26494, "s": 26396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26526, "s": 26494, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26582, "s": 26526, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26624, "s": 26582, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26679, "s": 26624, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26721, "s": 26679, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26743, "s": 26721, "text": "Defaultdict in Python" }, { "code": null, "e": 26789, "s": 26743, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26828, "s": 26789, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26866, "s": 26828, "text": "Python | Convert a list to dictionary" } ]
Python PostgreSQL - Where Clause
While performing SELECT, UPDATE or, DELETE operations, you can specify condition to filter the records using the WHERE clause. The operation will be performed on the records which satisfies the given condition. Following is the syntax of the WHERE clause in PostgreSQL − SELECT column1, column2, columnN FROM table_name WHERE [search_condition] You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Assume we have created a table with name CRICKETERS using the following query − postgres=# CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); CREATE TABLE postgres=# And if we have inserted 5 records in to it using INSERT statements as − postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); INSERT 0 1 postgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); INSERT 0 1 postgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); INSERT 0 1 postgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); INSERT 0 1 Following SELECT statement retrieves the records whose age is greater than 35 − postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35; first_name | last_name | age | place_of_birth | country ------------+------------+-----+----------------+------------- Jonathan | Trott | 38 | CapeTown | SouthAfrica Kumara | Sangakkara | 41 | Matale | Srilanka (2 rows) postgres=# To fetch specific records from a table using the python program execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method. Following python example demonstrates the usage of WHERE command using python. import psycopg2 #establishing the connection conn = psycopg2.connect( database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table insert_stmt = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)" data = [('Krishna', 'Sharma', 19, 'M', 2000), ('Raj', 'Kandukuri', 20, 'M', 7000), ('Ramya', 'Ramapriya', 25, 'M', 5000), ('Mac', 'Mohan', 26, 'M', 2000)] cursor.executemany(insert_stmt, data) #Retrieving specific records using the where clause cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)] 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": 3416, "s": 3205, "text": "While performing SELECT, UPDATE or, DELETE operations, you can specify condition to filter the records using the WHERE clause. The operation will be performed on the records which satisfies the given condition." }, { "code": null, "e": 3476, "s": 3416, "text": "Following is the syntax of the WHERE clause in PostgreSQL −" }, { "code": null, "e": 3551, "s": 3476, "text": "SELECT column1, column2, columnN\nFROM table_name\nWHERE [search_condition]\n" }, { "code": null, "e": 3709, "s": 3551, "text": "You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 3789, "s": 3709, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 3969, "s": 3789, "text": "postgres=# CREATE TABLE CRICKETERS ( \n First_Name VARCHAR(255), Last_Name VARCHAR(255), \n Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#" }, { "code": null, "e": 4041, "s": 3969, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 4533, "s": 4041, "text": "postgres=# insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nINSERT 0 1\npostgres=# insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nINSERT 0 1" }, { "code": null, "e": 4613, "s": 4533, "text": "Following SELECT statement retrieves the records whose age is greater than 35 −" }, { "code": null, "e": 4928, "s": 4613, "text": "postgres=# SELECT * FROM CRICKETERS WHERE AGE > 35;\nfirst_name | last_name | age | place_of_birth | country\n------------+------------+-----+----------------+-------------\nJonathan | Trott | 38 | CapeTown | SouthAfrica\nKumara | Sangakkara | 41 | Matale | Srilanka\n(2 rows)\npostgres=#\n" }, { "code": null, "e": 5094, "s": 4928, "text": "To fetch specific records from a table using the python program execute the SELECT statement with WHERE clause, by passing it as a parameter to the execute() method." }, { "code": null, "e": 5173, "s": 5094, "text": "Following python example demonstrates the usage of WHERE command using python." }, { "code": null, "e": 6270, "s": 5173, "text": "import psycopg2\n\n#establishing the connection\nconn = psycopg2.connect(\n database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432'\n)\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ninsert_stmt = \"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) \n VALUES (%s, %s, %s, %s, %s)\"\ndata = [('Krishna', 'Sharma', 19, 'M', 2000), \n ('Raj', 'Kandukuri', 20, 'M', 7000),\n ('Ramya', 'Ramapriya', 25, 'M', 5000),\n ('Mac', 'Mohan', 26, 'M', 2000)]\ncursor.executemany(insert_stmt, data)\n\n#Retrieving specific records using the where clause\ncursor.execute(\"SELECT * from EMPLOYEE WHERE AGE <23\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 6351, "s": 6270, "text": "[('Krishna', 'Sharma', 19, 'M', 2000.0), ('Raj', 'Kandukuri', 20, 'M', 7000.0)]\n" }, { "code": null, "e": 6388, "s": 6351, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6404, "s": 6388, "text": " Malhar Lathkar" }, { "code": null, "e": 6437, "s": 6404, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6456, "s": 6437, "text": " Arnab Chakraborty" }, { "code": null, "e": 6491, "s": 6456, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6513, "s": 6491, "text": " In28Minutes Official" }, { "code": null, "e": 6547, "s": 6513, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6575, "s": 6547, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6610, "s": 6575, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6624, "s": 6610, "text": " Lets Kode It" }, { "code": null, "e": 6657, "s": 6624, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6674, "s": 6657, "text": " Abhilash Nelson" }, { "code": null, "e": 6681, "s": 6674, "text": " Print" }, { "code": null, "e": 6692, "s": 6681, "text": " Add Notes" } ]
ReactJS - Stateless Component
React component with internal state is called Stateful component and React component without any internal state management is called Stateless component. React recommends to create and use as many stateless component as possible and create stateful component only when it is absolutely necessary. Also, React does not share the state with child component. The data needs to be passed to the child component through child’s properties. An example to pass date to the FormattedDate component is as follows − <FormattedDate value={this.state.item.spend_date} /> The general idea is not to overcomplicate the application logic and use advanced features only when necessary. Let us create a React application to show the current date and time. First, create a new react application, react-clock-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter. Next, open the application in your favorite editor. Next, create src folder under the root directory of the application. Next, create components folder under src folder. Next, create a file, Clock.js under src/components folder and start editing. Next, import React library. import React from 'react'; Next, create Clock component. class Clock extends React.Component { constructor(props) { super(props); } } Next, initialize state with current date and time. constructor(props) { super(props); this.state = { date: new Date() } } Next, add a method, setTime() to update the current time − setTime() { console.log(this.state.date); this.setState((state, props) => ( { date: new Date() } )) } Next, use JavaScript method, setInterval and call setTime() method every second to ensure that the component’s state is updated every second. constructor(props) { super(props); this.state = { date: new Date() } setInterval( () => this.setTime(), 1000); } Next, create a render function. render() { } Next, update the render() method to show the current time. render() { return ( <div><p>The current time is {this.state.date.toString()}</p></div> ); } Finally, export the component. export default Clock; The complete source code of the Clock component is as follows − import React from 'react'; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date() } setInterval( () => this.setTime(), 1000); } setTime() { console.log(this.state.date); this.setState((state, props) => ( { date: new Date() } )) } render() { return ( <div> <p>The current time is {this.state.date.toString()}</p> </div> ); } } export default Clock; Next, create a file, index.js under the src folder and use Clock component. import React from 'react'; import ReactDOM from 'react-dom'; import Clock from './components/Clock'; ReactDOM.render( <React.StrictMode> <Clock /> </React.StrictMode>, document.getElementById('root') ); Finally, create a public folder under the root folder and create index.html file. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Clock</title> </head> <body> <div id="root"></div> <script type="text/JavaScript" src="./index.js"></script> </body> </html> Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The application will show the time and update it every second. The current time is Wed Nov 11 2020 10:10:18 GMT+0530(Indian Standard Time) The above application works fine but throws an error in the console. Can't call setState on a component that is not yet mounted. The error message indicates that the setState has to be called only after the component is mounted. React component has a life-cycle and mounting is one of the stages in the life cycle. Let us learn more about the life-cycle in the upcoming chapters. Let us introduce state management in the expense manager application by adding a simple feature to remove an expenses item. Open expense-manager application in your favorite editor. Next, open ExpenseEntryItemList.js file. Next, initialize the state of the component with the expense items passed into the components through properties. this.state = { items: this.props.items } Next, add the Remove label in the render()method. <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> Next, update the lists in the render() method to include the remove link. Also, use items in the state (this.state.items) instead of items from the properties (this.props.items). const lists = this.state.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); Next, implement handleDelete method, which will remove the relevant expense item from the state. handleDelete = (id, e) => { e.preventDefault(); console.log(id); this.setState((state, props) => { let items = []; state.items.forEach((item, idx) => { if(item.id != id) items.push(item) }) let newState = { items: items } return newState; }) } Here, Expense items are fetched from the current state of the component. Current expense items are looped over to find the item referred by the user using id of the item. Create a new item list with all the expense item except the one referred by the user Next, add a new row to show the total expense amount. <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {this.getTotal()} </td> </tr> Next, implement the getTotal() method to calculate the total expense amount. getTotal() { let total = 0; for(var i = 0; i < this.state.items.length; i++) { total += this.state.items[i].amount } return total; } The complete code of the render() method is as follows − render() { const lists = this.state.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {this.getTotal()} </td> </tr> </tbody> </table> ); } Finally, the updated code of the ExpenseEntryItemList is as follows − import React from 'react'; import './ExpenseEntryItemList.css'; class ExpenseEntryItemList extends React.Component { constructor(props) { super(props); this.state = { items: this.props.items } this.handleMouseEnter = this.handleMouseEnter.bind(); this.handleMouseLeave = this.handleMouseLeave.bind(); this.handleMouseOver = this.handleMouseOver.bind(); } handleMouseEnter(e) { e.target.parentNode.classList.add("highlight"); } handleMouseLeave(e) { e.target.parentNode.classList.remove("highlight"); } handleMouseOver(e) { console.log("The mouse is at (" + e.clientX + ", " + e.clientY + ")"); } handleDelete = (id, e) => { e.preventDefault(); console.log(id); this.setState((state, props) => { let items = []; state.items.forEach((item, idx) => { if(item.id != id) items.push(item) }) let newState = { items: items } return newState; }) } getTotal() { let total = 0; for(var i = 0; i < this.state.items.length; i++) { total += this.state.items[i].amount } return total; } render() { const lists = this.state.items.map((item) => <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}> <td>{item.name}</td> <td>{item.amount}</td> <td>{new Date(item.spendDate).toDateString()}</td> <td>{item.category}</td> <td><a href="#" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td> </tr> ); return ( <table onMouseOver={this.handleMouseOver}> <thead> <tr> <th>Item</th> <th>Amount</th> <th>Date</th> <th>Category</th> <th>Remove</th> </tr> </thead> <tbody> {lists} <tr> <td colSpan="1" style={{ textAlign: "right" }}>Total Amount</td> <td colSpan="4" style={{ textAlign: "left" }}> {this.getTotal()} </td> </tr> </tbody> </table> ); } } export default ExpenseEntryItemList; Next, Update the index.js and include the ExpenseEntyItemList component. import React from 'react'; import ReactDOM from 'react-dom'; import ExpenseEntryItemList from './components/ExpenseEntryItemList' const items = [ { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" }, { id: 2, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" }, { id: 3, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" }, { id: 4, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" }, { id: 5, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" }, { id: 6, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" }, { id: 7, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" }, { id: 8, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" }, { id: 9, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" }, { id: 10, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" } ] ReactDOM.render( <React.StrictMode> <ExpenseEntryItemList items={items} /> </React.StrictMode>, document.getElementById('root') ); Next, serve the application using npm command. npm start Next, open the browser and enter http://localhost:3000 in the address bar and press enter. Finally, to remove an expense item, click the corresponding remove link. It will remove the corresponding item and refresh the user interface as shown in animated gif. 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2468, "s": 2033, "text": "React component with internal state is called Stateful component and React component without any internal state management is called Stateless component. React recommends to create and use as many stateless component as possible and create stateful component only when it is absolutely necessary. Also, React does not share the state with child component. The data needs to be passed to the child component through child’s properties." }, { "code": null, "e": 2539, "s": 2468, "text": "An example to pass date to the FormattedDate component is as follows −" }, { "code": null, "e": 2593, "s": 2539, "text": "<FormattedDate value={this.state.item.spend_date} />\n" }, { "code": null, "e": 2704, "s": 2593, "text": "The general idea is not to overcomplicate the application logic and use advanced features only when necessary." }, { "code": null, "e": 2773, "s": 2704, "text": "Let us create a React application to show the current date and time." }, { "code": null, "e": 2935, "s": 2773, "text": "First, create a new react application, react-clock-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter." }, { "code": null, "e": 2987, "s": 2935, "text": "Next, open the application in your favorite editor." }, { "code": null, "e": 3056, "s": 2987, "text": "Next, create src folder under the root directory of the application." }, { "code": null, "e": 3105, "s": 3056, "text": "Next, create components folder under src folder." }, { "code": null, "e": 3182, "s": 3105, "text": "Next, create a file, Clock.js under src/components folder and start editing." }, { "code": null, "e": 3210, "s": 3182, "text": "Next, import React library." }, { "code": null, "e": 3238, "s": 3210, "text": "import React from 'react';\n" }, { "code": null, "e": 3268, "s": 3238, "text": "Next, create Clock component." }, { "code": null, "e": 3362, "s": 3268, "text": "class Clock extends React.Component { \n constructor(props) { \n super(props); \n } \n}\n" }, { "code": null, "e": 3413, "s": 3362, "text": "Next, initialize state with current date and time." }, { "code": null, "e": 3504, "s": 3413, "text": "constructor(props) { \n super(props); \n this.state = { \n date: new Date() \n } \n}" }, { "code": null, "e": 3563, "s": 3504, "text": "Next, add a method, setTime() to update the current time −" }, { "code": null, "e": 3700, "s": 3563, "text": "setTime() { \n console.log(this.state.date); \n this.setState((state, props) => (\n {\n date: new Date() \n } \n )) \n}" }, { "code": null, "e": 3842, "s": 3700, "text": "Next, use JavaScript method, setInterval and call setTime() method every second to ensure that the component’s state is updated every second." }, { "code": null, "e": 3979, "s": 3842, "text": "constructor(props) { \n super(props); \n this.state = { \n date: new Date() \n } \n setInterval( () => this.setTime(), 1000); \n}" }, { "code": null, "e": 4011, "s": 3979, "text": "Next, create a render function." }, { "code": null, "e": 4187, "s": 4011, "text": "render() {\n}\nNext, update the render() method to show the current time.\nrender() {\n return (\n <div><p>The current time is {this.state.date.toString()}</p></div>\n );\n}" }, { "code": null, "e": 4218, "s": 4187, "text": "Finally, export the component." }, { "code": null, "e": 4241, "s": 4218, "text": "export default Clock;\n" }, { "code": null, "e": 4305, "s": 4241, "text": "The complete source code of the Clock component is as follows −" }, { "code": null, "e": 4851, "s": 4305, "text": "import React from 'react';\n\nclass Clock extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n date: new Date()\n } \n setInterval( () => this.setTime(), 1000);\n }\n setTime() {\n console.log(this.state.date);\n this.setState((state, props) => (\n {\n date: new Date()\n }\n ))\n }\n render() {\n return (\n <div>\n <p>The current time is {this.state.date.toString()}</p>\n </div>\n );\n }\n}\nexport default Clock;" }, { "code": null, "e": 4927, "s": 4851, "text": "Next, create a file, index.js under the src folder and use Clock component." }, { "code": null, "e": 5146, "s": 4927, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport Clock from './components/Clock';\n\nReactDOM.render(\n <React.StrictMode>\n <Clock />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 5228, "s": 5146, "text": "Finally, create a public folder under the root folder and create index.html file." }, { "code": null, "e": 5459, "s": 5228, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Clock</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>" }, { "code": null, "e": 5506, "s": 5459, "text": "Next, serve the application using npm command." }, { "code": null, "e": 5517, "s": 5506, "text": "npm start\n" }, { "code": null, "e": 5671, "s": 5517, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The application will show the time and update it every second." }, { "code": null, "e": 5748, "s": 5671, "text": "The current time is Wed Nov 11 2020 10:10:18 GMT+0530(Indian Standard Time)\n" }, { "code": null, "e": 5817, "s": 5748, "text": "The above application works fine but throws an error in the console." }, { "code": null, "e": 5878, "s": 5817, "text": "Can't call setState on a component that is not yet mounted.\n" }, { "code": null, "e": 5978, "s": 5878, "text": "The error message indicates that the setState has to be called only after the component is mounted." }, { "code": null, "e": 6129, "s": 5978, "text": "React component has a life-cycle and mounting is one of the stages in the life cycle. Let us learn more about the life-cycle in the upcoming chapters." }, { "code": null, "e": 6253, "s": 6129, "text": "Let us introduce state management in the expense manager application by adding a simple feature to remove an expenses item." }, { "code": null, "e": 6311, "s": 6253, "text": "Open expense-manager application in your favorite editor." }, { "code": null, "e": 6352, "s": 6311, "text": "Next, open ExpenseEntryItemList.js file." }, { "code": null, "e": 6466, "s": 6352, "text": "Next, initialize the state of the component with the expense items passed into the components through properties." }, { "code": null, "e": 6513, "s": 6466, "text": "this.state = { \n items: this.props.items \n}\n" }, { "code": null, "e": 6563, "s": 6513, "text": "Next, add the Remove label in the render()method." }, { "code": null, "e": 6705, "s": 6563, "text": "<thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n</thead>" }, { "code": null, "e": 6884, "s": 6705, "text": "Next, update the lists in the render() method to include the remove link. Also, use items in the state (this.state.items) instead of items from the properties (this.props.items)." }, { "code": null, "e": 7267, "s": 6884, "text": "const lists = this.state.items.map((item) =>\n <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\" onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n);" }, { "code": null, "e": 7364, "s": 7267, "text": "Next, implement handleDelete method, which will remove the relevant expense item from the state." }, { "code": null, "e": 7688, "s": 7364, "text": "handleDelete = (id, e) => {\n e.preventDefault();\n console.log(id);\n\n this.setState((state, props) => {\n let items = [];\n\n state.items.forEach((item, idx) => {\n if(item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })\n}" }, { "code": null, "e": 7694, "s": 7688, "text": "Here," }, { "code": null, "e": 7761, "s": 7694, "text": "Expense items are fetched from the current state of the component." }, { "code": null, "e": 7859, "s": 7761, "text": "Current expense items are looped over to find the item referred by the user using id of the item." }, { "code": null, "e": 7944, "s": 7859, "text": "Create a new item list with all the expense item except the one referred by the user" }, { "code": null, "e": 7998, "s": 7944, "text": "Next, add a new row to show the total expense amount." }, { "code": null, "e": 8161, "s": 7998, "text": "<tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td> \n</tr>" }, { "code": null, "e": 8238, "s": 8161, "text": "Next, implement the getTotal() method to calculate the total expense amount." }, { "code": null, "e": 8389, "s": 8238, "text": "getTotal() {\n let total = 0;\n for(var i = 0; i < this.state.items.length; i++) {\n total += this.state.items[i].amount\n }\n return total;\n}" }, { "code": null, "e": 8446, "s": 8389, "text": "The complete code of the render() method is as follows −" }, { "code": null, "e": 9477, "s": 8446, "text": "render() {\n const lists = this.state.items.map((item) =>\n <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\" \n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <table onMouseOver={this.handleMouseOver}>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td> \n </tr>\n </tbody>\n </table>\n );\n}" }, { "code": null, "e": 9547, "s": 9477, "text": "Finally, the updated code of the ExpenseEntryItemList is as follows −" }, { "code": null, "e": 11942, "s": 9547, "text": "import React from 'react';\nimport './ExpenseEntryItemList.css';\n\nclass ExpenseEntryItemList extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n items: this.props.items\n }\n this.handleMouseEnter = this.handleMouseEnter.bind();\n this.handleMouseLeave = this.handleMouseLeave.bind();\n this.handleMouseOver = this.handleMouseOver.bind();\n }\n handleMouseEnter(e) {\n e.target.parentNode.classList.add(\"highlight\");\n }\n handleMouseLeave(e) {\n e.target.parentNode.classList.remove(\"highlight\");\n }\n handleMouseOver(e) {\n console.log(\"The mouse is at (\" + e.clientX + \", \" + e.clientY + \")\");\n }\n handleDelete = (id, e) => {\n e.preventDefault();\n console.log(id);\n this.setState((state, props) => {\n let items = [];\n state.items.forEach((item, idx) => {\n if(item.id != id)\n items.push(item)\n })\n let newState = {\n items: items\n }\n return newState;\n })\n }\n getTotal() {\n let total = 0;\n for(var i = 0; i < this.state.items.length; i++) {\n total += this.state.items[i].amount\n }\n return total;\n }\n render() {\n const lists = this.state.items.map((item) =>\n <tr key={item.id} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave}>\n <td>{item.name}</td>\n <td>{item.amount}</td>\n <td>{new Date(item.spendDate).toDateString()}</td>\n <td>{item.category}</td>\n <td><a href=\"#\" \n onClick={(e) => this.handleDelete(item.id, e)}>Remove</a></td>\n </tr>\n );\n return (\n <table onMouseOver={this.handleMouseOver}>\n <thead>\n <tr>\n <th>Item</th>\n <th>Amount</th>\n <th>Date</th>\n <th>Category</th>\n <th>Remove</th>\n </tr>\n </thead>\n <tbody>\n {lists}\n <tr>\n <td colSpan=\"1\" style={{ textAlign: \"right\" }}>Total Amount</td>\n <td colSpan=\"4\" style={{ textAlign: \"left\" }}>\n {this.getTotal()}\n </td> \n </tr>\n </tbody>\n </table>\n );\n }\n}\nexport default ExpenseEntryItemList;" }, { "code": null, "e": 12015, "s": 11942, "text": "Next, Update the index.js and include the ExpenseEntyItemList component." }, { "code": null, "e": 13224, "s": 12015, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseEntryItemList from './components/ExpenseEntryItemList'\n\nconst items = [\n { id: 1, name: \"Pizza\", amount: 80, spendDate: \"2020-10-10\", category: \"Food\" },\n { id: 2, name: \"Grape Juice\", amount: 30, spendDate: \"2020-10-12\", category: \"Food\" },\n { id: 3, name: \"Cinema\", amount: 210, spendDate: \"2020-10-16\", category: \"Entertainment\" },\n { id: 4, name: \"Java Programming book\", amount: 242, spendDate: \"2020-10-15\", category: \"Academic\" },\n { id: 5, name: \"Mango Juice\", amount: 35, spendDate: \"2020-10-16\", category: \"Food\" },\n { id: 6, name: \"Dress\", amount: 2000, spendDate: \"2020-10-25\", category: \"Cloth\" },\n { id: 7, name: \"Tour\", amount: 2555, spendDate: \"2020-10-29\", category: \"Entertainment\" },\n { id: 8, name: \"Meals\", amount: 300, spendDate: \"2020-10-30\", category: \"Food\" },\n { id: 9, name: \"Mobile\", amount: 3500, spendDate: \"2020-11-02\", category: \"Gadgets\" },\n { id: 10, name: \"Exam Fees\", amount: 1245, spendDate: \"2020-11-04\", category: \"Academic\" }\n]\nReactDOM.render(\n <React.StrictMode>\n <ExpenseEntryItemList items={items} />\n </React.StrictMode>,\n document.getElementById('root')\n);" }, { "code": null, "e": 13271, "s": 13224, "text": "Next, serve the application using npm command." }, { "code": null, "e": 13282, "s": 13271, "text": "npm start\n" }, { "code": null, "e": 13373, "s": 13282, "text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter." }, { "code": null, "e": 13541, "s": 13373, "text": "Finally, to remove an expense item, click the corresponding remove link. It will remove the corresponding item and refresh the user interface as shown in animated gif." }, { "code": null, "e": 13576, "s": 13541, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 13590, "s": 13576, "text": " Anadi Sharma" }, { "code": null, "e": 13625, "s": 13590, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13645, "s": 13625, "text": " Skillbakerystudios" }, { "code": null, "e": 13680, "s": 13645, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 13703, "s": 13680, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 13738, "s": 13703, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 13754, "s": 13738, "text": " TELCOMA Global" }, { "code": null, "e": 13787, "s": 13754, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 13805, "s": 13787, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 13812, "s": 13805, "text": " Print" }, { "code": null, "e": 13823, "s": 13812, "text": " Add Notes" } ]
How can I create an android service that dalvik will not kill?
Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy. This example demonstrate about How can I create an android service that dalvik will not kill. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <TextView android:id = "@+id/text" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Start Service" android:textSize = "25sp" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken text view, when user click on text view, it will start service and stop service. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TextView text = findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isMyServiceRunning(service.class)) { text.setText("Stoped"); stopService(new Intent(MainActivity.this, service.class)); } else { text.setText("Started"); startService(new Intent(MainActivity.this, service.class)); } } }); } 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())) { return true; } } return false; } } In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code – package com.example.andy.myapplication; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.MediaPlayer; import android.os.Build; import android.os.IBinder; import android.os.PowerManager; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.Toast; public class service extends Service { PowerManager pm; @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl; @Override public IBinder onBind(Intent intent) { return null; } @SuppressLint("InvalidWakeLockTag") @Override public void onCreate() { super.onCreate(); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); } @TargetApi(Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public int onStartCommand(Intent intent, int flags, int startId) { wl.acquire(); //Do some task Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show(); return START_STICKY; } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onDestroy() { super.onDestroy(); wl.release(); Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show(); } } In the above code we have called power manager to stop screen lock so android thread not going to stop the service thread as shown below – @SuppressLint("InvalidWakeLockTag") @Override public void onCreate() { super.onCreate(); pm = (PowerManager) getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); } @TargetApi(Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public int onStartCommand(Intent intent, int flags, int startId) { wl.acquire(); //Do some task Toast.makeText(this, "Notification Service started by user.", Toast.LENGTH_LONG).show(); return START_STICKY; } @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onDestroy() { super.onDestroy(); wl.release(); Toast.makeText(this, "Notification Service destroyed by user.", Toast.LENGTH_LONG).show(); } Step 4 − Add the following code to manifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <uses-permission android:name = "android.permission.WAKE_LOCK"/> <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> <service android:name = ".service"/> </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 – In the above result is an initial screen, Click on Text view, it will start Notification service as shown below – In the above result, service is startd now click on text view, it will stop notification service as shown below - Click here to download the project code
[ { "code": null, "e": 1246, "s": 1062, "text": "Before getting into example, we should know what service is in android. Service is going to do back ground operation without interact with UI and it works even after activity destroy." }, { "code": null, "e": 1340, "s": 1246, "text": "This example demonstrate about How can I create an android service that dalvik will not kill." }, { "code": null, "e": 1469, "s": 1340, "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": 1534, "s": 1469, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2375, "s": 1534, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:text = \"Start Service\"\n android:textSize = \"25sp\"\n app:layout_constraintBottom_toBottomOf = \"parent\"\n app:layout_constraintLeft_toLeftOf = \"parent\"\n app:layout_constraintRight_toRightOf = \"parent\"\n app:layout_constraintTop_toTopOf = \"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2489, "s": 2375, "text": "In the above code, we have taken text view, when user click on text view, it will start service and stop service." }, { "code": null, "e": 2546, "s": 2489, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3977, "s": 2546, "text": "package com.example.andy.myapplication;\nimport android.app.ActivityManager;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView text = findViewById(R.id.text);\n text.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (isMyServiceRunning(service.class)) {\n text.setText(\"Stoped\");\n stopService(new Intent(MainActivity.this, service.class));\n } else {\n text.setText(\"Started\");\n startService(new Intent(MainActivity.this, service.class));\n }\n }\n });\n }\n private boolean isMyServiceRunning(Class<?> serviceClass) {\n ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);\n for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {\n if (serviceClass.getName().equals(service.service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n}" }, { "code": null, "e": 4171, "s": 3977, "text": "In the above code to start and stop service. We have used intent and passed context and service class. Now create a service class in package folder as service.class and add the following code –" }, { "code": null, "e": 5858, "s": 4171, "text": "package com.example.andy.myapplication;\nimport android.annotation.SuppressLint;\nimport android.annotation.TargetApi;\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.app.PendingIntent;\nimport android.app.Service;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.graphics.Color;\nimport android.media.MediaPlayer;\nimport android.os.Build;\nimport android.os.IBinder;\nimport android.os.PowerManager;\nimport android.support.annotation.RequiresApi;\nimport android.support.v4.app.NotificationCompat;\nimport android.util.Log;\nimport android.widget.Toast;\npublic class service extends Service {\n PowerManager pm;\n @SuppressLint(\"InvalidWakeLockTag\")\n PowerManager.WakeLock wl;\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n @SuppressLint(\"InvalidWakeLockTag\")\n @Override\n public void onCreate() {\n super.onCreate();\n pm = (PowerManager) getSystemService(Context.POWER_SERVICE);\n wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, \"My Tag\");\n }\n @TargetApi(Build.VERSION_CODES.O)\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n wl.acquire();\n //Do some task\n Toast.makeText(this, \"Notification Service started by user.\", Toast.LENGTH_LONG).show();\n return START_STICKY;\n }\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n public void onDestroy() {\n super.onDestroy();\n wl.release();\n Toast.makeText(this, \"Notification Service destroyed by user.\", Toast.LENGTH_LONG).show();\n }\n}" }, { "code": null, "e": 5997, "s": 5858, "text": "In the above code we have called power manager to stop screen lock so android thread not going to stop the service thread as shown below –" }, { "code": null, "e": 6752, "s": 5997, "text": "@SuppressLint(\"InvalidWakeLockTag\")\n@Override\npublic void onCreate() {\n super.onCreate();\n pm = (PowerManager) getSystemService(Context.POWER_SERVICE);\n wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, \"My Tag\");\n}\n@TargetApi(Build.VERSION_CODES.O)\n@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n@Override\npublic int onStartCommand(Intent intent, int flags, int startId) {\n wl.acquire();\n //Do some task\n Toast.makeText(this, \"Notification Service started by user.\", Toast.LENGTH_LONG).show();\n return START_STICKY;\n}\n@RequiresApi(api = Build.VERSION_CODES.N)\n@Override\npublic void onDestroy() {\n super.onDestroy();\n wl.release();\n Toast.makeText(this, \"Notification Service destroyed by user.\", Toast.LENGTH_LONG).show();\n}" }, { "code": null, "e": 6800, "s": 6752, "text": "Step 4 − Add the following code to manifest.xml" }, { "code": null, "e": 7626, "s": 6800, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.andy.myapplication\">\n <uses-permission android:name = \"android.permission.WAKE_LOCK\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <service android:name = \".service\"/>\n </application>\n</manifest>" }, { "code": null, "e": 7973, "s": 7626, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 8087, "s": 7973, "text": "In the above result is an initial screen, Click on Text view, it will start Notification service as shown below –" }, { "code": null, "e": 8201, "s": 8087, "text": "In the above result, service is startd now click on text view, it will stop notification service as shown below -" }, { "code": null, "e": 8241, "s": 8201, "text": "Click here to download the project code" } ]
Operations on struct variables in C - GeeksforGeeks
16 Jan, 2019 In C, the only operation that can be applied to struct variables is assignment. Any other operation (e.g. equality check) is not allowed on struct variables.For example, program 1 works without any error and program 2 fails in compilation. Program 1 #include <stdio.h> struct Point { int x; int y;}; int main(){ struct Point p1 = {10, 20}; struct Point p2 = p1; // works: contents of p1 are copied to p2 printf(" p2.x = %d, p2.y = %d", p2.x, p2.y); getchar(); return 0;} Program 2 #include <stdio.h> struct Point { int x; int y;}; int main(){ struct Point p1 = {10, 20}; struct Point p2 = p1; // works: contents of p1 are copied to p2 if (p1 == p2) // compiler error: cannot do equality check for // whole structures { printf("p1 and p2 are same "); } getchar(); return 0;} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Kaalan C-Struct-Union-Enum C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments rand() and srand() in C/C++ fork() in C Core Dump (Segmentation fault) in C/C++ Left Shift and Right Shift Operators in C/C++ Command line arguments in C/C++ Different methods to reverse a string in C/C++ Substring in C++ Function Pointer in C TCP Server-Client implementation in C Enumeration (or enum) in C
[ { "code": null, "e": 24396, "s": 24368, "text": "\n16 Jan, 2019" }, { "code": null, "e": 24636, "s": 24396, "text": "In C, the only operation that can be applied to struct variables is assignment. Any other operation (e.g. equality check) is not allowed on struct variables.For example, program 1 works without any error and program 2 fails in compilation." }, { "code": null, "e": 24646, "s": 24636, "text": "Program 1" }, { "code": "#include <stdio.h> struct Point { int x; int y;}; int main(){ struct Point p1 = {10, 20}; struct Point p2 = p1; // works: contents of p1 are copied to p2 printf(\" p2.x = %d, p2.y = %d\", p2.x, p2.y); getchar(); return 0;}", "e": 24876, "s": 24646, "text": null }, { "code": null, "e": 24886, "s": 24876, "text": "Program 2" }, { "code": "#include <stdio.h> struct Point { int x; int y;}; int main(){ struct Point p1 = {10, 20}; struct Point p2 = p1; // works: contents of p1 are copied to p2 if (p1 == p2) // compiler error: cannot do equality check for // whole structures { printf(\"p1 and p2 are same \"); } getchar(); return 0;}", "e": 25220, "s": 24886, "text": null }, { "code": null, "e": 25345, "s": 25220, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 25352, "s": 25345, "text": "Kaalan" }, { "code": null, "e": 25372, "s": 25352, "text": "C-Struct-Union-Enum" }, { "code": null, "e": 25383, "s": 25372, "text": "C Language" }, { "code": null, "e": 25481, "s": 25383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25490, "s": 25481, "text": "Comments" }, { "code": null, "e": 25503, "s": 25490, "text": "Old Comments" }, { "code": null, "e": 25531, "s": 25503, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 25543, "s": 25531, "text": "fork() in C" }, { "code": null, "e": 25583, "s": 25543, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 25629, "s": 25583, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 25661, "s": 25629, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25708, "s": 25661, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 25725, "s": 25708, "text": "Substring in C++" }, { "code": null, "e": 25747, "s": 25725, "text": "Function Pointer in C" }, { "code": null, "e": 25785, "s": 25747, "text": "TCP Server-Client implementation in C" } ]
Python – List Comprehension
13 May, 2022 Python is renowned for encouraging developers and programmers to write efficient, easy-to-understand, and almost as simple-to-read code. One of the most distinctive aspects of the language is the python list and the list compression feature, which one can use within a single line of code to construct powerful functionality. List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Syntax: newList = [ expression(element) for element in oldList if condition ] More time-efficient and space-efficient than loops. Require fewer lines of code. Transforms iterative statement into a formula. There are various ways to iterate through a list. However, the most common approach is to use the for loop. Let us look at the below example: Python3 # Empty listList = [] # Traditional approach of iteratingfor character in 'Geeks 4 Geeks!': List.append(character) # Display listprint(List) Output: [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘4’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘!’] Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc. Now list comprehension does the same task and also makes the program more simple. List Comprehensions translate the traditional iteration approach using for loop into a simple formula hence making them easy to use. Below is the approach to iterate through a list, string, tuple, etc. using list comprehension. Python3 # Using list comprehension to iterate through loopList = [character for character in 'Geeks 4 Geeks!'] # Displaying listprint(List) Output: [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘4’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘!’] The list comprehensions are more efficient both computationally and in terms of coding space and time than a for loop. Typically, they are written in a single line of code. The below program depicts the difference between for loops and list comprehension based on performance. Python3 # Import required moduleimport time # define function to implement for loopdef for_loop(n): result = [] for i in range(n): result.append(i**2) return result # define function to implement list comprehensiondef list_comprehension(n): return [i**2 for i in range(n)] # Driver Code # Calculate time takens by for_loop()begin = time.time()for_loop(10**6)end = time.time() # Display time taken by for_loop()print('Time taken for_loop:',round(end-begin,2)) # Calculate time takens by list_comprehension()begin = time.time()list_comprehension(10**6)end = time.time() # Display time taken by for_loop()print('Time taken for list_comprehension:',round(end-begin,2)) Output: Time taken for_loop: 0.56 Time taken for list_comprehension: 0.47 From the above program, we can see list comprehensions are quite faster than for loop. Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Below is the program which implements nested loop: Python3 matrix = [] for i in range(3): # Append an empty sublist inside the list matrix.append([]) for j in range(5): matrix[i].append(j) print(matrix) [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] Now by using nested list comprehensions same output can be generated in fewer lines of code. Python3 # Nested list comprehensionmatrix = [[j for j in range(5)] for i in range(3)] print(matrix) [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] Lambda Expressions are nothing but shorthand representations of Python functions. Using list comprehensions with lambda creates an efficient combination. Let us look at the below examples: Python3 # using lambda to print table of 10numbers = [] for i in range(1, 6): numbers.append(i*10) print(numbers) [10, 20, 30, 40, 50] Here, we have used for loop to print a table of 10. Python3 numbers= [i*10 for i in range(1,6)] print(numbers) Output: [10, 20, 30, 40, 50] Now here, we have used only list comprehension to display a table of 10. Python3 # using lambda to print table of 10numbers = list(map(lambda i: i*10, [i for i in range(1,6)])) print(numbers) Output: [10, 20, 30, 40, 50] Finally, we use lambda + list comprehension to display the table of 10. This combination is very useful to get efficient solutions in fewer lines of code for complex problems. We can also add conditional statements to the list comprehension. We can create a list using range(), operators, etc. and cal also apply some conditions to the list using the if statement. Below are some examples which depict the use of list comprehensions rather than the traditional approach to iterate through iterables: Python3 # Getting square of from 1 to 10squares = [n**2 for n in range(1, 11)] # Display square of even numbersprint(squares) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Python3 # Assign matrixtwoDMatrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] # Generate transposetrans = [[i[j] for i in twoDMatrix] for j in range(len(twoDMatrix))] print(trans) Output: [[10, 40, 70], [20, 50, 80], [30, 60, 90]] Python3 # Initializing stringstring = 'Geeks4Geeks' # Toggle case of each characterList = list(map(lambda i: chr(ord(i)^32), string)) # Display listprint(List) ['g', 'E', 'E', 'K', 'S', '\x14', 'g', 'E', 'E', 'K', 'S'] Python3 # Reverse each string in tupleList = [string[::-1] for string in ('Geeks', 'for', 'Geeks')] # Display listprint(List) Output: ['skeeG', 'rof', 'skeeG'] Python3 # Explicit functiondef digitSum(n): dsum = 0 for ele in str(n): dsum += int(ele) return dsum # Initializing listList = [367, 111, 562, 945, 6726, 873] # Using the function on odd elements of the listnewList = [digitSum(i) for i in List if i & 1] # Displaying new listprint(newList) Output: [16, 3, 18, 18] Comprehension of the list is an effective means of describing and constructing lists based on current lists. Generally, list comprehension is more lightweight and simpler than standard list formation functions and loops. We should not write long codes for list comprehensions in order to ensure user-friendly code. Every comprehension of the list can be rewritten in for loop, but in the context of list interpretation, every for loop can not be rewritten. riturajsaha nikhilaggarwal3 temope1626 AyushGupta8 python-list Technical Scripter 2020 Python Technical Scripter python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n13 May, 2022" }, { "code": null, "e": 378, "s": 52, "text": "Python is renowned for encouraging developers and programmers to write efficient, easy-to-understand, and almost as simple-to-read code. One of the most distinctive aspects of the language is the python list and the list compression feature, which one can use within a single line of code to construct powerful functionality." }, { "code": null, "e": 652, "s": 378, "text": "List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. " }, { "code": null, "e": 660, "s": 652, "text": "Syntax:" }, { "code": null, "e": 731, "s": 660, "text": "newList = [ expression(element) for element in oldList if condition ] " }, { "code": null, "e": 783, "s": 731, "text": "More time-efficient and space-efficient than loops." }, { "code": null, "e": 812, "s": 783, "text": "Require fewer lines of code." }, { "code": null, "e": 859, "s": 812, "text": "Transforms iterative statement into a formula." }, { "code": null, "e": 1001, "s": 859, "text": "There are various ways to iterate through a list. However, the most common approach is to use the for loop. Let us look at the below example:" }, { "code": null, "e": 1009, "s": 1001, "text": "Python3" }, { "code": "# Empty listList = [] # Traditional approach of iteratingfor character in 'Geeks 4 Geeks!': List.append(character) # Display listprint(List)", "e": 1153, "s": 1009, "text": null }, { "code": null, "e": 1161, "s": 1153, "text": "Output:" }, { "code": null, "e": 1232, "s": 1161, "text": "[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘4’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘!’]" }, { "code": null, "e": 1418, "s": 1232, "text": "Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc. Now list comprehension does the same task and also makes the program more simple. " }, { "code": null, "e": 1646, "s": 1418, "text": "List Comprehensions translate the traditional iteration approach using for loop into a simple formula hence making them easy to use. Below is the approach to iterate through a list, string, tuple, etc. using list comprehension." }, { "code": null, "e": 1654, "s": 1646, "text": "Python3" }, { "code": "# Using list comprehension to iterate through loopList = [character for character in 'Geeks 4 Geeks!'] # Displaying listprint(List)", "e": 1786, "s": 1654, "text": null }, { "code": null, "e": 1794, "s": 1786, "text": "Output:" }, { "code": null, "e": 1865, "s": 1794, "text": "[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘, ‘4’, ‘ ‘, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘!’]" }, { "code": null, "e": 2142, "s": 1865, "text": "The list comprehensions are more efficient both computationally and in terms of coding space and time than a for loop. Typically, they are written in a single line of code. The below program depicts the difference between for loops and list comprehension based on performance." }, { "code": null, "e": 2150, "s": 2142, "text": "Python3" }, { "code": "# Import required moduleimport time # define function to implement for loopdef for_loop(n): result = [] for i in range(n): result.append(i**2) return result # define function to implement list comprehensiondef list_comprehension(n): return [i**2 for i in range(n)] # Driver Code # Calculate time takens by for_loop()begin = time.time()for_loop(10**6)end = time.time() # Display time taken by for_loop()print('Time taken for_loop:',round(end-begin,2)) # Calculate time takens by list_comprehension()begin = time.time()list_comprehension(10**6)end = time.time() # Display time taken by for_loop()print('Time taken for list_comprehension:',round(end-begin,2))", "e": 2830, "s": 2150, "text": null }, { "code": null, "e": 2838, "s": 2830, "text": "Output:" }, { "code": null, "e": 2904, "s": 2838, "text": "Time taken for_loop: 0.56\nTime taken for list_comprehension: 0.47" }, { "code": null, "e": 2991, "s": 2904, "text": "From the above program, we can see list comprehensions are quite faster than for loop." }, { "code": null, "e": 3184, "s": 2991, "text": "Nested List Comprehensions are nothing but a list comprehension within another list comprehension which is quite similar to nested for loops. Below is the program which implements nested loop:" }, { "code": null, "e": 3192, "s": 3184, "text": "Python3" }, { "code": "matrix = [] for i in range(3): # Append an empty sublist inside the list matrix.append([]) for j in range(5): matrix[i].append(j) print(matrix)", "e": 3370, "s": 3192, "text": null }, { "code": null, "e": 3423, "s": 3370, "text": "[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]\n" }, { "code": null, "e": 3516, "s": 3423, "text": "Now by using nested list comprehensions same output can be generated in fewer lines of code." }, { "code": null, "e": 3524, "s": 3516, "text": "Python3" }, { "code": "# Nested list comprehensionmatrix = [[j for j in range(5)] for i in range(3)] print(matrix)", "e": 3616, "s": 3524, "text": null }, { "code": null, "e": 3669, "s": 3616, "text": "[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]\n" }, { "code": null, "e": 3858, "s": 3669, "text": "Lambda Expressions are nothing but shorthand representations of Python functions. Using list comprehensions with lambda creates an efficient combination. Let us look at the below examples:" }, { "code": null, "e": 3866, "s": 3858, "text": "Python3" }, { "code": "# using lambda to print table of 10numbers = [] for i in range(1, 6): numbers.append(i*10) print(numbers)", "e": 3975, "s": 3866, "text": null }, { "code": null, "e": 3997, "s": 3975, "text": "[10, 20, 30, 40, 50]\n" }, { "code": null, "e": 4049, "s": 3997, "text": "Here, we have used for loop to print a table of 10." }, { "code": null, "e": 4057, "s": 4049, "text": "Python3" }, { "code": "numbers= [i*10 for i in range(1,6)] print(numbers)", "e": 4108, "s": 4057, "text": null }, { "code": null, "e": 4117, "s": 4108, "text": " Output:" }, { "code": null, "e": 4138, "s": 4117, "text": "[10, 20, 30, 40, 50]" }, { "code": null, "e": 4212, "s": 4138, "text": " Now here, we have used only list comprehension to display a table of 10." }, { "code": null, "e": 4220, "s": 4212, "text": "Python3" }, { "code": "# using lambda to print table of 10numbers = list(map(lambda i: i*10, [i for i in range(1,6)])) print(numbers)", "e": 4331, "s": 4220, "text": null }, { "code": null, "e": 4339, "s": 4331, "text": "Output:" }, { "code": null, "e": 4360, "s": 4339, "text": "[10, 20, 30, 40, 50]" }, { "code": null, "e": 4536, "s": 4360, "text": "Finally, we use lambda + list comprehension to display the table of 10. This combination is very useful to get efficient solutions in fewer lines of code for complex problems." }, { "code": null, "e": 4725, "s": 4536, "text": "We can also add conditional statements to the list comprehension. We can create a list using range(), operators, etc. and cal also apply some conditions to the list using the if statement." }, { "code": null, "e": 4860, "s": 4725, "text": "Below are some examples which depict the use of list comprehensions rather than the traditional approach to iterate through iterables:" }, { "code": null, "e": 4868, "s": 4860, "text": "Python3" }, { "code": "# Getting square of from 1 to 10squares = [n**2 for n in range(1, 11)] # Display square of even numbersprint(squares)", "e": 4986, "s": 4868, "text": null }, { "code": null, "e": 5026, "s": 4986, "text": "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\n" }, { "code": null, "e": 5034, "s": 5026, "text": "Python3" }, { "code": "# Assign matrixtwoDMatrix = [[10, 20, 30], [40, 50, 60], [70, 80, 90]] # Generate transposetrans = [[i[j] for i in twoDMatrix] for j in range(len(twoDMatrix))] print(trans)", "e": 5233, "s": 5034, "text": null }, { "code": null, "e": 5241, "s": 5233, "text": "Output:" }, { "code": null, "e": 5284, "s": 5241, "text": "[[10, 40, 70], [20, 50, 80], [30, 60, 90]]" }, { "code": null, "e": 5292, "s": 5284, "text": "Python3" }, { "code": "# Initializing stringstring = 'Geeks4Geeks' # Toggle case of each characterList = list(map(lambda i: chr(ord(i)^32), string)) # Display listprint(List)", "e": 5444, "s": 5292, "text": null }, { "code": null, "e": 5504, "s": 5444, "text": "['g', 'E', 'E', 'K', 'S', '\\x14', 'g', 'E', 'E', 'K', 'S']\n" }, { "code": null, "e": 5512, "s": 5504, "text": "Python3" }, { "code": "# Reverse each string in tupleList = [string[::-1] for string in ('Geeks', 'for', 'Geeks')] # Display listprint(List)", "e": 5630, "s": 5512, "text": null }, { "code": null, "e": 5638, "s": 5630, "text": "Output:" }, { "code": null, "e": 5664, "s": 5638, "text": "['skeeG', 'rof', 'skeeG']" }, { "code": null, "e": 5672, "s": 5664, "text": "Python3" }, { "code": "# Explicit functiondef digitSum(n): dsum = 0 for ele in str(n): dsum += int(ele) return dsum # Initializing listList = [367, 111, 562, 945, 6726, 873] # Using the function on odd elements of the listnewList = [digitSum(i) for i in List if i & 1] # Displaying new listprint(newList)", "e": 5971, "s": 5672, "text": null }, { "code": null, "e": 5979, "s": 5971, "text": "Output:" }, { "code": null, "e": 5995, "s": 5979, "text": "[16, 3, 18, 18]" }, { "code": null, "e": 6104, "s": 5995, "text": "Comprehension of the list is an effective means of describing and constructing lists based on current lists." }, { "code": null, "e": 6216, "s": 6104, "text": "Generally, list comprehension is more lightweight and simpler than standard list formation functions and loops." }, { "code": null, "e": 6310, "s": 6216, "text": "We should not write long codes for list comprehensions in order to ensure user-friendly code." }, { "code": null, "e": 6452, "s": 6310, "text": "Every comprehension of the list can be rewritten in for loop, but in the context of list interpretation, every for loop can not be rewritten." }, { "code": null, "e": 6464, "s": 6452, "text": "riturajsaha" }, { "code": null, "e": 6480, "s": 6464, "text": "nikhilaggarwal3" }, { "code": null, "e": 6491, "s": 6480, "text": "temope1626" }, { "code": null, "e": 6503, "s": 6491, "text": "AyushGupta8" }, { "code": null, "e": 6515, "s": 6503, "text": "python-list" }, { "code": null, "e": 6539, "s": 6515, "text": "Technical Scripter 2020" }, { "code": null, "e": 6546, "s": 6539, "text": "Python" }, { "code": null, "e": 6565, "s": 6546, "text": "Technical Scripter" }, { "code": null, "e": 6577, "s": 6565, "text": "python-list" }, { "code": null, "e": 6675, "s": 6577, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6707, "s": 6675, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6734, "s": 6707, "text": "Python Classes and Objects" }, { "code": null, "e": 6755, "s": 6734, "text": "Python OOPs Concepts" }, { "code": null, "e": 6778, "s": 6755, "text": "Introduction To PYTHON" }, { "code": null, "e": 6834, "s": 6778, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6865, "s": 6834, "text": "Python | os.path.join() method" }, { "code": null, "e": 6907, "s": 6865, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6949, "s": 6907, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6988, "s": 6949, "text": "Python | Get unique values from a list" } ]
Go - Strings
Strings, which are widely used in Go programming, are a readonly slice of bytes. In the Go programming language, strings are slices. The Go platform provides various libraries to manipulate strings. unicode regexp strings The most direct way to create a string is to write − var greeting = "Hello world!" Whenever it encounters a string literal in your code, the compiler creates a string object with its value in this case, "Hello world!'. A string literal holds a valid UTF-8 sequences called runes. A String holds arbitrary bytes. package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("normal string: ") fmt.Printf("%s", greeting) fmt.Printf("\n") fmt.Printf("hex bytes: ") for i := 0; i < len(greeting); i++ { fmt.Printf("%x ", greeting[i]) } fmt.Printf("\n") const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" /*q flag escapes unprintable characters, with + flag it escapses non-ascii characters as well to make output unambigous */ fmt.Printf("quoted string: ") fmt.Printf("%+q", sampleText) fmt.Printf("\n") } This would produce the following result − normal string: Hello world! hex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 quoted string: "\xbd\xb2=\xbc \u2318" Note − The string literal is immutable, so that once it is created a string literal cannot be changed. len(str) method returns the number of bytes contained in the string literal. package main import "fmt" func main() { var greeting = "Hello world!" fmt.Printf("String Length is: ") fmt.Println(len(greeting)) } This would produce the following result − String Length is : 12 The strings package includes a method join for concatenating multiple strings − strings.Join(sample, " ") Join concatenates the elements of an array to create a single string. Second parameter is seperator which is placed between element of the array. Let us look at the following example − package main import ("fmt" "math" )"fmt" "strings") func main() { greetings := []string{"Hello","world!"} fmt.Println(strings.Join(greetings, " ")) } This would produce the following result − Hello world! 64 Lectures 6.5 hours Ridhi Arora 20 Lectures 2.5 hours Asif Hussain 22 Lectures 4 hours Dilip Padmanabhan 48 Lectures 6 hours Arnab Chakraborty 7 Lectures 1 hours Aditya Kulkarni 44 Lectures 3 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2136, "s": 1937, "text": "Strings, which are widely used in Go programming, are a readonly slice of bytes. In the Go programming language, strings are slices. The Go platform provides various libraries to manipulate strings." }, { "code": null, "e": 2144, "s": 2136, "text": "unicode" }, { "code": null, "e": 2151, "s": 2144, "text": "regexp" }, { "code": null, "e": 2159, "s": 2151, "text": "strings" }, { "code": null, "e": 2212, "s": 2159, "text": "The most direct way to create a string is to write −" }, { "code": null, "e": 2243, "s": 2212, "text": "var greeting = \"Hello world!\"\n" }, { "code": null, "e": 2379, "s": 2243, "text": "Whenever it encounters a string literal in your code, the compiler creates a string object with its value in this case, \"Hello world!'." }, { "code": null, "e": 2472, "s": 2379, "text": "A string literal holds a valid UTF-8 sequences called runes. A String holds arbitrary bytes." }, { "code": null, "e": 3057, "s": 2472, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var greeting = \"Hello world!\"\n \n fmt.Printf(\"normal string: \")\n fmt.Printf(\"%s\", greeting)\n fmt.Printf(\"\\n\")\n fmt.Printf(\"hex bytes: \")\n \n for i := 0; i < len(greeting); i++ {\n fmt.Printf(\"%x \", greeting[i])\n }\n \n fmt.Printf(\"\\n\")\n const sampleText = \"\\xbd\\xb2\\x3d\\xbc\\x20\\xe2\\x8c\\x98\" \n \n /*q flag escapes unprintable characters, with + flag it escapses non-ascii \n characters as well to make output unambigous */\n fmt.Printf(\"quoted string: \")\n fmt.Printf(\"%+q\", sampleText)\n fmt.Printf(\"\\n\") \n}" }, { "code": null, "e": 3099, "s": 3057, "text": "This would produce the following result −" }, { "code": null, "e": 3214, "s": 3099, "text": "normal string: Hello world!\nhex bytes: 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 \nquoted string: \"\\xbd\\xb2=\\xbc \\u2318\"\n" }, { "code": null, "e": 3317, "s": 3214, "text": "Note − The string literal is immutable, so that once it is created a string literal cannot be changed." }, { "code": null, "e": 3394, "s": 3317, "text": "len(str) method returns the number of bytes contained in the string literal." }, { "code": null, "e": 3544, "s": 3394, "text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var greeting = \"Hello world!\"\n \n fmt.Printf(\"String Length is: \")\n fmt.Println(len(greeting)) \n}" }, { "code": null, "e": 3586, "s": 3544, "text": "This would produce the following result −" }, { "code": null, "e": 3609, "s": 3586, "text": "String Length is : 12\n" }, { "code": null, "e": 3689, "s": 3609, "text": "The strings package includes a method join for concatenating multiple strings −" }, { "code": null, "e": 3716, "s": 3689, "text": "strings.Join(sample, \" \")\n" }, { "code": null, "e": 3862, "s": 3716, "text": "Join concatenates the elements of an array to create a single string. Second parameter is seperator which is placed between element of the array." }, { "code": null, "e": 3901, "s": 3862, "text": "Let us look at the following example −" }, { "code": null, "e": 4063, "s": 3901, "text": "package main\n\nimport (\"fmt\" \"math\" )\"fmt\" \"strings\")\n\nfunc main() {\n greetings := []string{\"Hello\",\"world!\"} \n fmt.Println(strings.Join(greetings, \" \"))\n}" }, { "code": null, "e": 4105, "s": 4063, "text": "This would produce the following result −" }, { "code": null, "e": 4119, "s": 4105, "text": "Hello world!\n" }, { "code": null, "e": 4154, "s": 4119, "text": "\n 64 Lectures \n 6.5 hours \n" }, { "code": null, "e": 4167, "s": 4154, "text": " Ridhi Arora" }, { "code": null, "e": 4202, "s": 4167, "text": "\n 20 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4216, "s": 4202, "text": " Asif Hussain" }, { "code": null, "e": 4249, "s": 4216, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 4268, "s": 4249, "text": " Dilip Padmanabhan" }, { "code": null, "e": 4301, "s": 4268, "text": "\n 48 Lectures \n 6 hours \n" }, { "code": null, "e": 4320, "s": 4301, "text": " Arnab Chakraborty" }, { "code": null, "e": 4352, "s": 4320, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 4369, "s": 4352, "text": " Aditya Kulkarni" }, { "code": null, "e": 4402, "s": 4369, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 4421, "s": 4402, "text": " Arnab Chakraborty" }, { "code": null, "e": 4428, "s": 4421, "text": " Print" }, { "code": null, "e": 4439, "s": 4428, "text": " Add Notes" } ]
What is the difference between HTML tags <div> and <span>?
Both <div> and <span> is used to define parts of a web page. The <span> element shows the inline portion of a document. The <div> elements show a block-level portion of a document. A div is a block-level element and a span is an inline element. The div should be used to wrap sections of a document, while use spans to wrap small portions of text, images, etc. Here’s an example: <div>Demo Text, with <span>some other</span> text.</div> The <div> element is used while creating CSS based layouts in html, whereas <span> element is used to stylize texts.
[ { "code": null, "e": 1243, "s": 1062, "text": "Both <div> and <span> is used to define parts of a web page. The <span> element shows the inline portion of a document. The <div> elements show a block-level portion of a document." }, { "code": null, "e": 1307, "s": 1243, "text": "A div is a block-level element and a span is an inline element." }, { "code": null, "e": 1423, "s": 1307, "text": "The div should be used to wrap sections of a document, while use spans to wrap small portions of text, images, etc." }, { "code": null, "e": 1442, "s": 1423, "text": "Here’s an example:" }, { "code": null, "e": 1499, "s": 1442, "text": "<div>Demo Text, with <span>some other</span> text.</div>" }, { "code": null, "e": 1616, "s": 1499, "text": "The <div> element is used while creating CSS based layouts in html, whereas <span> element is used to stylize texts." } ]
Generate Subtitles for any video file using Mozilla DeepSpeech | by Abhiroop Talasila | Towards Data Science
In the age of OTT platforms, there are still some who prefer to download movies/videos from YouTube/Facebook/Torrents (shush 🤫) over streaming. I am one of them and on one such occasion, I couldn’t find the subtitle file for a particular movie I had downloaded. Then, the idea for AutoSub struck me and since I had worked with DeepSpeech previously, I decided to use it to generate subtitles for my movie. Given a video file as input, my goal was to generate an .srt file. The subtitles could then be imported into any modern video player. In this article, I’m going to walk you through some of the code. You can find the project on my GitHub here with instructions on how to install locally. Prerequisites: Intermediate understanding of Python, some familiarity with Automatic Speech Recognition Engines, and a basic understanding of signal processing will be great. Note: This is my first article on Medium. If you have any suggestions/doubts please comment them down. Happy reading :) DeepSpeech is an open-source speech-to-text engine based on the original Deep Speech research paper by Baidu. It is one of the best speech recognition tools out there given its versatility and ease of use. It is built using Tensorflow, is trainable using custom datasets, trained on the huge Mozilla Common Voice dataset, and is licensed under the Mozilla Public License. The best advantage is that we can download the model files and perform inference locally just within a couple of minutes! Although, DeepSpeech does have its issues. The model struggles with non-native English accent speech. There is a workaround to this — fine-tuning the model using a custom dataset in the language we want to predict. I’ll write another article on how to do that soon. If you’re working with speech recognition tasks, I strongly recommend you have a look at DeepSpeech. Let’s start off by installing some packages we’ll be needing. All commands have been tested on Ubuntu 18.04 in a pip virtual environment. FFmpeg: FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter, and play pretty much anything that humans and machines have created. We need it to extract audio from our input video file. FFmpeg: FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter, and play pretty much anything that humans and machines have created. We need it to extract audio from our input video file. $ sudo apt-get install ffmpeg 2. DeepSpeech: Install the python package from PyPI and download the model file. The scorer file is optional but greatly increases accuracy. $ pip install deepspeech==0.8.2# Model file (~190 MB) $ wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.pbmm# Scorer file (~900 MB)$ wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.scorer Now that we’re all set up, let’s first extract the audio from our input video file using FFmpeg. We need to create a subprocess to run UNIX commands. DeepSpeech expects the input audio file to be sampled at 16kHz and hence the arguments to ffmpeg given below. Now, suppose our input video file is 2 hours long. Running DeepSpeech inference on the whole file is not generally recommended. I’ve tried it and it didn’t work out too well. One workaround to this is to split the audio file on silent segments. After splitting, we have multiple small files containing speech which we need to infer. This is done using pyAudioAnalysis. The following function uses the functions read_audio_file() and silenceRemoval() from pyAudioAnalysis and generates segment limits from where speech begins and ends. The arguments control the smoothing window size in seconds and weight factor in (0,1). Using the segment limits, smaller audio files are written to disk. We now need to run DeepSpeech inference on these files individually and write the inferred text to a SRT file. Let’s start by creating an instance of the DeepSpeech Model and add the scorer file. We then read the audio file into a NumPy array and feed it into the speech-to-text function to produce inference. As mentioned above, pyAudioAnalysis saves files with the segment limits time in seconds. We need to extract those limits and convert it into a suitable form before writing to the SRT file. The write function is defined here. The whole process shouldn’t take more than 60% of the original video file duration. Here’s a video showing a sample run on my laptop. There’s one more area I hope to improve in the future. The inferred text is unformatted. We need to add proper punctuation, correct possible small mistakes in words (off by one letter), and split very long segments into smaller ones (although this will be difficult to automate). That’s it! If you’ve reached till here, thank you for sticking along :) You can find me here: LinkedIn, GitHub
[ { "code": null, "e": 578, "s": 172, "text": "In the age of OTT platforms, there are still some who prefer to download movies/videos from YouTube/Facebook/Torrents (shush 🤫) over streaming. I am one of them and on one such occasion, I couldn’t find the subtitle file for a particular movie I had downloaded. Then, the idea for AutoSub struck me and since I had worked with DeepSpeech previously, I decided to use it to generate subtitles for my movie." }, { "code": null, "e": 865, "s": 578, "text": "Given a video file as input, my goal was to generate an .srt file. The subtitles could then be imported into any modern video player. In this article, I’m going to walk you through some of the code. You can find the project on my GitHub here with instructions on how to install locally." }, { "code": null, "e": 1040, "s": 865, "text": "Prerequisites: Intermediate understanding of Python, some familiarity with Automatic Speech Recognition Engines, and a basic understanding of signal processing will be great." }, { "code": null, "e": 1160, "s": 1040, "text": "Note: This is my first article on Medium. If you have any suggestions/doubts please comment them down. Happy reading :)" }, { "code": null, "e": 1654, "s": 1160, "text": "DeepSpeech is an open-source speech-to-text engine based on the original Deep Speech research paper by Baidu. It is one of the best speech recognition tools out there given its versatility and ease of use. It is built using Tensorflow, is trainable using custom datasets, trained on the huge Mozilla Common Voice dataset, and is licensed under the Mozilla Public License. The best advantage is that we can download the model files and perform inference locally just within a couple of minutes!" }, { "code": null, "e": 1920, "s": 1654, "text": "Although, DeepSpeech does have its issues. The model struggles with non-native English accent speech. There is a workaround to this — fine-tuning the model using a custom dataset in the language we want to predict. I’ll write another article on how to do that soon." }, { "code": null, "e": 2021, "s": 1920, "text": "If you’re working with speech recognition tasks, I strongly recommend you have a look at DeepSpeech." }, { "code": null, "e": 2159, "s": 2021, "text": "Let’s start off by installing some packages we’ll be needing. All commands have been tested on Ubuntu 18.04 in a pip virtual environment." }, { "code": null, "e": 2398, "s": 2159, "text": "FFmpeg: FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter, and play pretty much anything that humans and machines have created. We need it to extract audio from our input video file." }, { "code": null, "e": 2637, "s": 2398, "text": "FFmpeg: FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter, and play pretty much anything that humans and machines have created. We need it to extract audio from our input video file." }, { "code": null, "e": 2667, "s": 2637, "text": "$ sudo apt-get install ffmpeg" }, { "code": null, "e": 2808, "s": 2667, "text": "2. DeepSpeech: Install the python package from PyPI and download the model file. The scorer file is optional but greatly increases accuracy." }, { "code": null, "e": 3084, "s": 2808, "text": "$ pip install deepspeech==0.8.2# Model file (~190 MB) $ wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.pbmm# Scorer file (~900 MB)$ wget https://github.com/mozilla/DeepSpeech/releases/download/v0.8.2/deepspeech-0.8.2-models.scorer" }, { "code": null, "e": 3344, "s": 3084, "text": "Now that we’re all set up, let’s first extract the audio from our input video file using FFmpeg. We need to create a subprocess to run UNIX commands. DeepSpeech expects the input audio file to be sampled at 16kHz and hence the arguments to ffmpeg given below." }, { "code": null, "e": 3713, "s": 3344, "text": "Now, suppose our input video file is 2 hours long. Running DeepSpeech inference on the whole file is not generally recommended. I’ve tried it and it didn’t work out too well. One workaround to this is to split the audio file on silent segments. After splitting, we have multiple small files containing speech which we need to infer. This is done using pyAudioAnalysis." }, { "code": null, "e": 4033, "s": 3713, "text": "The following function uses the functions read_audio_file() and silenceRemoval() from pyAudioAnalysis and generates segment limits from where speech begins and ends. The arguments control the smoothing window size in seconds and weight factor in (0,1). Using the segment limits, smaller audio files are written to disk." }, { "code": null, "e": 4568, "s": 4033, "text": "We now need to run DeepSpeech inference on these files individually and write the inferred text to a SRT file. Let’s start by creating an instance of the DeepSpeech Model and add the scorer file. We then read the audio file into a NumPy array and feed it into the speech-to-text function to produce inference. As mentioned above, pyAudioAnalysis saves files with the segment limits time in seconds. We need to extract those limits and convert it into a suitable form before writing to the SRT file. The write function is defined here." }, { "code": null, "e": 4702, "s": 4568, "text": "The whole process shouldn’t take more than 60% of the original video file duration. Here’s a video showing a sample run on my laptop." }, { "code": null, "e": 4982, "s": 4702, "text": "There’s one more area I hope to improve in the future. The inferred text is unformatted. We need to add proper punctuation, correct possible small mistakes in words (off by one letter), and split very long segments into smaller ones (although this will be difficult to automate)." }, { "code": null, "e": 5054, "s": 4982, "text": "That’s it! If you’ve reached till here, thank you for sticking along :)" } ]
C/C++ Program to the Count Inversions in an array using Merge Sort?
The Count of inversions that take place to Sort the given array is known as inversion count. the inversion problem is a classical problem that can be solved using the merge sort Algorithm. in this problem v we will count all elements more than it to its left and add the count to output. ThisLogic is done inside merge function of merge sort. For understanding the topic better let us take an example. Let us consider two sub-arrays involved in merge process - Input: arr[] = { 1, 9, 6, 4, 5} Output: Inversion count is 5 Inversion count of an array Given an array, find the number of inversions of it. If (i < j) and (A[i] > A[j]) then the pair (i, j) is called an inversion of an array A. We need to count all such pairs in the arr For example, There are 5 inversions in the array (9,6), (9,4), (9,5), (6,4), (6,5) 1. Compare the values of the element with each other. 2. Increment the counter if the value at lower index is higher. 3. Display the result. #include <stdio.h> int Merge(int arr[], int aux[], int low, int mid, int high) { int k = low, i = low, j = mid + 1; int inversionCount = 0; while (i <= mid && j <= high) { if (arr[i] <= arr[j]) { aux[k++] = arr[i++]; } else { aux[k++] = arr[j++]; inversionCount += (mid - i + 1); // NOTE } } while (i <= mid) aux[k++] = arr[i++]; for (int i = low; i <= high; i++) arr[i] = aux[i]; return inversionCount; } int MergeSort(int arr[], int aux[], int low, int high) { if (high == low) // if run size == 1 return 0; int mid = (low + ((high - low) >> 1)); int inversionCount = 0; inversionCount += MergeSort(arr, aux, low, mid); inversionCount += MergeSort(arr, aux, mid + 1, high); inversionCount += Merge(arr, aux, low, mid, high); return inversionCount; } int main() { int arr[] = { 1, 9, 6, 4, 5 }; int N = 5; int aux[N]; for (int i = 0; i < N; i++) aux[i] = arr[i]; printf("Inversion count is %d", MergeSort(arr, aux, 0, N - 1)); return 0; }
[ { "code": null, "e": 1405, "s": 1062, "text": "The Count of inversions that take place to Sort the given array is known as inversion count. the inversion problem is a classical problem that can be solved using the merge sort Algorithm. in this problem v we will count all elements more than it to its left and add the count to output. ThisLogic is done inside merge function of merge sort." }, { "code": null, "e": 1523, "s": 1405, "text": "For understanding the topic better let us take an example. Let us consider two sub-arrays involved in merge process -" }, { "code": null, "e": 1588, "s": 1527, "text": "Input: arr[] = { 1, 9, 6, 4, 5}\nOutput: Inversion count is 5" }, { "code": null, "e": 1616, "s": 1588, "text": "Inversion count of an array" }, { "code": null, "e": 1800, "s": 1616, "text": "Given an array, find the number of inversions of it. If (i < j) and (A[i] > A[j]) then the pair (i, j) is called an inversion of an array A. We need to count all such pairs in the arr" }, { "code": null, "e": 1813, "s": 1800, "text": "For example," }, { "code": null, "e": 1849, "s": 1813, "text": "There are 5 inversions in the array" }, { "code": null, "e": 1883, "s": 1849, "text": "(9,6), (9,4), (9,5), (6,4), (6,5)" }, { "code": null, "e": 1937, "s": 1883, "text": "1. Compare the values of the element with each other." }, { "code": null, "e": 2001, "s": 1937, "text": "2. Increment the counter if the value at lower index is higher." }, { "code": null, "e": 2024, "s": 2001, "text": "3. Display the result." }, { "code": null, "e": 3090, "s": 2024, "text": "#include <stdio.h>\nint Merge(int arr[], int aux[], int low, int mid, int high) {\n int k = low, i = low, j = mid + 1;\n int inversionCount = 0;\n while (i <= mid && j <= high) {\n if (arr[i] <= arr[j]) {\n aux[k++] = arr[i++];\n } else {\n aux[k++] = arr[j++];\n inversionCount += (mid - i + 1); // NOTE\n }\n }\n while (i <= mid)\n aux[k++] = arr[i++];\n for (int i = low; i <= high; i++)\n arr[i] = aux[i];\n return inversionCount;\n}\nint MergeSort(int arr[], int aux[], int low, int high) {\n if (high == low) // if run size == 1\n return 0;\n int mid = (low + ((high - low) >> 1));\n int inversionCount = 0;\n inversionCount += MergeSort(arr, aux, low, mid);\n inversionCount += MergeSort(arr, aux, mid + 1, high);\n inversionCount += Merge(arr, aux, low, mid, high);\n return inversionCount;\n}\nint main() {\n int arr[] = { 1, 9, 6, 4, 5 };\n int N = 5;\n int aux[N];\n for (int i = 0; i < N; i++)\n aux[i] = arr[i];\n printf(\"Inversion count is %d\", MergeSort(arr, aux, 0, N - 1));\n return 0;\n}" } ]
Print all permutations of a string in Java - GeeksforGeeks
07 Mar, 2022 Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word.Examples: Input: str = “cd” Output: cd dcInput: str = “abb” Output: abb abb bab bba bab bba Approach: Write a recursive function that prints every permutation of the given string. Terminating condition will be when the passed string is empty.Below is the implementation of the above approach: Java // Java program to print all the permutations// of the given stringpublic class GFG { // Function to print all the permutations of str static void printPermutn(String str, String ans) { // If string is empty if (str.length() == 0) { System.out.print(ans + " "); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // Recursive call printPermutn(ros, ans + ch); } } // Driver code public static void main(String[] args) { String s = "abb"; printPermutn(s, ""); }} abb abb bab bba bab bba When the permutations need to be distinct.Examples: Input: str = “abb” Output: abb bab bba Input: str = “geek” Output: geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg Approach: Write a recursive function that print distinct permutations. Make a boolean array of size ’26’ which accounts the character being used. If the character has not been used then the recursive call will take place. Otherwise, don’t make any call. Terminating condition will be when the passed string is empty.Below is the implementation of the above approach: Java // Java program to print all the permutations// of the given stringpublic class GFG { // Function to print all the distinct // permutations of str static void printDistinctPermutn(String str, String ans) { // If string is empty if (str.length() == 0) { // print ans System.out.print(ans + " "); return; } // Make a boolean array of size '26' which // stores false by default and make true // at the position which alphabet is being // used boolean alpha[] = new boolean[26]; for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // If the character has not been used // then recursive call will take place. // Otherwise, there will be no recursive // call if (alpha[ch - 'a'] == false) printDistinctPermutn(ros, ans + ch); alpha[ch - 'a'] = true; } } // Driver code public static void main(String[] args) { String s = "geek"; printDistinctPermutn(s, ""); }} geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg nikhatkhan11 permutation Permutation and Combination Backtracking Recursion Strings Strings Recursion permutation Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tug of War Difference between Backtracking and Branch-N-Bound technique Perfect Sum Problem N-Queen Problem | Local Search using Hill climbing with random neighbour Find shortest safe route in a path with landmines Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number Write a program to reverse digits of a number Check if a number is Palindrome
[ { "code": null, "e": 24507, "s": 24479, "text": "\n07 Mar, 2022" }, { "code": null, "e": 24827, "s": 24507, "text": "Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word.Examples: " }, { "code": null, "e": 24911, "s": 24827, "text": "Input: str = “cd” Output: cd dcInput: str = “abb” Output: abb abb bab bba bab bba " }, { "code": null, "e": 25115, "s": 24913, "text": "Approach: Write a recursive function that prints every permutation of the given string. Terminating condition will be when the passed string is empty.Below is the implementation of the above approach: " }, { "code": null, "e": 25120, "s": 25115, "text": "Java" }, { "code": "// Java program to print all the permutations// of the given stringpublic class GFG { // Function to print all the permutations of str static void printPermutn(String str, String ans) { // If string is empty if (str.length() == 0) { System.out.print(ans + \" \"); return; } for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // Recursive call printPermutn(ros, ans + ch); } } // Driver code public static void main(String[] args) { String s = \"abb\"; printPermutn(s, \"\"); }}", "e": 25950, "s": 25120, "text": null }, { "code": null, "e": 25974, "s": 25950, "text": "abb abb bab bba bab bba" }, { "code": null, "e": 26030, "s": 25976, "text": "When the permutations need to be distinct.Examples: " }, { "code": null, "e": 26159, "s": 26030, "text": "Input: str = “abb” Output: abb bab bba Input: str = “geek” Output: geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg " }, { "code": null, "e": 26527, "s": 26159, "text": "Approach: Write a recursive function that print distinct permutations. Make a boolean array of size ’26’ which accounts the character being used. If the character has not been used then the recursive call will take place. Otherwise, don’t make any call. Terminating condition will be when the passed string is empty.Below is the implementation of the above approach: " }, { "code": null, "e": 26532, "s": 26527, "text": "Java" }, { "code": "// Java program to print all the permutations// of the given stringpublic class GFG { // Function to print all the distinct // permutations of str static void printDistinctPermutn(String str, String ans) { // If string is empty if (str.length() == 0) { // print ans System.out.print(ans + \" \"); return; } // Make a boolean array of size '26' which // stores false by default and make true // at the position which alphabet is being // used boolean alpha[] = new boolean[26]; for (int i = 0; i < str.length(); i++) { // ith character of str char ch = str.charAt(i); // Rest of the string after excluding // the ith character String ros = str.substring(0, i) + str.substring(i + 1); // If the character has not been used // then recursive call will take place. // Otherwise, there will be no recursive // call if (alpha[ch - 'a'] == false) printDistinctPermutn(ros, ans + ch); alpha[ch - 'a'] = true; } } // Driver code public static void main(String[] args) { String s = \"geek\"; printDistinctPermutn(s, \"\"); }}", "e": 27891, "s": 26532, "text": null }, { "code": null, "e": 27951, "s": 27891, "text": "geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg" }, { "code": null, "e": 27966, "s": 27953, "text": "nikhatkhan11" }, { "code": null, "e": 27978, "s": 27966, "text": "permutation" }, { "code": null, "e": 28006, "s": 27978, "text": "Permutation and Combination" }, { "code": null, "e": 28019, "s": 28006, "text": "Backtracking" }, { "code": null, "e": 28029, "s": 28019, "text": "Recursion" }, { "code": null, "e": 28037, "s": 28029, "text": "Strings" }, { "code": null, "e": 28045, "s": 28037, "text": "Strings" }, { "code": null, "e": 28055, "s": 28045, "text": "Recursion" }, { "code": null, "e": 28067, "s": 28055, "text": "permutation" }, { "code": null, "e": 28080, "s": 28067, "text": "Backtracking" }, { "code": null, "e": 28178, "s": 28080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28187, "s": 28178, "text": "Comments" }, { "code": null, "e": 28200, "s": 28187, "text": "Old Comments" }, { "code": null, "e": 28211, "s": 28200, "text": "Tug of War" }, { "code": null, "e": 28272, "s": 28211, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 28292, "s": 28272, "text": "Perfect Sum Problem" }, { "code": null, "e": 28365, "s": 28292, "text": "N-Queen Problem | Local Search using Hill climbing with random neighbour" }, { "code": null, "e": 28415, "s": 28365, "text": "Find shortest safe route in a path with landmines" }, { "code": null, "e": 28425, "s": 28415, "text": "Recursion" }, { "code": null, "e": 28452, "s": 28425, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 28500, "s": 28452, "text": "Program for Sum of the digits of a given number" }, { "code": null, "e": 28546, "s": 28500, "text": "Write a program to reverse digits of a number" } ]
Block Lambda Expressions in Java - GeeksforGeeks
17 Jun, 2021 Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda’s body consists of a block of code. If it has only a single expression they are called “Expression Bodies“. Lambdas which contain expression bodies are known as “Expression Lambdas“. Below is an example of Lambda expression in a single line. Block Lambda contains many operations that work on lambda expressions as it allows the lambda body to have many statements. This includes variables, loops, conditional statements like if, else and switch statements, nested blocks, etc. This is created by enclosing the block of statements in lambda body within braces {}. This can even have a return statement i.e return value. Syntax: Lambda Expressions (parameters) -> { lambda body } Now first let us do understand the Lambda expression to get to know about the block lambda expression. Illustration: In this case, lambda may need more than a single expression in its lambda body. Java supports Expression Lambdas which contains blocks of code with more than one statement. We call this type of Lambda Body a “Block Body“. Lambdas that contain block bodies can be known as “Block Lambdas“. Example Representing the Lambda expression Java // Java Program to illustrate Lambda expression // Importing input output classesimport java.io.*; // Interface// If1 is name of this interfaceinterface If1 { // Member function of this interface // Abstract function boolean fun(int n);} // Classclass GFG { // Main driver method public static void main(String[] args) { // Lambda expression body If1 isEven = (n) -> (n % 2) == 0; // Above is lambda expression which tests // passed number is even or odd // Condition check over some number N // by calling the above function // using isEven() over fun() defined above // Input is passed as a parameter N // Say custom input N = 21 if (isEven.fun(21)) // Display message to be printed System.out.println("21 is even"); else // Display message to be printed System.out.println("21 is odd"); }} 21 is odd Now switching over to the implementation of the block lambda expression followed by two examples as shown below: Implementation: Example 1: Java // Java Program to illustrate Block Lambda expression // Importing all classes from// java.util packageimport java.io.*; // Block lambda to find out factorial// of a number // Interfaceinterface Func { // n is some natural number whose // factorial is to be computed int fact(int n);} // Class// Main classclass GFG { // Main driver method public static void main(String[] args) { // Block lambda expression Func f = (n) -> { // Block body // Initially initializing with 1 int res = 1; // iterating from 1 to the current number // to find factorial by multiplication for (int i = 1; i <= n; i++) res = i * res; return res; }; // Calling lambda function // Print and display n the console System.out.println("Factorial of 5 : " + f.fact(5)); }} Factorial of 5: 120 Here in this block lambda declares a variable ‘res’, for loop and has return statement which are legal in lambda body. Example 2: Java // Java Program to illustrate Block Lambda expression // Importing all input output classesimport java.io.*; // Interface// Functional interface named 'New'interface New { // Boolean function to check over // natural number depicting calender year // 'n' deepicting year is // passed as an parameter boolean test(int n);} // Class// Main classclass GFG { // Main driver method public static void main(String[] args) { // block lambda // This block lambda checks if the // given year is leap year or not New leapyr = (year) -> { // Condition check // If year is divisible by 400 or the // year is divisible by 4 and 100 both if (((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0))) // Returning true as year is leap year return true; else // Returning false for non-leap years return false; }; // Calling lambda function over // custom input year- 2020 // Condition check using the test() // defined in the above interface if (leapyr.test(2020)) // Display message on the console System.out.println("leap year"); else // Display message on the console System.out.println("Non leap year"); }} leap year Here in this block lambda has if-else conditions and return statements which are legal in lambda body. abhishek0719kadiyan java-lambda Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23868, "s": 23840, "text": "\n17 Jun, 2021" }, { "code": null, "e": 24279, "s": 23868, "text": "Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda’s body consists of a block of code. If it has only a single expression they are called “Expression Bodies“. Lambdas which contain expression bodies are known as “Expression Lambdas“. Below is an example of Lambda expression in a single line." }, { "code": null, "e": 24658, "s": 24279, "text": "Block Lambda contains many operations that work on lambda expressions as it allows the lambda body to have many statements. This includes variables, loops, conditional statements like if, else and switch statements, nested blocks, etc. This is created by enclosing the block of statements in lambda body within braces {}. This can even have a return statement i.e return value." }, { "code": null, "e": 24685, "s": 24658, "text": "Syntax: Lambda Expressions" }, { "code": null, "e": 24717, "s": 24685, "text": "(parameters) -> { lambda body }" }, { "code": null, "e": 24820, "s": 24717, "text": "Now first let us do understand the Lambda expression to get to know about the block lambda expression." }, { "code": null, "e": 24835, "s": 24820, "text": "Illustration: " }, { "code": null, "e": 25125, "s": 24835, "text": "In this case, lambda may need more than a single expression in its lambda body. Java supports Expression Lambdas which contains blocks of code with more than one statement. We call this type of Lambda Body a “Block Body“. Lambdas that contain block bodies can be known as “Block Lambdas“." }, { "code": null, "e": 25169, "s": 25125, "text": " Example Representing the Lambda expression" }, { "code": null, "e": 25174, "s": 25169, "text": "Java" }, { "code": "// Java Program to illustrate Lambda expression // Importing input output classesimport java.io.*; // Interface// If1 is name of this interfaceinterface If1 { // Member function of this interface // Abstract function boolean fun(int n);} // Classclass GFG { // Main driver method public static void main(String[] args) { // Lambda expression body If1 isEven = (n) -> (n % 2) == 0; // Above is lambda expression which tests // passed number is even or odd // Condition check over some number N // by calling the above function // using isEven() over fun() defined above // Input is passed as a parameter N // Say custom input N = 21 if (isEven.fun(21)) // Display message to be printed System.out.println(\"21 is even\"); else // Display message to be printed System.out.println(\"21 is odd\"); }}", "e": 26116, "s": 25174, "text": null }, { "code": null, "e": 26129, "s": 26119, "text": "21 is odd" }, { "code": null, "e": 26244, "s": 26131, "text": "Now switching over to the implementation of the block lambda expression followed by two examples as shown below:" }, { "code": null, "e": 26263, "s": 26246, "text": "Implementation: " }, { "code": null, "e": 26276, "s": 26265, "text": "Example 1:" }, { "code": null, "e": 26283, "s": 26278, "text": "Java" }, { "code": "// Java Program to illustrate Block Lambda expression // Importing all classes from// java.util packageimport java.io.*; // Block lambda to find out factorial// of a number // Interfaceinterface Func { // n is some natural number whose // factorial is to be computed int fact(int n);} // Class// Main classclass GFG { // Main driver method public static void main(String[] args) { // Block lambda expression Func f = (n) -> { // Block body // Initially initializing with 1 int res = 1; // iterating from 1 to the current number // to find factorial by multiplication for (int i = 1; i <= n; i++) res = i * res; return res; }; // Calling lambda function // Print and display n the console System.out.println(\"Factorial of 5 : \" + f.fact(5)); }}", "e": 27193, "s": 26283, "text": null }, { "code": null, "e": 27216, "s": 27196, "text": "Factorial of 5: 120" }, { "code": null, "e": 27335, "s": 27216, "text": "Here in this block lambda declares a variable ‘res’, for loop and has return statement which are legal in lambda body." }, { "code": null, "e": 27348, "s": 27337, "text": "Example 2:" }, { "code": null, "e": 27355, "s": 27350, "text": "Java" }, { "code": "// Java Program to illustrate Block Lambda expression // Importing all input output classesimport java.io.*; // Interface// Functional interface named 'New'interface New { // Boolean function to check over // natural number depicting calender year // 'n' deepicting year is // passed as an parameter boolean test(int n);} // Class// Main classclass GFG { // Main driver method public static void main(String[] args) { // block lambda // This block lambda checks if the // given year is leap year or not New leapyr = (year) -> { // Condition check // If year is divisible by 400 or the // year is divisible by 4 and 100 both if (((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0))) // Returning true as year is leap year return true; else // Returning false for non-leap years return false; }; // Calling lambda function over // custom input year- 2020 // Condition check using the test() // defined in the above interface if (leapyr.test(2020)) // Display message on the console System.out.println(\"leap year\"); else // Display message on the console System.out.println(\"Non leap year\"); }}", "e": 28749, "s": 27355, "text": null }, { "code": null, "e": 28762, "s": 28752, "text": "leap year" }, { "code": null, "e": 28865, "s": 28762, "text": "Here in this block lambda has if-else conditions and return statements which are legal in lambda body." }, { "code": null, "e": 28887, "s": 28867, "text": "abhishek0719kadiyan" }, { "code": null, "e": 28899, "s": 28887, "text": "java-lambda" }, { "code": null, "e": 28904, "s": 28899, "text": "Java" }, { "code": null, "e": 28909, "s": 28904, "text": "Java" }, { "code": null, "e": 29007, "s": 28909, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29016, "s": 29007, "text": "Comments" }, { "code": null, "e": 29029, "s": 29016, "text": "Old Comments" }, { "code": null, "e": 29050, "s": 29029, "text": "Constructors in Java" }, { "code": null, "e": 29065, "s": 29050, "text": "Stream In Java" }, { "code": null, "e": 29084, "s": 29065, "text": "Exceptions in Java" }, { "code": null, "e": 29114, "s": 29084, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29160, "s": 29114, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29186, "s": 29160, "text": "Java Programming Examples" }, { "code": null, "e": 29222, "s": 29186, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 29262, "s": 29222, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 29278, "s": 29262, "text": "Strings in Java" } ]
Swing Examples - Show Warning message Dialog
Following example showcase how to show a warning message alert in swing based application. We are using the following APIs. JOptionPane − To create a standard dialog box. JOptionPane − To create a standard dialog box. JOptionPane.showMessageDialog() − To show the message alert. JOptionPane.showMessageDialog() − To show the message alert. JOptionPane.WARNING_MESSAGE − To mark the alert message as warning. JOptionPane.WARNING_MESSAGE − To mark the alert message as warning. import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(frame, "Please ensure compliance!", "Swing Tester", JOptionPane.WARNING_MESSAGE); } }); panel.add(button); frame.getContentPane().add(panel, BorderLayout.CENTER); } } Print Add Notes Bookmark this page
[ { "code": null, "e": 2130, "s": 2039, "text": "Following example showcase how to show a warning message alert in swing based application." }, { "code": null, "e": 2163, "s": 2130, "text": "We are using the following APIs." }, { "code": null, "e": 2210, "s": 2163, "text": "JOptionPane − To create a standard dialog box." }, { "code": null, "e": 2257, "s": 2210, "text": "JOptionPane − To create a standard dialog box." }, { "code": null, "e": 2318, "s": 2257, "text": "JOptionPane.showMessageDialog() − To show the message alert." }, { "code": null, "e": 2379, "s": 2318, "text": "JOptionPane.showMessageDialog() − To show the message alert." }, { "code": null, "e": 2447, "s": 2379, "text": "JOptionPane.WARNING_MESSAGE − To mark the alert message as warning." }, { "code": null, "e": 2515, "s": 2447, "text": "JOptionPane.WARNING_MESSAGE − To mark the alert message as warning." }, { "code": null, "e": 3799, "s": 2515, "text": "import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.LayoutManager;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\n\npublic class SwingTester {\n public static void main(String[] args) {\n createWindow();\n }\n\n private static void createWindow() { \n JFrame frame = new JFrame(\"Swing Tester\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n createUI(frame);\n frame.setSize(560, 200); \n frame.setLocationRelativeTo(null); \n frame.setVisible(true);\n }\n\n private static void createUI(final JFrame frame){ \n JPanel panel = new JPanel();\n LayoutManager layout = new FlowLayout(); \n panel.setLayout(layout); \n JButton button = new JButton(\"Click Me!\");\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n JOptionPane.showMessageDialog(frame, \"Please ensure compliance!\",\n \"Swing Tester\", JOptionPane.WARNING_MESSAGE);\n }\n });\n\n panel.add(button);\n frame.getContentPane().add(panel, BorderLayout.CENTER); \n } \n}" }, { "code": null, "e": 3806, "s": 3799, "text": " Print" }, { "code": null, "e": 3817, "s": 3806, "text": " Add Notes" } ]
Catching that flight: Visualizing social network with Networkx and Basemap | by Tuan Nguyen Doan | Towards Data Science
“If you graph these numbers, patterns emerge. There are patterns everywhere in nature.” Max Cohen (played by Sean Gullette, in Pi, a film by Darren Aronofsky) Today, I will introduce very powerful tools to visualize network — Networkx and Basemap. Many interesting problems naturally arrive from or inspire some form of graph models — relationship between vertices (or nodes) and edges that connects these vertices. For example: the outlink and inlink structures of a website can be represented by a directed graph, in which the vertices represent web pages and directed edges represent links from one page to another. Another example is a friend circle, in which vertices represent different people and edges represent the type of relationship. When it comes to complicated networks such as virus outbreaks, cash flows among countries, or seismic waves of the 2005 Earthquake, it remains a challenge to illustrate attributes of the network visually, descriptively and effectively. We want the audience to quickly grasp the network in its geographical context. Networkx and Basemap (a toolkit of the matplotlib package) provides a “end-to-end” solution. While the former creates network graphs and calculates various measures, the latter is capable of presenting neat visualizations that are both intuitive and informative. In this example, we look at the flight route network between airports in the United States of America. The goal is to represent vertices (airports) and edges (flight route) and preserve the geographical relationships between different vertices (e.g: we want to look at the graph and tell that this vertex is JFK or Logan Airport or whatever) At first we load the relevant packages: import pandas as pdimport networkx as nximport matplotlib.pyplot as pltfrom mpl_toolkits.basemap import Basemap as Basemap The matplotlib basemap toolkit is a library for plotting 2D data on maps in Python. Networkx is a comprehensive library to study network structure. The first step is to acquire the data and process it. Here, I use the OpenFlight1 database to acquire information about airports and routes. They have very comprehensive data. Unfortunately, the route database is not very up-to-date. It currently contains 59,036 routes between 3,209 airports on 531 airlines spanning the globe. Until today, there are up to 17,678 commercial airports in the world. Nevertheless, the current datasets are good enough for our illustration purpose today. There are two relevant datasets: The airport.dat dataset contains geographic information of all the listed airport The routes.dat dataset contains geographic information of all the listed airports Networkx cannot read the data in its raw form, so our first job is to process the data to acquire a clean dataframe of routes that could be read by Networkx. Here, we use pandas to parse Excel files into dataframes ,extract and process the information. Notice how the two dataset are connected by the code of the airport (the three letter IATA code). You can find the full code to process the data in my source code here. The aim of our data-processing step is to acquire the following two Panda dataframes: A condensed routes_us data frame where each row represents a unique air route and the total number of airlines operate on that route (for example, there are 3 airlines that operate the flight from Lehigh Valley Airport (ABE) to Atlanta International Airport (ATL). A condensed position dataframe where each row represent each USA airports with IATA code, and more importantly, longitudinal and latitudinal details With the former dataframe, we are ready to draw our very first sketch of the flight networks. At first, we translated our dataframe into a graph. Notice that our graph is a directed graph, that is, a graph with a set of vertices connected by edges having directions associated with them. This means that in our graph, the two routes JFK-ATL and ATL-JFK are distinct since even though they are connecting the same 2 nodes, the two routes have different (opposite) directions. We use Networkx’s from_panda_dataframe() function to quickly import our graph. Here we create a graph from our dataframe routes_us, where the source is ‘Source Airport’ column, the target is ‘Dest Airport’ column using a Directed Graph model. edge_attr means that we can add information to the edges of the graph. I have added the number of airlines operated on a route as the edge attribute graph = nx.from_pandas_dataframe(routes_us, source = 'Source Airport', target = 'Dest Airport', edge_attr = 'number of flights',create_using = nx.DiGraph()) Networkx does have a graphical tool that we can use to draw our network. plt.figure(figsize = (10,9))nx.draw_networkx(graph)plt.savefig("./images/map_0.png", format = "png", dpi = 300)plt.show() The problem with this rough network is that we really cannot tell which airport is which and how routes are related to one another. Maybe it is a better idea to plot the airport in the exact geographical position in a American map. How do we do that? Aha, Basemap !!! Now, we need to help Basemap define the borderline of the USA. Let us define a relatively large map that includes Alaska and Puerto Rico. One thing to note is that there are many ways we can map a large area such as a continent onto a 2-D surface. For example, we can choose Equidistant Cylindrical projection, a simple projection which divides the globe into rectangulars of equal size. A more familiar method is the Mercator projection, which is a cylindrical, conformal projection with very large distortion at high latitudes. Yes, this is the wrongly misguided map in every classroom that has Alaska at the same size with the African continent I also choose the familiar Mercator projection. This plt.figure(figsize = (10,9))m = Basemap(projection='merc',llcrnrlon=-180,llcrnrlat=10,urcrnrlon=-50,urcrnrlat=70, lat_ts=0, resolution='l',suppress_ticks=True) Now, we need to define the position of our airports on the Basemap. Until now, we only have their longitudinal and latitudinal information. We need to find their actual projection onto the Basemap surface. Notice how I call our position dataset, get the Long and Lat data, and project them onto the Basemap surface mx, my = m(pos_data['Long'].values, pos_data['Lat'].values)pos = {}for count, elem in enumerate (pos_data['IATA']): pos[elem] = (mx[count], my[count]) The next step is to ask Networkx to add the nodes, edges and their attributes to the Basemap. This can be done as follows: nx.draw_networkx_nodes(G = graph, pos = pos, node_list = graph.nodes(),node_color = 'r', alpha = 0.8, node_size = 100)nx.draw_networkx_edges(G = graph, pos = pos, edge_color='g', alpha=0.2, arrows = False) The last step is to draw the countries, coastlines, and statelines. m.drawcountries(linewidth = 3)m.drawstates(linewidth = 0.2)m.drawcoastlines(linewidth=3)plt.tight_layout()plt.savefig("./images/map_1.png", format = "png", dpi = 300)plt.show() Well, this plot is pretty anti-climatic. It looks fine, but not great. Besides the fact that the map looks pretty ugly, we cannot tell anything from the graph. For example, we want to see more information such as: Which airports are busy? Which air routes are more prominent? To answer these questions, maybe it is a good idea to incorporate the total number of incoming and outgoing flights each airport has, and plot them as the size of the airport. For example, an airport with lots of incoming and outgoing flights will have a larger size and appear more visible on the map. To do that, we repeat the same code, with a small tweak: nx.draw_networkx_nodes(G = graph, pos = pos, node_list = graph.nodes(), node_color = 'r', alpha = 0.8, node_size = [counts['total_flight'][s]*3 for s in graph.nodes()]) This is a lot better, once you have been more familiar with using Networkx and Basemap, you can start using personalize the map according to your use cases. For example, here, I restrict my map to mainland airports and style the map a little differently We can start to make all sorts of interesting observations: for example, a number of large airports are mostly located in the 2 coastal areas (and Vegas, Denver, Dallas/Fort Worth, Houston and Atlanta). We can start to see the domestically air routes are particularly more dense in the West Coast area, as compared to any other geographical places. Interestingly, airports such as DEN (Denver International Airport) appears to function as a hub, that is, it serve as transfer (or stop-over) points to get passengers to their final destination. In future posts, I will introduce Networkx tools to analyze the distribution of edges and characteristics of nodes in such a network using Networkx If you enjoy this article, you may also enjoy my other article sport visualization: Advanced sports visualization with Python, Matplotlib and Seaborn For other deep dive analyses about interesting statistical facts and rules of thumbs: A statistical rule to optimize your life: the Lindy’s Effect Rules of Three: Calculating the probability of events that have not yet occurred Making big bucks with a data-driven sport betting strategy The entire Python script for this article can be found at my Github page. Data Source: OpenFlight. Airport, airline and route data 2017 https://openflights.org/data.html
[ { "code": null, "e": 260, "s": 172, "text": "“If you graph these numbers, patterns emerge. There are patterns everywhere in nature.”" }, { "code": null, "e": 331, "s": 260, "text": "Max Cohen (played by Sean Gullette, in Pi, a film by Darren Aronofsky)" }, { "code": null, "e": 918, "s": 331, "text": "Today, I will introduce very powerful tools to visualize network — Networkx and Basemap. Many interesting problems naturally arrive from or inspire some form of graph models — relationship between vertices (or nodes) and edges that connects these vertices. For example: the outlink and inlink structures of a website can be represented by a directed graph, in which the vertices represent web pages and directed edges represent links from one page to another. Another example is a friend circle, in which vertices represent different people and edges represent the type of relationship." }, { "code": null, "e": 1496, "s": 918, "text": "When it comes to complicated networks such as virus outbreaks, cash flows among countries, or seismic waves of the 2005 Earthquake, it remains a challenge to illustrate attributes of the network visually, descriptively and effectively. We want the audience to quickly grasp the network in its geographical context. Networkx and Basemap (a toolkit of the matplotlib package) provides a “end-to-end” solution. While the former creates network graphs and calculates various measures, the latter is capable of presenting neat visualizations that are both intuitive and informative." }, { "code": null, "e": 1838, "s": 1496, "text": "In this example, we look at the flight route network between airports in the United States of America. The goal is to represent vertices (airports) and edges (flight route) and preserve the geographical relationships between different vertices (e.g: we want to look at the graph and tell that this vertex is JFK or Logan Airport or whatever)" }, { "code": null, "e": 1878, "s": 1838, "text": "At first we load the relevant packages:" }, { "code": null, "e": 2001, "s": 1878, "text": "import pandas as pdimport networkx as nximport matplotlib.pyplot as pltfrom mpl_toolkits.basemap import Basemap as Basemap" }, { "code": null, "e": 2149, "s": 2001, "text": "The matplotlib basemap toolkit is a library for plotting 2D data on maps in Python. Networkx is a comprehensive library to study network structure." }, { "code": null, "e": 2635, "s": 2149, "text": "The first step is to acquire the data and process it. Here, I use the OpenFlight1 database to acquire information about airports and routes. They have very comprehensive data. Unfortunately, the route database is not very up-to-date. It currently contains 59,036 routes between 3,209 airports on 531 airlines spanning the globe. Until today, there are up to 17,678 commercial airports in the world. Nevertheless, the current datasets are good enough for our illustration purpose today." }, { "code": null, "e": 2668, "s": 2635, "text": "There are two relevant datasets:" }, { "code": null, "e": 2750, "s": 2668, "text": "The airport.dat dataset contains geographic information of all the listed airport" }, { "code": null, "e": 2832, "s": 2750, "text": "The routes.dat dataset contains geographic information of all the listed airports" }, { "code": null, "e": 3254, "s": 2832, "text": "Networkx cannot read the data in its raw form, so our first job is to process the data to acquire a clean dataframe of routes that could be read by Networkx. Here, we use pandas to parse Excel files into dataframes ,extract and process the information. Notice how the two dataset are connected by the code of the airport (the three letter IATA code). You can find the full code to process the data in my source code here." }, { "code": null, "e": 3340, "s": 3254, "text": "The aim of our data-processing step is to acquire the following two Panda dataframes:" }, { "code": null, "e": 3605, "s": 3340, "text": "A condensed routes_us data frame where each row represents a unique air route and the total number of airlines operate on that route (for example, there are 3 airlines that operate the flight from Lehigh Valley Airport (ABE) to Atlanta International Airport (ATL)." }, { "code": null, "e": 3754, "s": 3605, "text": "A condensed position dataframe where each row represent each USA airports with IATA code, and more importantly, longitudinal and latitudinal details" }, { "code": null, "e": 3848, "s": 3754, "text": "With the former dataframe, we are ready to draw our very first sketch of the flight networks." }, { "code": null, "e": 4229, "s": 3848, "text": "At first, we translated our dataframe into a graph. Notice that our graph is a directed graph, that is, a graph with a set of vertices connected by edges having directions associated with them. This means that in our graph, the two routes JFK-ATL and ATL-JFK are distinct since even though they are connecting the same 2 nodes, the two routes have different (opposite) directions." }, { "code": null, "e": 4621, "s": 4229, "text": "We use Networkx’s from_panda_dataframe() function to quickly import our graph. Here we create a graph from our dataframe routes_us, where the source is ‘Source Airport’ column, the target is ‘Dest Airport’ column using a Directed Graph model. edge_attr means that we can add information to the edges of the graph. I have added the number of airlines operated on a route as the edge attribute" }, { "code": null, "e": 4778, "s": 4621, "text": "graph = nx.from_pandas_dataframe(routes_us, source = 'Source Airport', target = 'Dest Airport', edge_attr = 'number of flights',create_using = nx.DiGraph())" }, { "code": null, "e": 4851, "s": 4778, "text": "Networkx does have a graphical tool that we can use to draw our network." }, { "code": null, "e": 4973, "s": 4851, "text": "plt.figure(figsize = (10,9))nx.draw_networkx(graph)plt.savefig(\"./images/map_0.png\", format = \"png\", dpi = 300)plt.show()" }, { "code": null, "e": 5241, "s": 4973, "text": "The problem with this rough network is that we really cannot tell which airport is which and how routes are related to one another. Maybe it is a better idea to plot the airport in the exact geographical position in a American map. How do we do that? Aha, Basemap !!!" }, { "code": null, "e": 5889, "s": 5241, "text": "Now, we need to help Basemap define the borderline of the USA. Let us define a relatively large map that includes Alaska and Puerto Rico. One thing to note is that there are many ways we can map a large area such as a continent onto a 2-D surface. For example, we can choose Equidistant Cylindrical projection, a simple projection which divides the globe into rectangulars of equal size. A more familiar method is the Mercator projection, which is a cylindrical, conformal projection with very large distortion at high latitudes. Yes, this is the wrongly misguided map in every classroom that has Alaska at the same size with the African continent" }, { "code": null, "e": 5942, "s": 5889, "text": "I also choose the familiar Mercator projection. This" }, { "code": null, "e": 6102, "s": 5942, "text": "plt.figure(figsize = (10,9))m = Basemap(projection='merc',llcrnrlon=-180,llcrnrlat=10,urcrnrlon=-50,urcrnrlat=70, lat_ts=0, resolution='l',suppress_ticks=True)" }, { "code": null, "e": 6417, "s": 6102, "text": "Now, we need to define the position of our airports on the Basemap. Until now, we only have their longitudinal and latitudinal information. We need to find their actual projection onto the Basemap surface. Notice how I call our position dataset, get the Long and Lat data, and project them onto the Basemap surface" }, { "code": null, "e": 6572, "s": 6417, "text": "mx, my = m(pos_data['Long'].values, pos_data['Lat'].values)pos = {}for count, elem in enumerate (pos_data['IATA']): pos[elem] = (mx[count], my[count])" }, { "code": null, "e": 6695, "s": 6572, "text": "The next step is to ask Networkx to add the nodes, edges and their attributes to the Basemap. This can be done as follows:" }, { "code": null, "e": 6901, "s": 6695, "text": "nx.draw_networkx_nodes(G = graph, pos = pos, node_list = graph.nodes(),node_color = 'r', alpha = 0.8, node_size = 100)nx.draw_networkx_edges(G = graph, pos = pos, edge_color='g', alpha=0.2, arrows = False)" }, { "code": null, "e": 6969, "s": 6901, "text": "The last step is to draw the countries, coastlines, and statelines." }, { "code": null, "e": 7146, "s": 6969, "text": "m.drawcountries(linewidth = 3)m.drawstates(linewidth = 0.2)m.drawcoastlines(linewidth=3)plt.tight_layout()plt.savefig(\"./images/map_1.png\", format = \"png\", dpi = 300)plt.show()" }, { "code": null, "e": 7360, "s": 7146, "text": "Well, this plot is pretty anti-climatic. It looks fine, but not great. Besides the fact that the map looks pretty ugly, we cannot tell anything from the graph. For example, we want to see more information such as:" }, { "code": null, "e": 7385, "s": 7360, "text": "Which airports are busy?" }, { "code": null, "e": 7422, "s": 7385, "text": "Which air routes are more prominent?" }, { "code": null, "e": 7725, "s": 7422, "text": "To answer these questions, maybe it is a good idea to incorporate the total number of incoming and outgoing flights each airport has, and plot them as the size of the airport. For example, an airport with lots of incoming and outgoing flights will have a larger size and appear more visible on the map." }, { "code": null, "e": 7782, "s": 7725, "text": "To do that, we repeat the same code, with a small tweak:" }, { "code": null, "e": 7951, "s": 7782, "text": "nx.draw_networkx_nodes(G = graph, pos = pos, node_list = graph.nodes(), node_color = 'r', alpha = 0.8, node_size = [counts['total_flight'][s]*3 for s in graph.nodes()])" }, { "code": null, "e": 8205, "s": 7951, "text": "This is a lot better, once you have been more familiar with using Networkx and Basemap, you can start using personalize the map according to your use cases. For example, here, I restrict my map to mainland airports and style the map a little differently" }, { "code": null, "e": 8897, "s": 8205, "text": "We can start to make all sorts of interesting observations: for example, a number of large airports are mostly located in the 2 coastal areas (and Vegas, Denver, Dallas/Fort Worth, Houston and Atlanta). We can start to see the domestically air routes are particularly more dense in the West Coast area, as compared to any other geographical places. Interestingly, airports such as DEN (Denver International Airport) appears to function as a hub, that is, it serve as transfer (or stop-over) points to get passengers to their final destination. In future posts, I will introduce Networkx tools to analyze the distribution of edges and characteristics of nodes in such a network using Networkx" }, { "code": null, "e": 8981, "s": 8897, "text": "If you enjoy this article, you may also enjoy my other article sport visualization:" }, { "code": null, "e": 9047, "s": 8981, "text": "Advanced sports visualization with Python, Matplotlib and Seaborn" }, { "code": null, "e": 9133, "s": 9047, "text": "For other deep dive analyses about interesting statistical facts and rules of thumbs:" }, { "code": null, "e": 9194, "s": 9133, "text": "A statistical rule to optimize your life: the Lindy’s Effect" }, { "code": null, "e": 9275, "s": 9194, "text": "Rules of Three: Calculating the probability of events that have not yet occurred" }, { "code": null, "e": 9334, "s": 9275, "text": "Making big bucks with a data-driven sport betting strategy" }, { "code": null, "e": 9408, "s": 9334, "text": "The entire Python script for this article can be found at my Github page." } ]
State the difference between structure and union with suitable example in C language
The differences between structures and unions in C language are explained below − struct tagname{ datatype member1; datatype member2; ---- ---- ---- }; union tagname{ datatype member1; datatype member2; ---- ---- ---- }; struct sample{ int a; float b; char c; }; union sample{ int a; float b; char c; }; Following is the C program for structures − #include<stdio.h> struct size{ double a; int b; char c; float d; }; int main(){ printf("%ld",sizeof( stuct size)); } When the above program is executed, it produces the following result − 24 Following is the C program on union − #include<stdio.h> union size{ double a; int b; char c; float d; } Int main(){ Printf("ld",sizeof(union size)); } When the above program is executed, it produces the following result − 8
[ { "code": null, "e": 1144, "s": 1062, "text": "The differences between structures and unions in C language are explained below −" }, { "code": null, "e": 1229, "s": 1144, "text": "struct tagname{\n datatype member1;\n datatype member2;\n ----\n ----\n ----\n};" }, { "code": null, "e": 1313, "s": 1229, "text": "union tagname{\n datatype member1;\n datatype member2;\n ----\n ----\n ----\n};" }, { "code": null, "e": 1364, "s": 1313, "text": "struct sample{\n int a;\n float b;\n char c;\n};" }, { "code": null, "e": 1414, "s": 1364, "text": "union sample{\n int a;\n float b;\n char c;\n};" }, { "code": null, "e": 1458, "s": 1414, "text": "Following is the C program for structures −" }, { "code": null, "e": 1590, "s": 1458, "text": "#include<stdio.h>\nstruct size{\n double a;\n int b;\n char c;\n float d;\n};\nint main(){\n printf(\"%ld\",sizeof( stuct size));\n}" }, { "code": null, "e": 1661, "s": 1590, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 1664, "s": 1661, "text": "24" }, { "code": null, "e": 1702, "s": 1664, "text": "Following is the C program on union −" }, { "code": null, "e": 1830, "s": 1702, "text": "#include<stdio.h>\nunion size{\n double a;\n int b;\n char c;\n float d;\n}\nInt main(){\n Printf(\"ld\",sizeof(union size));\n}" }, { "code": null, "e": 1901, "s": 1830, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 1903, "s": 1901, "text": "8" } ]
Longest Increasing Subsequence
Longest Increasing Subsequence is a subsequence where one item is greater than its previous item. Here we will try to find Longest Increasing Subsequence length, from a set of integers. Input: A set of integers. {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} Output: The length of longest increasing subsequence. Here it is 6. The subsequence is 0, 2, 6, 9, 13, 15. longestSubSeq(subarray, n) Input − The sub array and the size of sub array. Output − Longest increasing sub sequence length. Begin define array length of size n initially set 0 to all entries of length for i := 1 to n-1, do for j := 0 to i-1, do if subarray[j] < subarray[i] and length[j] > length[i], then length[i] := length[j] done increase length[i] by 1 done lis := 0 for i := 0 to n-1, do lis := maximum of lis and length[i] done return lis End #include <iostream> using namespace std; int longestSubSeq(int subArr[], int n) { int length[n] = { 0 }; //set all length to 0 length[0] = 1; //subsequence ending with subArr[0] is 1 for (int i = 1; i < n; i++) { //ignore first character, second to all for (int j = 0; j < i; j++) { //subsequence ends with subArr[j] if (subArr[j] < subArr[i] && length[j] > length[i]) length[i] = length[j]; } length[i]++; //add arr[i] } int lis = 0; for (int i = 0; i<n; i++) // find longest increasing subsequence lis = max(lis, length[i]); return lis; } int main() { int arr[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; int n = 16 cout << "Length of Longest Increasing Subsequence is: " << longestSubSeq(arr, n); return 0; } Length of Longest Increasing Subsequence is: 6
[ { "code": null, "e": 1248, "s": 1062, "text": "Longest Increasing Subsequence is a subsequence where one item is greater than its previous item. Here we will try to find Longest Increasing Subsequence length, from a set of integers." }, { "code": null, "e": 1436, "s": 1248, "text": "Input:\nA set of integers. {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}\nOutput:\nThe length of longest increasing subsequence. Here it is 6.\nThe subsequence is 0, 2, 6, 9, 13, 15." }, { "code": null, "e": 1463, "s": 1436, "text": "longestSubSeq(subarray, n)" }, { "code": null, "e": 1512, "s": 1463, "text": "Input − The sub array and the size of sub array." }, { "code": null, "e": 1561, "s": 1512, "text": "Output − Longest increasing sub sequence length." }, { "code": null, "e": 1948, "s": 1561, "text": "Begin\n define array length of size n\n initially set 0 to all entries of length\n\n for i := 1 to n-1, do\n for j := 0 to i-1, do\n if subarray[j] < subarray[i] and length[j] > length[i], then length[i] := length[j]\n done\n\n increase length[i] by 1\n done\n\n lis := 0\n for i := 0 to n-1, do\n lis := maximum of lis and length[i]\n done\n\n return lis\nEnd" }, { "code": null, "e": 2844, "s": 1948, "text": "#include <iostream>\nusing namespace std;\n\nint longestSubSeq(int subArr[], int n) {\n int length[n] = { 0 }; //set all length to 0\n length[0] = 1; //subsequence ending with subArr[0] is 1\n\n for (int i = 1; i < n; i++) { //ignore first character, second to all\n for (int j = 0; j < i; j++) { //subsequence ends with subArr[j]\n if (subArr[j] < subArr[i] && length[j] > length[i])\n length[i] = length[j];\n }\n length[i]++; //add arr[i]\n }\n int lis = 0;\n for (int i = 0; i<n; i++) // find longest increasing subsequence\n lis = max(lis, length[i]);\n return lis;\n}\nint main() {\n int arr[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};\n int n = 16\n cout << \"Length of Longest Increasing Subsequence is: \" << longestSubSeq(arr, n);\n return 0;\n}" }, { "code": null, "e": 2891, "s": 2844, "text": "Length of Longest Increasing Subsequence is: 6" } ]
How to get the creation date of a MySQL table?
To get the creation date of a MySQL table, use create_time from information_schema.tables. The syntax is as follows − SELECT create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'yourDatabaseName' AND table_name = 'yourTableName'; My table name is 'skiplasttenrecords' and database is ‘test’. Implement the above syntax for your database and table name. The query is as follows − mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'test' −> AND table_name = 'skiplasttenrecords'; The following is the output displaying the creation date − +---------------------+ | CREATE_TIME | +---------------------+ | 2018-11-29 15:47:14 | +---------------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1180, "s": 1062, "text": "To get the creation date of a MySQL table, use create_time from information_schema.tables. The syntax is as follows −" }, { "code": null, "e": 1304, "s": 1180, "text": "SELECT create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'yourDatabaseName' AND table_name = 'yourTableName';" }, { "code": null, "e": 1366, "s": 1304, "text": "My table name is 'skiplasttenrecords' and database is ‘test’." }, { "code": null, "e": 1453, "s": 1366, "text": "Implement the above syntax for your database and table name. The query is as follows −" }, { "code": null, "e": 1583, "s": 1453, "text": "mysql> SELECT create_time FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'test'\n −> AND table_name = 'skiplasttenrecords';" }, { "code": null, "e": 1642, "s": 1583, "text": "The following is the output displaying the creation date −" }, { "code": null, "e": 1786, "s": 1642, "text": "+---------------------+\n| CREATE_TIME |\n+---------------------+\n| 2018-11-29 15:47:14 |\n+---------------------+\n1 row in set (0.00 sec)" } ]
Difference between Procedural and Declarative Knowledge
Procedural or imperative knowledge clarifies how to perform a certain task. It lays down the steps to perform. For example, - how to copy an array using javascript in a procedural way. var a=[1, 2, 3, 4, 5]; var b=[]; for(var i=0;i < a.length;i++) { b.push(a[i]); } console.log(b); [1, 2, 3, 4, 5] Declarative or functional knowledge clarifies what to do to perform a certain task. It lays down the function to perform. For example, - how to copy an array using javascript in a declarative way. var a=[1, 2, 3, 4, 5]; var b=a.map(function(number){ return number*1 }); console.log(b); [1, 2, 3, 4, 5] The following are some of the important differences between Procedural Knowledge and Declarative Knowledge.
[ { "code": null, "e": 1247, "s": 1062, "text": "Procedural or imperative knowledge clarifies how to perform a certain task. It lays down the steps to perform. For example, - how to copy an array using javascript in a procedural way." }, { "code": null, "e": 1347, "s": 1247, "text": "var a=[1, 2, 3, 4, 5];\nvar b=[];\nfor(var i=0;i < a.length;i++) {\n b.push(a[i]);\n}\nconsole.log(b);" }, { "code": null, "e": 1363, "s": 1347, "text": "[1, 2, 3, 4, 5]" }, { "code": null, "e": 1560, "s": 1363, "text": "Declarative or functional knowledge clarifies what to do to perform a certain task. It lays down the function to perform. For example, - how to copy an array using javascript in a declarative way." }, { "code": null, "e": 1652, "s": 1560, "text": "var a=[1, 2, 3, 4, 5];\nvar b=a.map(function(number){\n return number*1\n});\nconsole.log(b);" }, { "code": null, "e": 1668, "s": 1652, "text": "[1, 2, 3, 4, 5]" }, { "code": null, "e": 1776, "s": 1668, "text": "The following are some of the important differences between Procedural Knowledge and Declarative Knowledge." } ]
SettingWithCopyWarning in pandas. What it is, why it crops up, and how to... | by Tan Nian Wei | Towards Data Science
(tl;dr: jump straight to Getting rid of SettingWithCopyWarnings if you’re here for answers) If you are a pandas user, chances are you’ve seen the SettingWithCopyWarning crop up when you’re assigning values to a pd.DataFrame or pd.Series. In [1]: import pandas as pd ...: ...: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: }, index=range(5) ...: ) ...: dfa = df.loc[3:5] ...: dfa[“C”] = dfa[“B”] * 50<ipython-input-2–63497d1da3d9>:9: SettingWithCopyWarning:A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“C”] = dfa[“B”] * 50 pandas drops a warning here because the value assignment might or might not have worked as expected. To be clear, the value assignment did occur all right; the emphasis here is on “expected”. In [2]: dfaOut[2]: A B C3 4 9 4504 5 10 500In [3]: dfOut[3]: A B0 1 61 2 72 3 83 4 94 5 10 Did you expect the contents of dfto be affected by the value assignment in dfa? pandas has internally consistent (albeit obtuse) rules on whether that happens or not. It’s just that the ambiguity in user expectations present in this situation warrants a warning, so that end users like you and me know where to look when our code misbehaves. The act of selecting rows or columns to access from a dataframe or series is called indexing. The flexibility of pandas allows for chained indexing, where you can repeatedly index the outcome of a previous indexing operation. # Select the 2nd to 4th row of data where col A > 3 and col B != 7df[df[“A”] > 3 & df[“B”] != 7].iloc[3:5] pandas will then return either a view or a copy of the dataframe. A view (shallow copy) references data from the original dataframe, while a copy (deep copy) is a separate instance of the same data. It is difficult to predict which will be returned by the indexing operation, as it depends on the memory layout of the underlying array. How exactly the indexing is chained can lead to different __getitem__ and __setitem__ calls being issued under the hood. Reproducing an example below: # Example borrowed from [1]dfmi.loc[:, (‘one’, ‘second’)] = value# becomesdfmi.loc.__setitem__((slice(None), (‘one’, ‘second’)), value)dfmi[‘one’][‘second’] = value# becomesdfmi.__getitem__(‘one’).__setitem__(‘second’, value) Chain indexing inherently is not a problem, but assigning values using chained indexing, i.e. chained assignment, can be. Depending on the situation, chained assignment will either modify the original dataframe directly, or return a modified copy of the original dataframe. This can lead to insidious bugs when it is not obvious that chained indexing has occured. Chained indexing can take places across a few lines of code: # The following doesn’t look like chain indexing, does it?dfa = df.loc[row1:row2, col1:col2]......dfa[row2] = dfa[row1].apply(fn) If pandas did not raise a warning in this scenario, it would not be obvious that df is not modified by the second value assignment. This is why the SettingWithCopyWarning exists. pandas docs [1] go into this with more detail. The warning message helpfully links to it, which is great because if you search pandas settingwithcopywarning on Google, the docs page is easy to miss! At time of writing, it is the 7th result on the first page of Google, and is crowded out by blogposts and StackOverflow questions. Chained indexing is a godsend of convenience for selecting the right data, but chained assignment is a minefield for assigning the correct values. The TowardsDataScience article in [2] has a nice example where inverting the order of chained indexing alone is the difference between whether an assignment to the original dataframe occurs or not: # Example borrowed from [2]# This updates `df`df[“product_group”][df[“product_group”]==”PG4"] = “PG14”# This doesn’t!df[df[“product_group”]==”PG4"][“product_group”] = “PG14”# pandas raises warnings for both# the user needs to confirm the intended outcome From this StackOverflow post, pd.DataFrame and pd.Series objects have _is_view and _is_copy attributes as part of their internal API. _is_view returns True if the object is a view, and False if the object is not. _is_copy stores either a weak reference to the dataframe it is copied from, or None if it is not associated to an existing dataframe. Printing these internal attributes while poking around with chained assignment does reveal some interesting tidbits of info. On one hand, pandas uses _is_copy to decide if a SettingWithCopyWarning needs to be raised. On the other hand, modifying a dataframe with _is_view = True means that it will affect the original underlying dataframe. Before we begin, a disclaimer: internal APIs are not meant to be accessed by the end user and are subject to change, use them at your own risk. In [4]: pd.__version__Out[4]: ‘1.3.3’# Setting up convenience functionsIn [5]: def make_clean_df(): ...: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5) ...: ) ...: return dfIn [6]: def show_attrs(obj): ...: print(f”view: {obj._is_view}, copy: {obj._is_copy}”) We’ll start by showing the _is_view and _is_copy attributes of a few common indexing methods. In [7]: df = make_clean_df()In [8]: show_attrs(df.loc[3:5]) ...: show_attrs(df.iloc[3:5]) ...: show_attrs(df.loc[3:5, [“A”, “B”]]) ...: show_attrs(df.iloc[3:5, [0, 1]]) ...: show_attrs(df[“A”]) ...: show_attrs(df.loc[:, “A”])view: True, copy: <weakref at 0x7f4d648b2590; to ‘DataFrame’ at 0x7f4d648b54c0>view: True, copy: <weakref at 0x7f4d648b2590; to ‘DataFrame’ at 0x7f4d648b54c0>view: False, copy: Noneview: False, copy: <weakref at 0x7f4d648be770; dead>view: True, copy: Noneview: True, copy: None Let’s break this down: Both df.loc[3:5] and df.iloc[3:5] returned views and have references to the original dataframe. For df.loc[3:5, [“A”, “B”]] and df.iloc[3:5, [0, 1]] , when the columns are additionally specified on top of the rows, copies of df are returned instead. Using .loc indexing has no references to the OG dataframe, while using iloc indexing results in a reference to a temporary dataframe that has been garbage collected, which is as good as None itself. We’ll see if this carries any significance. Referring to a column directly using either df[“A”] or df.loc[:, “A”] returns a view, with no reference to the original dataframe. It might have to do with the fact that each dataframe column is actually stored as a pd.Series. What happens if we manually create copies of these indexed dataframes / series? In [9]: show_attrs(df.loc[3:5].copy()) ...: show_attrs(df.iloc[3:5].copy()) ...: show_attrs(df.loc[3:5, [“A”, “B”]].copy()) ...: show_attrs(df.iloc[3:5, [0, 1]].copy()) ...: show_attrs(df[“A”].copy()) ...: show_attrs(df.loc[:, “A”].copy())view: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: None Explicitly calling .copy returns copies of data that have no reference to the original dataframe / series. Assigning data on these copies will not affect the original dataframe, and thus will not trigger SettingwithCopyWarnings. Given that df.loc[3:5, [“A”, “B”]] and df.iloc[3:5, [0, 1]] above have similar attributes, we can expect that their behaviour under chained assignment should be similar to explicitly created copies. Next, we’ll try a few chained assignment scenarios. The following three chained assignments raise SettingWithCopyWarnings: In [10]: df = make_clean_df() ...: dfa = df.loc[3:5] ...: show_attrs(dfa)view: True, copy: <weakref at 0x7fba308565e0; to ‘DataFrame’ at 0x7fba3084eac0># (1a)In [11]: dfa[dfa % 2 == 0] = 100/tmp/ipykernel_34555/3321004726.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[dfa % 2 == 0] = 100/home/tnwei/miniconda3/envs/ml/lib/python3.9/site-packages/pandas/core/frame.py:3718: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._where(-key, value, inplace=True)# (1b)In [12]: dfa[“D”] = dfa[“B”] * 10/tmp/ipykernel_34555/447367411.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“D”] = dfa[“B”] * 10 # 1b# (1c)In [13]: dfa[“A”][3] = 10/tmp/ipykernel_34555/1338713145.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“A”][3] = 10 All of the value assignments took effect on dfa itself, but only (1a) and (1c) affected the original dataframe. (1b) did not. In [14]: print(dfa) A B C D3 10 9 100 904 5 100 15 1000In [15]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15 In addition, dfa is no longer a view, but a copy of the dataframe! In [16]: show_attrs(dfa) # view changed to Falseview: False, copy: <weakref at 0x7fba308565e0; to ‘DataFrame’ at 0x7fba3084eac0> What this tells us is that pandas will convert a view to a copy when necessary. This further shows why figuring out chained assignment is inherently tricky, and is difficult to cater for automatically at the library level. This is the same as scenario 1, but using iloc instead. In [17]: df = make_clean_df() ...: dfb = df.iloc[3:5] ...: show_attrs(dfb)view: True, copy: <weakref at 0x7fba30862040; to ‘DataFrame’ at 0x7fba30868c10># (1a)In [18]: dfb[dfb % 2 == 0] = 100/tmp/ipykernel_34555/734837801.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[dfb % 2 == 0] = 100/home/tnwei/miniconda3/envs/ml/lib/python3.9/site-packages/pandas/core/frame.py:3718: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._where(-key, value, inplace=True)# (1b)In [19]: dfb[“D”] = dfb[“B”] * 10/tmp/ipykernel_34555/4288697762.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[“D”] = dfb[“B”] * 10# (1c)In [20]: dfb[“A”][3] = 10/tmp/ipykernel_34555/2062795903.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[“A”][3] = 10 The observed outcome is the same as Scenario 1. In [21]: print(dfb) A B C D3 10 9 100 904 5 100 15 1000In [22]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15In [23]: show_attrs(dfb)view: False, copy: <weakref at 0x7fba30862040; to ‘DataFrame’ at 0x7fba30868c10> Same as Scenario 1, but the columns are specified as well. In [24]: df = make_clean_df() ...: dfc = df.loc[3:5, [“A”, “B”]] ...: show_attrs(dfc)view: False, copy: NoneIn [25]: dfc[dfc % 2 == 0] = 100 # No warnings raised ...: dfc[“D”] = dfc[“B”] * 10 ...: dfc[“A”][3] = 10 No warnings raised. All changes took effect on `dfc` without impacting `df`. In [26]: print(dfc) A B D3 10 9 904 5 100 1000In [27]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15 The chained assignment outcome is different, while the data indexed is the same as in Scenario 1. My guess is that a more complete description of the indexing operation prompted pandas to directly return a copy upfront, instead of a view that is linked to the original dataframe. This is similar to Scenario 3, but using iloc instead. Given the past few scenarios, it is no surprise that this scenario had the same outcome as Scenario 3. In [28]: df = make_clean_df() ...: dfd = df.iloc[3:5, [0, 1]] ...: show_attrs(dfd)view: False, copy: <weakref at 0x7fba306f29f0; dead>In [29]: dfd[dfd % 2 == 0] = 100 # No warnings raised ...: dfd[“D”] = dfd[“B”] * 10 ...: dfd[“A”][3] = 10In [30]: print(dfd) A B D3 10 9 904 5 100 1000In [31]: print(df) A B C0 1 6 111 2 7 122 3 8 133 4 9 144 5 10 15 In addition, `dfd` discarded the reference to the garbage-collected dataframe at the end of this code. In [32]: show_attrs(dfd)view: False, copy: None This scenario tests chained assignment on series. In [33]: df = make_clean_df() ...: dfe = df[“A”] ...: show_attrs(dfe)view: True, copy: NoneIn [34]: dfe[1] = 99999 # No warnings raised ...: dfe.loc[2:4] = 88888 dfe remained a view of df[“A”]. All changes effected on dfe is reflected in df[“A”], which is still part of df. It appears that there’s not much to worry about for chained assignment on individual series. In [35]: print(dfe)0 11 999992 888883 888884 88888Name: A, dtype: int64In [36]: print(df) A B C0 1 6 111 99999 7 122 88888 8 133 88888 9 144 88888 10 15In [37]: show_attrs(dfe)view: True, copy: None SettingWithCopyWarnings pop up when pandas isn’t sure if you want value assignment to affect the original dataframe or not. Therefore, getting rid of these warnings entails avoiding ambiguity in value assignment. As seen from the code samples above, getting pandas to return copies with no reference to the original dataframe is a clean way to ensure that values will not be written to the original dataframe unintended. I’ve found this to be a unifying thread across the solutions I came across when researching this topic. Summarizing them below: If you know what you’re doing and your code is behaving as intended, you can choose to suppress the warnings by disabling them [3]: # Example borrowed from [3]# Disables SettingWithCopyWarning globallypd.set_option(‘mode.chained_assignment’, None)# Resets the warning option to defaultpd.reset_option(‘mode.chained_assignment’)# Disables SettingWithCopyWarning locally within a context managerwith pd.option_context(‘mode.chained_assignment’, None): # YOUR CODE HERE Alternatively, you can suppress the warnings by setting the dataframe _is_copy attribute to None [3]. # Example modified from [3]In [38]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5)) ...: ...: dfa = df.loc[3:5] ...: print(dfa._is_copy)<weakref at 0x7f4d64792810; to ‘DataFrame’ at 0x7f4d64784460>In [39]: dfa._is_copy = None ...: dfa[“D”] = dfa[“B”] * 10 # No warning raised Remember that making the warnings go away doesn’t resolve wonky chained assignment issues. Chained assignment is a minefield where you might or might not step on a landmine. Disabling the warnings is like removing the minefield warning signs. Food for thought. When you run into a SettingWithCopy warning, take a moment to trace the chained assignment and decide if you want to modify the original dataframe directly, or have values assigned to a copy of the dataframe. Use .loc indexing to directly assign values to the dataframe. # Modified from examples in [2]In [40]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5)) ...: ...: df.loc[df[“A”] % 2 != 0, “B”] = df.loc[df[“A”] % 2 != 0, “B”] + 0.5 ...: print(df)A B C0 1 6.5 111 2 7.0 122 3 8.5 133 4 9.0 144 5 10.5 15 pandas docs recommend this method for two reasons: using .loc is guaranteed to refer to the underlying dataframe it is called on. .iloc does not have this property. .loc indexing replaces what could be chain indexing into a single indexing step. If you refer to the example above under Chained assignment with views and copies, .loc indexing resolves chained indexing into a single __setitem__ call. If you are selecting data using conditionals, you can consider returning a mask instead of a copy of the original dataframe. A mask is a boolean series or dataframe which can conveniently be used in .loc indexing, as the example below: # Modified from examples in [5]In [41]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))In [42]: dfa = (df[“A”] <= 3) & (df[“C”] == 12)In [43]: df.loc[dfa, “B”] = 99 # dfa can be fed into the loc index!In [44]: print(df) # changes took place in the original dataframe A B C0 1 6 111 2 99 122 3 8 133 4 9 144 5 10 15 Working on the original dataframe directly can be tricky if existing indexing logic is complex. In that case, you can always use one of the methods from the next section to return a copy, then assign it back to the original dataframe [4]. Use assign, where and replace: In [45]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))# 1. Use the `assign` method to add columnsIn [46]: df = df.assign(D=df[“C”] * 10) ...: df = df.assign(**{“D”: df[“C”] * 10}) # allows passing variables as names# 2. Use the `where` method to select values using conditionals and replace them# Modified from examples in [2]In [47]: df[“B”] = df[“B”].where( ...: df[“A”] < 2, df[“B”] * 10 ...: )# 3. Use the `replace` method to select and replace values in the dataframe# Modified from examples in [2]In [48]: df = df.replace({“A” : 1}, 100)In [49]: print(df) A B C D0 100 6 11 1101 2 70 12 1202 3 80 13 1303 4 90 14 1404 5 100 15 150 Break down chained assignment steps into single assignments [5]: # Examples borrowed from [4]# Not thesedf[“z”][mask] = 0df.loc[mask][“z”] = 0# But thisdf.loc[mask, “z”] = 0 A less elegant but foolproof method is to manually create a copy of the original dataframe and work on it instead [2]. As long as you don’t introduce additional chained indexing, you will not see the SettingWithCopyWarning. In [50]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))In [51]: dfa = df.loc[3:5].copy() # Added .copy() here ...: dfa.loc[3, “A”] = 10 # causes this line to raise no warning Replace a chained assignment with where: # (i)df = make_clean_df()dfa = df.loc[3:5]# Original that raises warning# dfa[dfa % 2 == 0] = 100dfa = dfa.where(dfa % 2 != 0, 100) # df is not affected Replace creating a new column on the indexed dataframe with assign: # (ii) df = make_clean_df()# Original that raises warning# dfa[“D”] = dfa[“B”] * 10dfa = dfa.assign(D=dfa[“B”]*10) # df is not affected Creating a copy of the dataframe, before assigning values using .loc indexing: # (iii)df = make_clean_df()# Original that raises warnings# dfa = df.loc[3:5]# dfa[“A”][3] = 10# Create a copy then do loc indexingdfa = df.loc[3:5].copy()dfa.loc[3, “A”] = 10 Note that directly assigning values to dfa using .loc indexing will still raise a warning, as it is ambiguous if the assignment to dfa should also affect df. Personally, I am a fan of promoting SettingWithCopyWarnings to SettingWithCopyExceptions for important scripts, using the following code: pd.set_option(‘mode.chained_assignment’, “raise”) Doing this forces chained assignment to be dealt with, rather than allowing warnings to accumulate. In my experience, cleaning up notebooks with stderr clogged by SettingWithCopyWarnings is its special kind of zen. I wholeheartedly recommend it. Original blogpost: SettingWithCopyWarnings in pandas [1]: Official `pandas` docs on chained assignment.[https://pandas.pydata.org/docs/user_guide/indexing.html#returning-a-view-versus-a-copy](https://pandas.pydata.org/docs/user_guide/indexing.html#returning-a-view-versus-a-copy) [2]: TowardsDataScience article that briefly touches on a few ways to deal with the SettingWithCopy warnings.[https://scribe.rip/@towardsdatascience.com/3-solutions-for-the-setting-with-copy-warning-of-python-pandas-dfe15d62de08](https://scribe.rip/@towardsdatascience.com/3-solutions-for-the-setting-with-copy-warning-of-python-pandas-dfe15d62de08) [3]: In-depth article on this topic by DataQuest. Notably, there is a section dedicated to the history of dealing with chained assignment in `pandas`.[https://www.dataquest.io/blog/settingwithcopywarning/](https://www.dataquest.io/blog/settingwithcopywarning/) [4]: StackOverflow post that contains more chained assignment examples. [https://stackoverflow.com/questions/48173980/pandas-knowing-when-an-operation-affects-the-original-dataframe](https://stackoverflow.com/questions/48173980/pandas-knowing-when-an-operation-affects-the-original-dataframe) [5]: RealPython article covering this topic. For me, RealPython is a trusted goto reference second to official library docs. This article further goes into depth on the underlying view vs copy mechanisms in pandas, and in numpy, which pandas depends on.[https://realpython.com/pandas-settingwithcopywarning/](https://realpython.com/pandas-settingwithcopywarning/)
[ { "code": null, "e": 257, "s": 165, "text": "(tl;dr: jump straight to Getting rid of SettingWithCopyWarnings if you’re here for answers)" }, { "code": null, "e": 403, "s": 257, "text": "If you are a pandas user, chances are you’ve seen the SettingWithCopyWarning crop up when you’re assigning values to a pd.DataFrame or pd.Series." }, { "code": null, "e": 984, "s": 403, "text": "In [1]: import pandas as pd ...: ...: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: }, index=range(5) ...: ) ...: dfa = df.loc[3:5] ...: dfa[“C”] = dfa[“B”] * 50<ipython-input-2–63497d1da3d9>:9: SettingWithCopyWarning:A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“C”] = dfa[“B”] * 50" }, { "code": null, "e": 1085, "s": 984, "text": "pandas drops a warning here because the value assignment might or might not have worked as expected." }, { "code": null, "e": 1176, "s": 1085, "text": "To be clear, the value assignment did occur all right; the emphasis here is on “expected”." }, { "code": null, "e": 1269, "s": 1176, "text": "In [2]: dfaOut[2]: A B C3 4 9 4504 5 10 500In [3]: dfOut[3]: A B0 1 61 2 72 3 83 4 94 5 10" }, { "code": null, "e": 1611, "s": 1269, "text": "Did you expect the contents of dfto be affected by the value assignment in dfa? pandas has internally consistent (albeit obtuse) rules on whether that happens or not. It’s just that the ambiguity in user expectations present in this situation warrants a warning, so that end users like you and me know where to look when our code misbehaves." }, { "code": null, "e": 1837, "s": 1611, "text": "The act of selecting rows or columns to access from a dataframe or series is called indexing. The flexibility of pandas allows for chained indexing, where you can repeatedly index the outcome of a previous indexing operation." }, { "code": null, "e": 1944, "s": 1837, "text": "# Select the 2nd to 4th row of data where col A > 3 and col B != 7df[df[“A”] > 3 & df[“B”] != 7].iloc[3:5]" }, { "code": null, "e": 2143, "s": 1944, "text": "pandas will then return either a view or a copy of the dataframe. A view (shallow copy) references data from the original dataframe, while a copy (deep copy) is a separate instance of the same data." }, { "code": null, "e": 2431, "s": 2143, "text": "It is difficult to predict which will be returned by the indexing operation, as it depends on the memory layout of the underlying array. How exactly the indexing is chained can lead to different __getitem__ and __setitem__ calls being issued under the hood. Reproducing an example below:" }, { "code": null, "e": 2657, "s": 2431, "text": "# Example borrowed from [1]dfmi.loc[:, (‘one’, ‘second’)] = value# becomesdfmi.loc.__setitem__((slice(None), (‘one’, ‘second’)), value)dfmi[‘one’][‘second’] = value# becomesdfmi.__getitem__(‘one’).__setitem__(‘second’, value)" }, { "code": null, "e": 3021, "s": 2657, "text": "Chain indexing inherently is not a problem, but assigning values using chained indexing, i.e. chained assignment, can be. Depending on the situation, chained assignment will either modify the original dataframe directly, or return a modified copy of the original dataframe. This can lead to insidious bugs when it is not obvious that chained indexing has occured." }, { "code": null, "e": 3082, "s": 3021, "text": "Chained indexing can take places across a few lines of code:" }, { "code": null, "e": 3212, "s": 3082, "text": "# The following doesn’t look like chain indexing, does it?dfa = df.loc[row1:row2, col1:col2]......dfa[row2] = dfa[row1].apply(fn)" }, { "code": null, "e": 3391, "s": 3212, "text": "If pandas did not raise a warning in this scenario, it would not be obvious that df is not modified by the second value assignment. This is why the SettingWithCopyWarning exists." }, { "code": null, "e": 3721, "s": 3391, "text": "pandas docs [1] go into this with more detail. The warning message helpfully links to it, which is great because if you search pandas settingwithcopywarning on Google, the docs page is easy to miss! At time of writing, it is the 7th result on the first page of Google, and is crowded out by blogposts and StackOverflow questions." }, { "code": null, "e": 4066, "s": 3721, "text": "Chained indexing is a godsend of convenience for selecting the right data, but chained assignment is a minefield for assigning the correct values. The TowardsDataScience article in [2] has a nice example where inverting the order of chained indexing alone is the difference between whether an assignment to the original dataframe occurs or not:" }, { "code": null, "e": 4321, "s": 4066, "text": "# Example borrowed from [2]# This updates `df`df[“product_group”][df[“product_group”]==”PG4\"] = “PG14”# This doesn’t!df[df[“product_group”]==”PG4\"][“product_group”] = “PG14”# pandas raises warnings for both# the user needs to confirm the intended outcome" }, { "code": null, "e": 4668, "s": 4321, "text": "From this StackOverflow post, pd.DataFrame and pd.Series objects have _is_view and _is_copy attributes as part of their internal API. _is_view returns True if the object is a view, and False if the object is not. _is_copy stores either a weak reference to the dataframe it is copied from, or None if it is not associated to an existing dataframe." }, { "code": null, "e": 5008, "s": 4668, "text": "Printing these internal attributes while poking around with chained assignment does reveal some interesting tidbits of info. On one hand, pandas uses _is_copy to decide if a SettingWithCopyWarning needs to be raised. On the other hand, modifying a dataframe with _is_view = True means that it will affect the original underlying dataframe." }, { "code": null, "e": 5152, "s": 5008, "text": "Before we begin, a disclaimer: internal APIs are not meant to be accessed by the end user and are subject to change, use them at your own risk." }, { "code": null, "e": 5575, "s": 5152, "text": "In [4]: pd.__version__Out[4]: ‘1.3.3’# Setting up convenience functionsIn [5]: def make_clean_df(): ...: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5) ...: ) ...: return dfIn [6]: def show_attrs(obj): ...: print(f”view: {obj._is_view}, copy: {obj._is_copy}”)" }, { "code": null, "e": 5669, "s": 5575, "text": "We’ll start by showing the _is_view and _is_copy attributes of a few common indexing methods." }, { "code": null, "e": 6192, "s": 5669, "text": "In [7]: df = make_clean_df()In [8]: show_attrs(df.loc[3:5]) ...: show_attrs(df.iloc[3:5]) ...: show_attrs(df.loc[3:5, [“A”, “B”]]) ...: show_attrs(df.iloc[3:5, [0, 1]]) ...: show_attrs(df[“A”]) ...: show_attrs(df.loc[:, “A”])view: True, copy: <weakref at 0x7f4d648b2590; to ‘DataFrame’ at 0x7f4d648b54c0>view: True, copy: <weakref at 0x7f4d648b2590; to ‘DataFrame’ at 0x7f4d648b54c0>view: False, copy: Noneview: False, copy: <weakref at 0x7f4d648be770; dead>view: True, copy: Noneview: True, copy: None" }, { "code": null, "e": 6215, "s": 6192, "text": "Let’s break this down:" }, { "code": null, "e": 6311, "s": 6215, "text": "Both df.loc[3:5] and df.iloc[3:5] returned views and have references to the original dataframe." }, { "code": null, "e": 6708, "s": 6311, "text": "For df.loc[3:5, [“A”, “B”]] and df.iloc[3:5, [0, 1]] , when the columns are additionally specified on top of the rows, copies of df are returned instead. Using .loc indexing has no references to the OG dataframe, while using iloc indexing results in a reference to a temporary dataframe that has been garbage collected, which is as good as None itself. We’ll see if this carries any significance." }, { "code": null, "e": 6935, "s": 6708, "text": "Referring to a column directly using either df[“A”] or df.loc[:, “A”] returns a view, with no reference to the original dataframe. It might have to do with the fact that each dataframe column is actually stored as a pd.Series." }, { "code": null, "e": 7015, "s": 6935, "text": "What happens if we manually create copies of these indexed dataframes / series?" }, { "code": null, "e": 7413, "s": 7015, "text": "In [9]: show_attrs(df.loc[3:5].copy()) ...: show_attrs(df.iloc[3:5].copy()) ...: show_attrs(df.loc[3:5, [“A”, “B”]].copy()) ...: show_attrs(df.iloc[3:5, [0, 1]].copy()) ...: show_attrs(df[“A”].copy()) ...: show_attrs(df.loc[:, “A”].copy())view: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: Noneview: False, copy: None" }, { "code": null, "e": 7841, "s": 7413, "text": "Explicitly calling .copy returns copies of data that have no reference to the original dataframe / series. Assigning data on these copies will not affect the original dataframe, and thus will not trigger SettingwithCopyWarnings. Given that df.loc[3:5, [“A”, “B”]] and df.iloc[3:5, [0, 1]] above have similar attributes, we can expect that their behaviour under chained assignment should be similar to explicitly created copies." }, { "code": null, "e": 7893, "s": 7841, "text": "Next, we’ll try a few chained assignment scenarios." }, { "code": null, "e": 7964, "s": 7893, "text": "The following three chained assignments raise SettingWithCopyWarnings:" }, { "code": null, "e": 9564, "s": 7964, "text": "In [10]: df = make_clean_df() ...: dfa = df.loc[3:5] ...: show_attrs(dfa)view: True, copy: <weakref at 0x7fba308565e0; to ‘DataFrame’ at 0x7fba3084eac0># (1a)In [11]: dfa[dfa % 2 == 0] = 100/tmp/ipykernel_34555/3321004726.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[dfa % 2 == 0] = 100/home/tnwei/miniconda3/envs/ml/lib/python3.9/site-packages/pandas/core/frame.py:3718: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._where(-key, value, inplace=True)# (1b)In [12]: dfa[“D”] = dfa[“B”] * 10/tmp/ipykernel_34555/447367411.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“D”] = dfa[“B”] * 10 # 1b# (1c)In [13]: dfa[“A”][3] = 10/tmp/ipykernel_34555/1338713145.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfa[“A”][3] = 10" }, { "code": null, "e": 9690, "s": 9564, "text": "All of the value assignments took effect on dfa itself, but only (1a) and (1c) affected the original dataframe. (1b) did not." }, { "code": null, "e": 9833, "s": 9690, "text": "In [14]: print(dfa) A B C D3 10 9 100 904 5 100 15 1000In [15]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15" }, { "code": null, "e": 9900, "s": 9833, "text": "In addition, dfa is no longer a view, but a copy of the dataframe!" }, { "code": null, "e": 10029, "s": 9900, "text": "In [16]: show_attrs(dfa) # view changed to Falseview: False, copy: <weakref at 0x7fba308565e0; to ‘DataFrame’ at 0x7fba3084eac0>" }, { "code": null, "e": 10252, "s": 10029, "text": "What this tells us is that pandas will convert a view to a copy when necessary. This further shows why figuring out chained assignment is inherently tricky, and is difficult to cater for automatically at the library level." }, { "code": null, "e": 10308, "s": 10252, "text": "This is the same as scenario 1, but using iloc instead." }, { "code": null, "e": 11904, "s": 10308, "text": "In [17]: df = make_clean_df() ...: dfb = df.iloc[3:5] ...: show_attrs(dfb)view: True, copy: <weakref at 0x7fba30862040; to ‘DataFrame’ at 0x7fba30868c10># (1a)In [18]: dfb[dfb % 2 == 0] = 100/tmp/ipykernel_34555/734837801.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[dfb % 2 == 0] = 100/home/tnwei/miniconda3/envs/ml/lib/python3.9/site-packages/pandas/core/frame.py:3718: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._where(-key, value, inplace=True)# (1b)In [19]: dfb[“D”] = dfb[“B”] * 10/tmp/ipykernel_34555/4288697762.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value insteadSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[“D”] = dfb[“B”] * 10# (1c)In [20]: dfb[“A”][3] = 10/tmp/ipykernel_34555/2062795903.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrameSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy dfb[“A”][3] = 10" }, { "code": null, "e": 11952, "s": 11904, "text": "The observed outcome is the same as Scenario 1." }, { "code": null, "e": 12203, "s": 11952, "text": "In [21]: print(dfb) A B C D3 10 9 100 904 5 100 15 1000In [22]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15In [23]: show_attrs(dfb)view: False, copy: <weakref at 0x7fba30862040; to ‘DataFrame’ at 0x7fba30868c10>" }, { "code": null, "e": 12262, "s": 12203, "text": "Same as Scenario 1, but the columns are specified as well." }, { "code": null, "e": 12496, "s": 12262, "text": "In [24]: df = make_clean_df() ...: dfc = df.loc[3:5, [“A”, “B”]] ...: show_attrs(dfc)view: False, copy: NoneIn [25]: dfc[dfc % 2 == 0] = 100 # No warnings raised ...: dfc[“D”] = dfc[“B”] * 10 ...: dfc[“A”][3] = 10" }, { "code": null, "e": 12573, "s": 12496, "text": "No warnings raised. All changes took effect on `dfc` without impacting `df`." }, { "code": null, "e": 12710, "s": 12573, "text": "In [26]: print(dfc) A B D3 10 9 904 5 100 1000In [27]: print(df) A B C0 1 6 111 2 7 122 3 8 133 10 9 1004 5 100 15" }, { "code": null, "e": 12990, "s": 12710, "text": "The chained assignment outcome is different, while the data indexed is the same as in Scenario 1. My guess is that a more complete description of the indexing operation prompted pandas to directly return a copy upfront, instead of a view that is linked to the original dataframe." }, { "code": null, "e": 13148, "s": 12990, "text": "This is similar to Scenario 3, but using iloc instead. Given the past few scenarios, it is no surprise that this scenario had the same outcome as Scenario 3." }, { "code": null, "e": 13532, "s": 13148, "text": "In [28]: df = make_clean_df() ...: dfd = df.iloc[3:5, [0, 1]] ...: show_attrs(dfd)view: False, copy: <weakref at 0x7fba306f29f0; dead>In [29]: dfd[dfd % 2 == 0] = 100 # No warnings raised ...: dfd[“D”] = dfd[“B”] * 10 ...: dfd[“A”][3] = 10In [30]: print(dfd) A B D3 10 9 904 5 100 1000In [31]: print(df) A B C0 1 6 111 2 7 122 3 8 133 4 9 144 5 10 15" }, { "code": null, "e": 13635, "s": 13532, "text": "In addition, `dfd` discarded the reference to the garbage-collected dataframe at the end of this code." }, { "code": null, "e": 13683, "s": 13635, "text": "In [32]: show_attrs(dfd)view: False, copy: None" }, { "code": null, "e": 13733, "s": 13683, "text": "This scenario tests chained assignment on series." }, { "code": null, "e": 13910, "s": 13733, "text": "In [33]: df = make_clean_df() ...: dfe = df[“A”] ...: show_attrs(dfe)view: True, copy: NoneIn [34]: dfe[1] = 99999 # No warnings raised ...: dfe.loc[2:4] = 88888" }, { "code": null, "e": 14115, "s": 13910, "text": "dfe remained a view of df[“A”]. All changes effected on dfe is reflected in df[“A”], which is still part of df. It appears that there’s not much to worry about for chained assignment on individual series." }, { "code": null, "e": 14323, "s": 14115, "text": "In [35]: print(dfe)0 11 999992 888883 888884 88888Name: A, dtype: int64In [36]: print(df) A B C0 1 6 111 99999 7 122 88888 8 133 88888 9 144 88888 10 15In [37]: show_attrs(dfe)view: True, copy: None" }, { "code": null, "e": 14744, "s": 14323, "text": "SettingWithCopyWarnings pop up when pandas isn’t sure if you want value assignment to affect the original dataframe or not. Therefore, getting rid of these warnings entails avoiding ambiguity in value assignment. As seen from the code samples above, getting pandas to return copies with no reference to the original dataframe is a clean way to ensure that values will not be written to the original dataframe unintended." }, { "code": null, "e": 14872, "s": 14744, "text": "I’ve found this to be a unifying thread across the solutions I came across when researching this topic. Summarizing them below:" }, { "code": null, "e": 15004, "s": 14872, "text": "If you know what you’re doing and your code is behaving as intended, you can choose to suppress the warnings by disabling them [3]:" }, { "code": null, "e": 15342, "s": 15004, "text": "# Example borrowed from [3]# Disables SettingWithCopyWarning globallypd.set_option(‘mode.chained_assignment’, None)# Resets the warning option to defaultpd.reset_option(‘mode.chained_assignment’)# Disables SettingWithCopyWarning locally within a context managerwith pd.option_context(‘mode.chained_assignment’, None): # YOUR CODE HERE" }, { "code": null, "e": 15444, "s": 15342, "text": "Alternatively, you can suppress the warnings by setting the dataframe _is_copy attribute to None [3]." }, { "code": null, "e": 15856, "s": 15444, "text": "# Example modified from [3]In [38]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5)) ...: ...: dfa = df.loc[3:5] ...: print(dfa._is_copy)<weakref at 0x7f4d64792810; to ‘DataFrame’ at 0x7f4d64784460>In [39]: dfa._is_copy = None ...: dfa[“D”] = dfa[“B”] * 10 # No warning raised" }, { "code": null, "e": 16117, "s": 15856, "text": "Remember that making the warnings go away doesn’t resolve wonky chained assignment issues. Chained assignment is a minefield where you might or might not step on a landmine. Disabling the warnings is like removing the minefield warning signs. Food for thought." }, { "code": null, "e": 16326, "s": 16117, "text": "When you run into a SettingWithCopy warning, take a moment to trace the chained assignment and decide if you want to modify the original dataframe directly, or have values assigned to a copy of the dataframe." }, { "code": null, "e": 16388, "s": 16326, "text": "Use .loc indexing to directly assign values to the dataframe." }, { "code": null, "e": 16708, "s": 16388, "text": "# Modified from examples in [2]In [40]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5)) ...: ...: df.loc[df[“A”] % 2 != 0, “B”] = df.loc[df[“A”] % 2 != 0, “B”] + 0.5 ...: print(df)A B C0 1 6.5 111 2 7.0 122 3 8.5 133 4 9.0 144 5 10.5 15" }, { "code": null, "e": 16759, "s": 16708, "text": "pandas docs recommend this method for two reasons:" }, { "code": null, "e": 16873, "s": 16759, "text": "using .loc is guaranteed to refer to the underlying dataframe it is called on. .iloc does not have this property." }, { "code": null, "e": 17108, "s": 16873, "text": ".loc indexing replaces what could be chain indexing into a single indexing step. If you refer to the example above under Chained assignment with views and copies, .loc indexing resolves chained indexing into a single __setitem__ call." }, { "code": null, "e": 17344, "s": 17108, "text": "If you are selecting data using conditionals, you can consider returning a mask instead of a copy of the original dataframe. A mask is a boolean series or dataframe which can conveniently be used in .loc indexing, as the example below:" }, { "code": null, "e": 17779, "s": 17344, "text": "# Modified from examples in [5]In [41]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))In [42]: dfa = (df[“A”] <= 3) & (df[“C”] == 12)In [43]: df.loc[dfa, “B”] = 99 # dfa can be fed into the loc index!In [44]: print(df) # changes took place in the original dataframe A B C0 1 6 111 2 99 122 3 8 133 4 9 144 5 10 15" }, { "code": null, "e": 18018, "s": 17779, "text": "Working on the original dataframe directly can be tricky if existing indexing logic is complex. In that case, you can always use one of the methods from the next section to return a copy, then assign it back to the original dataframe [4]." }, { "code": null, "e": 18049, "s": 18018, "text": "Use assign, where and replace:" }, { "code": null, "e": 18835, "s": 18049, "text": "In [45]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))# 1. Use the `assign` method to add columnsIn [46]: df = df.assign(D=df[“C”] * 10) ...: df = df.assign(**{“D”: df[“C”] * 10}) # allows passing variables as names# 2. Use the `where` method to select values using conditionals and replace them# Modified from examples in [2]In [47]: df[“B”] = df[“B”].where( ...: df[“A”] < 2, df[“B”] * 10 ...: )# 3. Use the `replace` method to select and replace values in the dataframe# Modified from examples in [2]In [48]: df = df.replace({“A” : 1}, 100)In [49]: print(df) A B C D0 100 6 11 1101 2 70 12 1202 3 80 13 1303 4 90 14 1404 5 100 15 150" }, { "code": null, "e": 18900, "s": 18835, "text": "Break down chained assignment steps into single assignments [5]:" }, { "code": null, "e": 19009, "s": 18900, "text": "# Examples borrowed from [4]# Not thesedf[“z”][mask] = 0df.loc[mask][“z”] = 0# But thisdf.loc[mask, “z”] = 0" }, { "code": null, "e": 19233, "s": 19009, "text": "A less elegant but foolproof method is to manually create a copy of the original dataframe and work on it instead [2]. As long as you don’t introduce additional chained indexing, you will not see the SettingWithCopyWarning." }, { "code": null, "e": 19529, "s": 19233, "text": "In [50]: df = pd.DataFrame({ ...: “A”: [1, 2, 3, 4, 5], ...: “B”: [6, 7, 8, 9, 10], ...: “C”: [11, 12, 13, 14, 15], ...: }, index=range(5))In [51]: dfa = df.loc[3:5].copy() # Added .copy() here ...: dfa.loc[3, “A”] = 10 # causes this line to raise no warning" }, { "code": null, "e": 19570, "s": 19529, "text": "Replace a chained assignment with where:" }, { "code": null, "e": 19723, "s": 19570, "text": "# (i)df = make_clean_df()dfa = df.loc[3:5]# Original that raises warning# dfa[dfa % 2 == 0] = 100dfa = dfa.where(dfa % 2 != 0, 100) # df is not affected" }, { "code": null, "e": 19791, "s": 19723, "text": "Replace creating a new column on the indexed dataframe with assign:" }, { "code": null, "e": 19927, "s": 19791, "text": "# (ii) df = make_clean_df()# Original that raises warning# dfa[“D”] = dfa[“B”] * 10dfa = dfa.assign(D=dfa[“B”]*10) # df is not affected" }, { "code": null, "e": 20006, "s": 19927, "text": "Creating a copy of the dataframe, before assigning values using .loc indexing:" }, { "code": null, "e": 20182, "s": 20006, "text": "# (iii)df = make_clean_df()# Original that raises warnings# dfa = df.loc[3:5]# dfa[“A”][3] = 10# Create a copy then do loc indexingdfa = df.loc[3:5].copy()dfa.loc[3, “A”] = 10" }, { "code": null, "e": 20340, "s": 20182, "text": "Note that directly assigning values to dfa using .loc indexing will still raise a warning, as it is ambiguous if the assignment to dfa should also affect df." }, { "code": null, "e": 20478, "s": 20340, "text": "Personally, I am a fan of promoting SettingWithCopyWarnings to SettingWithCopyExceptions for important scripts, using the following code:" }, { "code": null, "e": 20528, "s": 20478, "text": "pd.set_option(‘mode.chained_assignment’, “raise”)" }, { "code": null, "e": 20628, "s": 20528, "text": "Doing this forces chained assignment to be dealt with, rather than allowing warnings to accumulate." }, { "code": null, "e": 20774, "s": 20628, "text": "In my experience, cleaning up notebooks with stderr clogged by SettingWithCopyWarnings is its special kind of zen. I wholeheartedly recommend it." }, { "code": null, "e": 20827, "s": 20774, "text": "Original blogpost: SettingWithCopyWarnings in pandas" }, { "code": null, "e": 21054, "s": 20827, "text": "[1]: Official `pandas` docs on chained assignment.[https://pandas.pydata.org/docs/user_guide/indexing.html#returning-a-view-versus-a-copy](https://pandas.pydata.org/docs/user_guide/indexing.html#returning-a-view-versus-a-copy)" }, { "code": null, "e": 21404, "s": 21054, "text": "[2]: TowardsDataScience article that briefly touches on a few ways to deal with the SettingWithCopy warnings.[https://scribe.rip/@towardsdatascience.com/3-solutions-for-the-setting-with-copy-warning-of-python-pandas-dfe15d62de08](https://scribe.rip/@towardsdatascience.com/3-solutions-for-the-setting-with-copy-warning-of-python-pandas-dfe15d62de08)" }, { "code": null, "e": 21665, "s": 21404, "text": "[3]: In-depth article on this topic by DataQuest. Notably, there is a section dedicated to the history of dealing with chained assignment in `pandas`.[https://www.dataquest.io/blog/settingwithcopywarning/](https://www.dataquest.io/blog/settingwithcopywarning/)" }, { "code": null, "e": 21958, "s": 21665, "text": "[4]: StackOverflow post that contains more chained assignment examples. [https://stackoverflow.com/questions/48173980/pandas-knowing-when-an-operation-affects-the-original-dataframe](https://stackoverflow.com/questions/48173980/pandas-knowing-when-an-operation-affects-the-original-dataframe)" } ]
How to update the date format in MySQL?
Let us first create a table − mysql> create table DemoTable630 (ArrivalDate varchar(100)); Query OK, 0 rows affected (0.55 sec) Insert some records in the table using insert command − mysql> insert into DemoTable630 values('2015-21-01'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable630 values('2018-25-12'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable630 values('2019-15-07'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable630 values('2016-31-03'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable630; This will produce the following output − +-------------+ | ArrivalDate | +-------------+ | 2015-21-01 | | 2018-25-12 | | 2019-15-07 | | 2016-31-03 | +-------------+ 4 rows in set (0.00 sec) Following is the query to convert date format − mysql> select str_to_date(ArrivalDate,'%Y-%d-%m') from DemoTable630; This will produce the following output − +-------------------------------------+ | str_to_date(ArrivalDate,'%Y-%d-%m') | +-------------------------------------+ | 2015-01-21 | | 2018-12-25 | | 2019-07-15 | | 2016-03-31 | +-------------------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1190, "s": 1092, "text": "mysql> create table DemoTable630 (ArrivalDate varchar(100));\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1246, "s": 1190, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1606, "s": 1246, "text": "mysql> insert into DemoTable630 values('2015-21-01');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable630 values('2018-25-12');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable630 values('2019-15-07');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable630 values('2016-31-03');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1666, "s": 1606, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1700, "s": 1666, "text": "mysql> select *from DemoTable630;" }, { "code": null, "e": 1741, "s": 1700, "text": "This will produce the following output −" }, { "code": null, "e": 1894, "s": 1741, "text": "+-------------+\n| ArrivalDate |\n+-------------+\n| 2015-21-01 |\n| 2018-25-12 |\n| 2019-15-07 |\n| 2016-31-03 |\n+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 1942, "s": 1894, "text": "Following is the query to convert date format −" }, { "code": null, "e": 2011, "s": 1942, "text": "mysql> select str_to_date(ArrivalDate,'%Y-%d-%m') from DemoTable630;" }, { "code": null, "e": 2052, "s": 2011, "text": "This will produce the following output −" }, { "code": null, "e": 2397, "s": 2052, "text": "+-------------------------------------+\n| str_to_date(ArrivalDate,'%Y-%d-%m') |\n+-------------------------------------+\n| 2015-01-21 |\n| 2018-12-25 |\n| 2019-07-15 |\n| 2016-03-31 |\n+-------------------------------------+\n4 rows in set (0.00 sec)" } ]
Count triplets with sum smaller than a given value - GeeksforGeeks
14 Jun, 2021 Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: Input : arr[] = {-2, 0, 1, 3} sum = 2. Output : 2 Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3) Input : arr[] = {5, 1, 3, 4, 7} sum = 12. Output : 4 Explanation : Below are triplets with sum less than 12 (1, 3, 4), (1, 3, 5), (1, 3, 7) and (1, 4, 5) A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and increment count if the triplet sum is smaller than the given sum. C++ Java Python 3 C# Javascript // A Simple C++ program to count triplets with sum smaller// than a given value#include<bits/stdc++.h>using namespace std; int countTriplets(int arr[], int n, int sum){ // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans;} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; cout << countTriplets(arr, n, sum) << endl; return 0;} // A Simple Java program to count triplets with sum smaller// than a given value class Test{ static int arr[] = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function public static void main(String[] args) { int sum = 12; System.out.println(countTriplets(arr.length, sum)); }} # A Simple Python 3 program to count triplets with sum smaller# than a given value#include<bits/stdc++.h>def countTriplets(arr, n, sum): # Initialize result ans = 0 # Fix the first element as A[i] for i in range( 0 ,n-2): # Fix the second element as A[j] for j in range( i+1 ,n-1): # Now look for the third number for k in range( j+1, n): if (arr[i] + arr[j] + arr[k] < sum): ans+=1 return ans # Driver programarr = [5, 1, 3, 4, 7]n = len(arr)sum = 12print(countTriplets(arr, n, sum)) #Contributed by Smitha // A Simple C# program to count triplets with sum smaller// than a given value using System;class Test{ static int[] arr = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function public static void Main() { int sum = 12; Console.Write(countTriplets(arr.Length, sum)); }} <script>// A Simple Javascript program to count triplets with sum smaller// than a given value let arr = [5, 1, 3, 4, 7]; function countTriplets(n,sum) { // Initialize result let ans = 0; // Fix the first element as A[i] for (let i = 0; i < n-2; i++) { // Fix the second element as A[j] for (let j = i + 1; j < n-1; j++) { // Now look for the third number for (let k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function let sum = 12; document.write(countTriplets(arr.length, sum)); // This code is contributed by avanitrachhadiya2155 </script> Output: 4 The time complexity of the above solution is O(n3). An Efficient Solution can count triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop. 1) Sort the input array in increasing order. 2) Initialize result as 0. 3) Run a loop from i = 0 to n-2. An iteration of this loop finds all triplets with arr[i] as first element. a) Initialize other two elements as corner elements of subarray arr[i+1..n-1], i.e., j = i+1 and k = n-1 b) Move j and k toward each other until they meet, i.e., while (j<k), (i) If arr[i] + arr[j] + arr[k] >= sum then k-- // Else for current i and j, there can (k-j) possible third elements // that satisfy the constraint. (ii) Else Do ans += (k - j) followed by j++ Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to count triplets with sum smaller than a given value#include<bits/stdc++.h>using namespace std; int countTriplets(int arr[], int n, int sum){ // Sort input array sort(arr, arr+n); // Initialize result int ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans;} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; cout << countTriplets(arr, n, sum) << endl; return 0;} // A Simple Java program to count triplets with sum smaller// than a given value import java.util.Arrays; class Test{ static int arr[] = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Sort input array Arrays.sort(arr); // Initialize result int ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver method to test the above function public static void main(String[] args) { int sum = 12; System.out.println(countTriplets(arr.length, sum)); }} # Python3 program to count triplets with# sum smaller than a given value # Function to count triplets with sum smaller# than a given value def countTriplets(arr,n,sum): # Sort input array arr.sort() # Initialize result ans = 0 # Every iteration of loop counts triplet with # first element as arr[i]. for i in range(0,n-2): # Initialize other two elements as corner elements # of subarray arr[j+1..k] j = i + 1 k = n-1 # Use Meet in the Middle concept while(j < k): # If sum of current triplet is more or equal, # move right corner to look for smaller values if (arr[i]+arr[j]+arr[k] >=sum): k = k-1 # Else move left corner else: # This is important. For current i and j, there # can be total k-j third elements. ans += (k - j) j = j+1 return ans # Driver programif __name__=='__main__': arr = [5, 1, 3, 4, 7] n = len(arr) sum = 12 print(countTriplets(arr, n, sum)) # This code is contributed by# Yatin Gupta // A Simple C# program to count// triplets with sum smaller// than a given valueusing System; class GFG{ static int []arr = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Sort input array Array.Sort(arr); // Initialize result int ans = 0; // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two // elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver Code public static void Main() { int sum = 12; Console.Write(countTriplets(arr.Length, sum)); }} // This code is contributed by Smitha <script>// A Simple Javascript program to count triplets with sum smaller// than a given value let arr = [5, 1, 3, 4, 7]; function countTriplets(n,sum) { // Sort input array arr.sort(function(a,b){return b-a}); // Initialize result let ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (let i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] let j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver method to test the above function let sum = 12; document.write(countTriplets(arr.length, sum)); // This code is contributed by rag2127</script> Output: 4 YouTubeGeeksforGeeks500K subscribersCount triplets with sum smaller than a given value | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=7nso5Dgc6CI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Thanks to Gaurav Ahirwar for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Smitha Dinesh Semwal YatinGupta ukasp AnuragTripathy avanitrachhadiya2155 rag2127 iamdhavalparmar Amazon SAP Labs Arrays Amazon SAP Labs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Linked List vs Array Python | Using 2D arrays/lists the right way Maximum and minimum of an array using minimum number of comparisons Given an array of size n and a number k, find all elements that appear more than n/k times
[ { "code": null, "e": 25049, "s": 25021, "text": "\n14 Jun, 2021" }, { "code": null, "e": 25214, "s": 25049, "text": "Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value. The expected Time Complexity is O(n2).Examples: " }, { "code": null, "e": 25564, "s": 25214, "text": "Input : arr[] = {-2, 0, 1, 3}\n sum = 2.\nOutput : 2\nExplanation : Below are triplets with sum less than 2\n (-2, 0, 1) and (-2, 0, 3) \n\nInput : arr[] = {5, 1, 3, 4, 7}\n sum = 12.\nOutput : 4\nExplanation : Below are triplets with sum less than 12\n (1, 3, 4), (1, 3, 5), (1, 3, 7) and \n (1, 4, 5)" }, { "code": null, "e": 25751, "s": 25566, "text": "A Simple Solution is to run three loops to consider all triplets one by one. For every triplet, compare the sums and increment count if the triplet sum is smaller than the given sum. " }, { "code": null, "e": 25755, "s": 25751, "text": "C++" }, { "code": null, "e": 25760, "s": 25755, "text": "Java" }, { "code": null, "e": 25769, "s": 25760, "text": "Python 3" }, { "code": null, "e": 25772, "s": 25769, "text": "C#" }, { "code": null, "e": 25783, "s": 25772, "text": "Javascript" }, { "code": "// A Simple C++ program to count triplets with sum smaller// than a given value#include<bits/stdc++.h>using namespace std; int countTriplets(int arr[], int n, int sum){ // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans;} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; cout << countTriplets(arr, n, sum) << endl; return 0;}", "e": 26519, "s": 25783, "text": null }, { "code": "// A Simple Java program to count triplets with sum smaller// than a given value class Test{ static int arr[] = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function public static void main(String[] args) { int sum = 12; System.out.println(countTriplets(arr.length, sum)); }}", "e": 27362, "s": 26519, "text": null }, { "code": "# A Simple Python 3 program to count triplets with sum smaller# than a given value#include<bits/stdc++.h>def countTriplets(arr, n, sum): # Initialize result ans = 0 # Fix the first element as A[i] for i in range( 0 ,n-2): # Fix the second element as A[j] for j in range( i+1 ,n-1): # Now look for the third number for k in range( j+1, n): if (arr[i] + arr[j] + arr[k] < sum): ans+=1 return ans # Driver programarr = [5, 1, 3, 4, 7]n = len(arr)sum = 12print(countTriplets(arr, n, sum)) #Contributed by Smitha", "e": 27972, "s": 27362, "text": null }, { "code": "// A Simple C# program to count triplets with sum smaller// than a given value using System;class Test{ static int[] arr = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Initialize result int ans = 0; // Fix the first element as A[i] for (int i = 0; i < n-2; i++) { // Fix the second element as A[j] for (int j = i+1; j < n-1; j++) { // Now look for the third number for (int k = j+1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function public static void Main() { int sum = 12; Console.Write(countTriplets(arr.Length, sum)); }}", "e": 28813, "s": 27972, "text": null }, { "code": "<script>// A Simple Javascript program to count triplets with sum smaller// than a given value let arr = [5, 1, 3, 4, 7]; function countTriplets(n,sum) { // Initialize result let ans = 0; // Fix the first element as A[i] for (let i = 0; i < n-2; i++) { // Fix the second element as A[j] for (let j = i + 1; j < n-1; j++) { // Now look for the third number for (let k = j + 1; k < n; k++) if (arr[i] + arr[j] + arr[k] < sum) ans++; } } return ans; } // Driver method to test the above function let sum = 12; document.write(countTriplets(arr.length, sum)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 29640, "s": 28813, "text": null }, { "code": null, "e": 29649, "s": 29640, "text": "Output: " }, { "code": null, "e": 29651, "s": 29649, "text": "4" }, { "code": null, "e": 29830, "s": 29651, "text": "The time complexity of the above solution is O(n3). An Efficient Solution can count triplets in O(n2) by sorting the array first, and then using method 1 of this post in a loop. " }, { "code": null, "e": 30465, "s": 29830, "text": "1) Sort the input array in increasing order.\n2) Initialize result as 0.\n3) Run a loop from i = 0 to n-2. An iteration of this loop finds all\n triplets with arr[i] as first element.\n a) Initialize other two elements as corner elements of subarray\n arr[i+1..n-1], i.e., j = i+1 and k = n-1\n b) Move j and k toward each other until they meet, i.e., while (j<k),\n (i) If arr[i] + arr[j] + arr[k] >= sum\n then k--\n // Else for current i and j, there can (k-j) possible third elements\n // that satisfy the constraint.\n (ii) Else Do ans += (k - j) followed by j++ " }, { "code": null, "e": 30514, "s": 30465, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 30518, "s": 30514, "text": "C++" }, { "code": null, "e": 30523, "s": 30518, "text": "Java" }, { "code": null, "e": 30531, "s": 30523, "text": "Python3" }, { "code": null, "e": 30534, "s": 30531, "text": "C#" }, { "code": null, "e": 30545, "s": 30534, "text": "Javascript" }, { "code": "// C++ program to count triplets with sum smaller than a given value#include<bits/stdc++.h>using namespace std; int countTriplets(int arr[], int n, int sum){ // Sort input array sort(arr, arr+n); // Initialize result int ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans;} // Driver programint main(){ int arr[] = {5, 1, 3, 4, 7}; int n = sizeof arr / sizeof arr[0]; int sum = 12; cout << countTriplets(arr, n, sum) << endl; return 0;}", "e": 31746, "s": 30545, "text": null }, { "code": "// A Simple Java program to count triplets with sum smaller// than a given value import java.util.Arrays; class Test{ static int arr[] = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Sort input array Arrays.sort(arr); // Initialize result int ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver method to test the above function public static void main(String[] args) { int sum = 12; System.out.println(countTriplets(arr.length, sum)); }}", "e": 33156, "s": 31746, "text": null }, { "code": "# Python3 program to count triplets with# sum smaller than a given value # Function to count triplets with sum smaller# than a given value def countTriplets(arr,n,sum): # Sort input array arr.sort() # Initialize result ans = 0 # Every iteration of loop counts triplet with # first element as arr[i]. for i in range(0,n-2): # Initialize other two elements as corner elements # of subarray arr[j+1..k] j = i + 1 k = n-1 # Use Meet in the Middle concept while(j < k): # If sum of current triplet is more or equal, # move right corner to look for smaller values if (arr[i]+arr[j]+arr[k] >=sum): k = k-1 # Else move left corner else: # This is important. For current i and j, there # can be total k-j third elements. ans += (k - j) j = j+1 return ans # Driver programif __name__=='__main__': arr = [5, 1, 3, 4, 7] n = len(arr) sum = 12 print(countTriplets(arr, n, sum)) # This code is contributed by# Yatin Gupta", "e": 34357, "s": 33156, "text": null }, { "code": "// A Simple C# program to count// triplets with sum smaller// than a given valueusing System; class GFG{ static int []arr = new int[]{5, 1, 3, 4, 7}; static int countTriplets(int n, int sum) { // Sort input array Array.Sort(arr); // Initialize result int ans = 0; // Every iteration of loop // counts triplet with // first element as arr[i]. for (int i = 0; i < n - 2; i++) { // Initialize other two // elements as corner elements // of subarray arr[j+1..k] int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet // is more or equal, move right // corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For // current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver Code public static void Main() { int sum = 12; Console.Write(countTriplets(arr.Length, sum)); }} // This code is contributed by Smitha", "e": 35804, "s": 34357, "text": null }, { "code": "<script>// A Simple Javascript program to count triplets with sum smaller// than a given value let arr = [5, 1, 3, 4, 7]; function countTriplets(n,sum) { // Sort input array arr.sort(function(a,b){return b-a}); // Initialize result let ans = 0; // Every iteration of loop counts triplet with // first element as arr[i]. for (let i = 0; i < n - 2; i++) { // Initialize other two elements as corner elements // of subarray arr[j+1..k] let j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Driver method to test the above function let sum = 12; document.write(countTriplets(arr.length, sum)); // This code is contributed by rag2127</script>", "e": 37211, "s": 35804, "text": null }, { "code": null, "e": 37220, "s": 37211, "text": "Output: " }, { "code": null, "e": 37222, "s": 37220, "text": "4" }, { "code": null, "e": 38073, "s": 37224, "text": "YouTubeGeeksforGeeks500K subscribersCount triplets with sum smaller than a given value | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=7nso5Dgc6CI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 38252, "s": 38073, "text": "Thanks to Gaurav Ahirwar for suggesting this solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 38273, "s": 38252, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 38284, "s": 38273, "text": "YatinGupta" }, { "code": null, "e": 38290, "s": 38284, "text": "ukasp" }, { "code": null, "e": 38305, "s": 38290, "text": "AnuragTripathy" }, { "code": null, "e": 38326, "s": 38305, "text": "avanitrachhadiya2155" }, { "code": null, "e": 38334, "s": 38326, "text": "rag2127" }, { "code": null, "e": 38350, "s": 38334, "text": "iamdhavalparmar" }, { "code": null, "e": 38357, "s": 38350, "text": "Amazon" }, { "code": null, "e": 38366, "s": 38357, "text": "SAP Labs" }, { "code": null, "e": 38373, "s": 38366, "text": "Arrays" }, { "code": null, "e": 38380, "s": 38373, "text": "Amazon" }, { "code": null, "e": 38389, "s": 38380, "text": "SAP Labs" }, { "code": null, "e": 38396, "s": 38389, "text": "Arrays" }, { "code": null, "e": 38494, "s": 38396, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38503, "s": 38494, "text": "Comments" }, { "code": null, "e": 38516, "s": 38503, "text": "Old Comments" }, { "code": null, "e": 38564, "s": 38516, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 38608, "s": 38564, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 38631, "s": 38608, "text": "Introduction to Arrays" }, { "code": null, "e": 38663, "s": 38631, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 38677, "s": 38663, "text": "Linear Search" }, { "code": null, "e": 38762, "s": 38677, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 38783, "s": 38762, "text": "Linked List vs Array" }, { "code": null, "e": 38828, "s": 38783, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 38896, "s": 38828, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
Calculate the average value in a MongoDB document grouping by null?
You can use $group operator with _id: null. Following is the syntax − db.yourCollectionName.aggregate([{$group: {_id:null, "anyFieldName": {$avg:"$yourFieldName"} } }]); Let us first create a collection with documents − > db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a197924bb85b3f4895f") } > db.caculateTheAverageValueDemo.insertOne({"Population":500}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a1c7924bb85b3f48960") } > db.caculateTheAverageValueDemo.insertOne({"Population":200}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a237924bb85b3f48961") } > db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a297924bb85b3f48962") } > db.caculateTheAverageValueDemo.insertOne({"Population":100}); { "acknowledged" : true, "insertedId" : ObjectId("5cd68a2e7924bb85b3f48963") } Following is the query to display all documents from a collection with the help of find() method − > db.caculateTheAverageValueDemo.find().pretty(); This will produce the following output − { "_id" : ObjectId("5cd68a197924bb85b3f4895f"), "Population" : 100 } { "_id" : ObjectId("5cd68a1c7924bb85b3f48960"), "Population" : 500 } { "_id" : ObjectId("5cd68a237924bb85b3f48961"), "Population" : 200 } { "_id" : ObjectId("5cd68a297924bb85b3f48962"), "Population" : 100 } { "_id" : ObjectId("5cd68a2e7924bb85b3f48963"), "Population" : 100 } Following is the query to average the values of a MongoDB document − > db.caculateTheAverageValueDemo.aggregate([{$group: {_id:null, "AveragePopulation": {$avg:"$Population"} } }]); This will produce the following output − { "_id" : null, "AveragePopulation" : 200 }
[ { "code": null, "e": 1132, "s": 1062, "text": "You can use $group operator with _id: null. Following is the syntax −" }, { "code": null, "e": 1232, "s": 1132, "text": "db.yourCollectionName.aggregate([{$group: {_id:null, \"anyFieldName\": {$avg:\"$yourFieldName\"} } }]);" }, { "code": null, "e": 1282, "s": 1232, "text": "Let us first create a collection with documents −" }, { "code": null, "e": 2027, "s": 1282, "text": "> db.caculateTheAverageValueDemo.insertOne({\"Population\":100});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd68a197924bb85b3f4895f\")\n}\n> db.caculateTheAverageValueDemo.insertOne({\"Population\":500});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd68a1c7924bb85b3f48960\")\n}\n> db.caculateTheAverageValueDemo.insertOne({\"Population\":200});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd68a237924bb85b3f48961\")\n}\n> db.caculateTheAverageValueDemo.insertOne({\"Population\":100});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd68a297924bb85b3f48962\")\n}\n> db.caculateTheAverageValueDemo.insertOne({\"Population\":100});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd68a2e7924bb85b3f48963\")\n}" }, { "code": null, "e": 2126, "s": 2027, "text": "Following is the query to display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2176, "s": 2126, "text": "> db.caculateTheAverageValueDemo.find().pretty();" }, { "code": null, "e": 2217, "s": 2176, "text": "This will produce the following output −" }, { "code": null, "e": 2562, "s": 2217, "text": "{ \"_id\" : ObjectId(\"5cd68a197924bb85b3f4895f\"), \"Population\" : 100 }\n{ \"_id\" : ObjectId(\"5cd68a1c7924bb85b3f48960\"), \"Population\" : 500 }\n{ \"_id\" : ObjectId(\"5cd68a237924bb85b3f48961\"), \"Population\" : 200 }\n{ \"_id\" : ObjectId(\"5cd68a297924bb85b3f48962\"), \"Population\" : 100 }\n{ \"_id\" : ObjectId(\"5cd68a2e7924bb85b3f48963\"), \"Population\" : 100 }" }, { "code": null, "e": 2631, "s": 2562, "text": "Following is the query to average the values of a MongoDB document −" }, { "code": null, "e": 2744, "s": 2631, "text": "> db.caculateTheAverageValueDemo.aggregate([{$group: {_id:null, \"AveragePopulation\": {$avg:\"$Population\"} } }]);" }, { "code": null, "e": 2785, "s": 2744, "text": "This will produce the following output −" }, { "code": null, "e": 2829, "s": 2785, "text": "{ \"_id\" : null, \"AveragePopulation\" : 200 }" } ]
What is a final method in Java?
The final modifier for finalizing the implementations of classes, methods, and variables. We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class. The main intention of making a method final would be that the content of the method should not be changed by any outsider. public class FinalMethodExample { public final void display(){ System.out.println("Hello welcome to Tutorialspoint"); } public static void main(String args[]){ new FinalMethodExample().display(); } class Sample extends FinalMethodExample{ public void display(){ System.out.println("hi"); } } } FinalMethodExample.java:12: error: display() in FinalMethodExample.Sample cannot override display() in FinalMethodExample public void display(){ ^ overridden method is final 1 error
[ { "code": null, "e": 1152, "s": 1062, "text": "The final modifier for finalizing the implementations of classes, methods, and variables." }, { "code": null, "e": 1298, "s": 1152, "text": "We can declare a method as final, once you declare a method final it cannot be overridden. So, you cannot modify a final method from a sub class." }, { "code": null, "e": 1421, "s": 1298, "text": "The main intention of making a method final would be that the content of the method should not be changed by any outsider." }, { "code": null, "e": 1766, "s": 1421, "text": "public class FinalMethodExample {\n public final void display(){\n System.out.println(\"Hello welcome to Tutorialspoint\");\n }\n public static void main(String args[]){\n new FinalMethodExample().display();\n }\n class Sample extends FinalMethodExample{\n public void display(){\n System.out.println(\"hi\");\n }\n }\n}" }, { "code": null, "e": 1961, "s": 1766, "text": "FinalMethodExample.java:12: error: display() in FinalMethodExample.Sample cannot override display() in FinalMethodExample\npublic void display(){\n ^\noverridden method is final\n1 error\n" } ]
Python - RemoveAccents Module - GeeksforGeeks
16 Jul, 2020 removeaccents module is that library of python which helps you to remove all the accents from a given string. The most common accents are the acute (é), grave (è), circumflex (â, î or ô), umlaut and dieresis (ü or ï ). Accent marks usually appear above a character.It can be widely used in Natural language Processing for filtering out the data by removing all the accents from a given text. Installing Library : This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install removeaccents remove_accents : It will return the string after removing all accents from the characters in the string. Example : # Importing removeaccents function # From removeaccents Library from removeaccents import removeaccents str_input ="Ît löökèd cóol ând câsüâl, büt nôt prôvôcâtïvê ."str_output = removeaccents.remove_accents(str_input)print(str_output) str_input ="För môrê àrticlés vîsit GééksförGèèks ."str_output = removeaccents.remove_accents(str_input)print(str_output) str_input ="https://äüth.gèéksforgëëks.ôrg / usër / vâsü_gûptâ/àrtîclés ."str_output = removeaccents.remove_accents(str_input)print(str_output) Output: It looked cool and casual, but not provocative . For more articles visit GeeksforGeeks . https://auth.geeksforgeeks.org/user/vasu_gupta/articles . Reference:pypy.org Natural-language-processing 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() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n16 Jul, 2020" }, { "code": null, "e": 24300, "s": 23901, "text": "removeaccents module is that library of python which helps you to remove all the accents from a given string. The most common accents are the acute (é), grave (è), circumflex (â, î or ô), umlaut and dieresis (ü or ï ). Accent marks usually appear above a character.It can be widely used in Natural language Processing for filtering out the data by removing all the accents from a given text." }, { "code": null, "e": 24321, "s": 24300, "text": "Installing Library :" }, { "code": null, "e": 24467, "s": 24321, "text": "This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal." }, { "code": null, "e": 24493, "s": 24467, "text": "pip install removeaccents" }, { "code": null, "e": 24598, "s": 24493, "text": "remove_accents : It will return the string after removing all accents from the characters in the string." }, { "code": null, "e": 24608, "s": 24598, "text": "Example :" }, { "code": "# Importing removeaccents function # From removeaccents Library from removeaccents import removeaccents str_input =\"Ît löökèd cóol ând câsüâl, büt nôt prôvôcâtïvê .\"str_output = removeaccents.remove_accents(str_input)print(str_output) str_input =\"För môrê àrticlés vîsit GééksförGèèks .\"str_output = removeaccents.remove_accents(str_input)print(str_output) str_input =\"https://äüth.gèéksforgëëks.ôrg / usër / vâsü_gûptâ/àrtîclés .\"str_output = removeaccents.remove_accents(str_input)print(str_output)", "e": 25156, "s": 24608, "text": null }, { "code": null, "e": 25164, "s": 25156, "text": "Output:" }, { "code": null, "e": 25315, "s": 25164, "text": "It looked cool and casual, but not provocative .\n\nFor more articles visit GeeksforGeeks .\n\nhttps://auth.geeksforgeeks.org/user/vasu_gupta/articles .\n\n" }, { "code": null, "e": 25334, "s": 25315, "text": "Reference:pypy.org" }, { "code": null, "e": 25362, "s": 25334, "text": "Natural-language-processing" }, { "code": null, "e": 25369, "s": 25362, "text": "Python" }, { "code": null, "e": 25467, "s": 25369, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25476, "s": 25467, "text": "Comments" }, { "code": null, "e": 25489, "s": 25476, "text": "Old Comments" }, { "code": null, "e": 25521, "s": 25489, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25577, "s": 25521, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25619, "s": 25577, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25661, "s": 25619, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25697, "s": 25661, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25719, "s": 25697, "text": "Defaultdict in Python" }, { "code": null, "e": 25758, "s": 25719, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25785, "s": 25758, "text": "Python Classes and Objects" }, { "code": null, "e": 25816, "s": 25785, "text": "Python | os.path.join() method" } ]
Paginated Report visual in Power BI — everything you need to know! | by Nikola Ilic | Towards Data Science
One of the most anticipated Power BI features is finally there! No, it’s not new fancy Small multiples improvements, or another fresh AI thing...It’s not even DirectQuery support for Dataflows, neither dataset discoverability (which are both, by the way, very cool additions). Guess what — Paginated Report visual has just arrived into Power BI Desktop! At this moment, it’s still in preview, but the excitement around is huge. I hear you, I hear you...Who needs this thing at all?! Why would one use the (almost) deprecated technology in super modern shiny Power BI solutions?! Even more, Paginated reports are almost exclusively boring tables + matrices. We have these two in Power BI with waaay more customization options and properties to make them a lot nicer and better looking. We, old people, tend often to say: “you know how it was done in my younger days...”, or “we did exactly like that X years ago...” And, Paginated reports came into our lives way before Power BI. In 2004, Microsoft introduced SQL Server 2000 add-in called SQL Server Reporting Services, and this tool became a reporting standard for the first decade and a half of this century (some will argue even longer, till nowadays). Things in the data area evolving fast! Extremely fast! So, new challenges required fresh solutions, and Power BI was introduced in 2015 to answer as many business reporting questions as possible, in the most efficient and eye-catching way. However, same as SSAS Multidimensional, which still resists giving up (even though Microsoft pushes everything to Tabular in recent years), SSRS is an integral part of many legacy BI solutions that still work — and not just work, they work quite good! Ok, the number of visualization types and their customization might look awkward compared to Power BI, but, hey, we could’ve written Visual Basic to extend built-in features! Raise your hand everyone of you who used something like the following code snippet to make your table rows color alternating:) =iif(rownumber(nothing) mod 2 = 0,"LightGrey","Transparent") Yeah, I know, it’s much easier to format your table in Power BI and just click on Alternate rows option, but VB is much more fun:)) (just kidding, of course) I myself thought 2–3 years ago that SSRS is dead...Oh, how wrong I was! Do you know the movie: “No country for old men”? In my case, it could’ve been easily translated to: “No SSRS for old (data) men”... Even though most of the companies migrated to Power BI and adapted their reporting solutions to fit into a new cloud environment, there is still a significant number of clients who are not willing to discontinue using good old paginated reports. And, believe me, I saw a lot of hybrid solutions, where the majority of the reports were migrated to Power BI, but certain reports remained in paginated form, without any intention to recreate them in Power BI...Why is that way, I hear you ask? Isn’t Power BI a more robust, more efficient, and more powerful tool? Of course, it is! There is no single doubt about it. If you look from a performance perspective, VertiPaq is a beast that can compress and process enormous amounts of data blazingly fast...From a data modeling perspective, I can bet that Power BI is the most comprehensive solution at this moment. You can extend traditional data modeling principles using various powerful features, such as Composite models, role-playing dimensions, Dataflows, and so on. Not to tell about the capabilities for data transformation and data shaping, to prepare your data in an optimal way for the final reporting solution. Of course, if you put Power BI vs SSRS head-to-head, the winner is obvious! But, if you compare these two tools head-to-head, feature by feature, you are missing the point. Paginated reports are not here to be an alternative to Power BI — they are here to complement Power BI! Simply put, there are some certain features that SSRS offers, which Power BI simply can’t replicate. For example, if your users insist on pixel-perfect, printable, or easily exportable reports, there is no better option than a paginated report! Their name says all — they are called paginated, because they are designed to fit well on the page! Up until now, integration between paginated report and Power BI report was not possible. It was either one or the other. Now, with Paginated Report visual, you can take advantage of the best features from both worlds! To be able to use a Paginated report visual, you first need to build a paginated report itself. So, let’s go and build a very basic paginated report, using the Adventure Works sample database. I’m intentionally keeping things simple, as the purpose of this article is not to go deep into the Paginated report creation process, but more focus on integration between Paginated report and Power BI. If you plan to use Paginated reports, you MUST have some sort of Premium license — EM1-EM3 SKUs, P1-P3 SKUs and A1-A6 SKUs. It also is available on a per-user basis with Premium per user, which is built on Premium Gen2 and also in public preview. It’s important to keep in mind that the workspace you are publishing the Paginated report to, must be defined as a Premium workspace In order to build a Paginated report, you’ll need a separate tool, called Power BI Report Builder. If you used to work in SSRS Report Builder, the whole environment will look familiar. Here is the query I’ll use to create a dataset for my Paginated report: SELECT p.Color, fsi.SalesAmount, d.FullDateAlternateKey AS [date]FROM FactInternetSales fsi INNER JOIN DimProduct p ON p.ProductKey = fsi.ProductKey INNER JOIN DimDate d ON d.DateKey = fsi.OrderDateKeyWHERE d.FullDateAlternateKey >= @dFrom AND d.FullDateAlternateKey <= @dTo; Basically, I want to show product color, sales amount, and date for every single transaction from my FactInternetSales table. As I said, quite a basic setup. Since my query is parameterized, I need to map parameters (in my case, those are starting and ending date). In case you’re using additional parameters (for example, color), make sure that you map them too. I’ve put a simple matrix on the report canvas, and I’m ready now to publish the report to my workspace: You can immediately notice that the Paginated report differs from the “classic” Power BI report by looking at the icons next to the report name. And, if I run the Paginated report, it renders nice to show me results based on date parameters I’ve set: So far, nothing special, as you had to decide whether you want to use Power BI or Paginated report... And, here is where the real magic happens! Now, you can integrate the Paginated report into your Power BI report and run it from there! Let’s go step by step to see how it’s done... Within Power BI Desktop, I’m using exactly the same dataset (AdventureWorksDW2017) and I’ve created the same matrix as in the Paginated report previously. Now, I’ll drag a brand new Paginated Report visual on the report canvas and follow the instructions to connect to the My Paginated Report. Now follows the interesting part, as you’ll need to configure a few things. After I’ve selected the paginated report I want to connect to (in my case, My Paginated Report), I need to provide parameter values, so that the visual can be cross filtered from within Power BI! Therefore, I’ll create two measures to use them to feed the parameter values: dFrom = MIN(FactInternetSales[OrderDate])dTo = MAX(FactInternetSales[OrderDate]) I will drag these measures as Parameters for the Paginated report visual and assign those values to my original parameters: And once I click on See report, you can notice that I’m getting my Paginated report rendered within Power BI directly! How cool is that! And results are the same between the two matrices: There are also additional formatting options for the Paginated Report visual. Obviously, not as many possibilities for customization as with “regular” Power BI visuals, but still useful, especially Toolbar and Parameters properties: Since the visual is fully responsive in terms of cross-filtering, let’s check what happens if I change the slicer values: As you would expect, the Power BI visual immediately reflects the changes, but for the Paginated report visual nothing changed. By default, you need to explicitly click on this Apply changes button for new slicer values to be propagated to an underlying data source. You can change this behavior by enabling Auto-apply filters in the Format pane, but I would suggest not to do it, as the default setup was specified with query reduction in mind. We will come soon to explain what is going on in the background when you change the slicer values... So, I was curious to see what happens under the hood when you render paginated report within Power BI and how the data is being retrieved. Let’s first launch DAX Studio and capture the queries generated by Power BI: Hm, that’s strange, as there is no SQL code generated, and I would expect to see something like a SQL statement. This query basically calculates only our measures for dFrom and dTo parameters. So, I’m turning on a good old SQL Server Profiler to check what is really going on down there. And here it is! This is the SQL statement that retrieves the data from the AdventureWorksDW2017 database. Looks familiar? Yes, exactly, that’s the query we’ve used to create our original dataset for the paginated report! However, Power BI generated a dynamic SQL statement, wrapping our original query with parameters grabbed from the Power BI slicer (that’s the query we saw in DAX Studio)! If I change the slicers values, we should see the new dynamic SQL query with different parameter values (I’ll set starting date to June 25th). Let’s check if that’s the case: BAM! There you go! As expected, we have a new SQL statement — in fact, the base statement is the same, but parameter values were changed and new dynamic SQL was generated and executed. This leads to a conclusion that Paginated Report visual works in a DirectQuery mode! Well, that was all nice, but I hear you asking: why do I need Paginated Report visual in my Power BI report in the first place? I’ll publish our Power BI report that includes Paginated report visual to a workspace and I’ll show you the use case. Let’s imagine that one of the users requests is to export the data from the visuals. When you’re exporting the data from Power BI original matrix, the only available format is xlsx. On the other hand, if I click on Export within the Paginated Report visual, look what I have at my disposal: Wow! Not just Excel! I can export to a whole range of different formats, including pdf if I need to print out something (oh, yes, believe me, there are a lot of people around that still prefer to print their reports), or pptx in case I need it for my fancy PowerPoint presentation! Don’t forget why are Paginated reports called Paginated at first place:) Next, what happens if I have more data in my visual than it can fit on one page and want to export it to pdf? Let’s check how Power BI matrix renders to pdf: Oh, man, I’m missing data! Why is that? Where are my dates between June 3rd and June 30th? I saw them in my Power BI report. Yes, you did. But, you can scroll the table in the Power BI report, and you can’t scroll the image in pdf! Let’s check what happens if we export data from the Paginated Report visual: Oh, how nice and clean that looks! The possibility to render Paginated Report directly within Power BI report is an immense addition to the already wide range of capabilities that Power BI offers. Having another (very powerful) tool under the belt can only increase the business value your reporting solution provides. There will always be users that insist on pixel-perfect, print-friendly data, and Power BI on its own couldn’t address these requests properly. But, now, by integration of mature and established technology, such as Paginated reports, you can satisfy all requests from within a single location, even applying all the filters to the data at once! Despite some limitations, I believe that Paginated Report visual is one of the greatest improvements in Power BI recently! Thanks for reading! Become a member and read every story on Medium!
[ { "code": null, "e": 599, "s": 171, "text": "One of the most anticipated Power BI features is finally there! No, it’s not new fancy Small multiples improvements, or another fresh AI thing...It’s not even DirectQuery support for Dataflows, neither dataset discoverability (which are both, by the way, very cool additions). Guess what — Paginated Report visual has just arrived into Power BI Desktop! At this moment, it’s still in preview, but the excitement around is huge." }, { "code": null, "e": 956, "s": 599, "text": "I hear you, I hear you...Who needs this thing at all?! Why would one use the (almost) deprecated technology in super modern shiny Power BI solutions?! Even more, Paginated reports are almost exclusively boring tables + matrices. We have these two in Power BI with waaay more customization options and properties to make them a lot nicer and better looking." }, { "code": null, "e": 1377, "s": 956, "text": "We, old people, tend often to say: “you know how it was done in my younger days...”, or “we did exactly like that X years ago...” And, Paginated reports came into our lives way before Power BI. In 2004, Microsoft introduced SQL Server 2000 add-in called SQL Server Reporting Services, and this tool became a reporting standard for the first decade and a half of this century (some will argue even longer, till nowadays)." }, { "code": null, "e": 1869, "s": 1377, "text": "Things in the data area evolving fast! Extremely fast! So, new challenges required fresh solutions, and Power BI was introduced in 2015 to answer as many business reporting questions as possible, in the most efficient and eye-catching way. However, same as SSAS Multidimensional, which still resists giving up (even though Microsoft pushes everything to Tabular in recent years), SSRS is an integral part of many legacy BI solutions that still work — and not just work, they work quite good!" }, { "code": null, "e": 2171, "s": 1869, "text": "Ok, the number of visualization types and their customization might look awkward compared to Power BI, but, hey, we could’ve written Visual Basic to extend built-in features! Raise your hand everyone of you who used something like the following code snippet to make your table rows color alternating:)" }, { "code": null, "e": 2232, "s": 2171, "text": "=iif(rownumber(nothing) mod 2 = 0,\"LightGrey\",\"Transparent\")" }, { "code": null, "e": 2390, "s": 2232, "text": "Yeah, I know, it’s much easier to format your table in Power BI and just click on Alternate rows option, but VB is much more fun:)) (just kidding, of course)" }, { "code": null, "e": 2840, "s": 2390, "text": "I myself thought 2–3 years ago that SSRS is dead...Oh, how wrong I was! Do you know the movie: “No country for old men”? In my case, it could’ve been easily translated to: “No SSRS for old (data) men”... Even though most of the companies migrated to Power BI and adapted their reporting solutions to fit into a new cloud environment, there is still a significant number of clients who are not willing to discontinue using good old paginated reports." }, { "code": null, "e": 3611, "s": 2840, "text": "And, believe me, I saw a lot of hybrid solutions, where the majority of the reports were migrated to Power BI, but certain reports remained in paginated form, without any intention to recreate them in Power BI...Why is that way, I hear you ask? Isn’t Power BI a more robust, more efficient, and more powerful tool? Of course, it is! There is no single doubt about it. If you look from a performance perspective, VertiPaq is a beast that can compress and process enormous amounts of data blazingly fast...From a data modeling perspective, I can bet that Power BI is the most comprehensive solution at this moment. You can extend traditional data modeling principles using various powerful features, such as Composite models, role-playing dimensions, Dataflows, and so on." }, { "code": null, "e": 3761, "s": 3611, "text": "Not to tell about the capabilities for data transformation and data shaping, to prepare your data in an optimal way for the final reporting solution." }, { "code": null, "e": 4383, "s": 3761, "text": "Of course, if you put Power BI vs SSRS head-to-head, the winner is obvious! But, if you compare these two tools head-to-head, feature by feature, you are missing the point. Paginated reports are not here to be an alternative to Power BI — they are here to complement Power BI! Simply put, there are some certain features that SSRS offers, which Power BI simply can’t replicate. For example, if your users insist on pixel-perfect, printable, or easily exportable reports, there is no better option than a paginated report! Their name says all — they are called paginated, because they are designed to fit well on the page!" }, { "code": null, "e": 4601, "s": 4383, "text": "Up until now, integration between paginated report and Power BI report was not possible. It was either one or the other. Now, with Paginated Report visual, you can take advantage of the best features from both worlds!" }, { "code": null, "e": 4997, "s": 4601, "text": "To be able to use a Paginated report visual, you first need to build a paginated report itself. So, let’s go and build a very basic paginated report, using the Adventure Works sample database. I’m intentionally keeping things simple, as the purpose of this article is not to go deep into the Paginated report creation process, but more focus on integration between Paginated report and Power BI." }, { "code": null, "e": 5377, "s": 4997, "text": "If you plan to use Paginated reports, you MUST have some sort of Premium license — EM1-EM3 SKUs, P1-P3 SKUs and A1-A6 SKUs. It also is available on a per-user basis with Premium per user, which is built on Premium Gen2 and also in public preview. It’s important to keep in mind that the workspace you are publishing the Paginated report to, must be defined as a Premium workspace" }, { "code": null, "e": 5634, "s": 5377, "text": "In order to build a Paginated report, you’ll need a separate tool, called Power BI Report Builder. If you used to work in SSRS Report Builder, the whole environment will look familiar. Here is the query I’ll use to create a dataset for my Paginated report:" }, { "code": null, "e": 5947, "s": 5634, "text": "SELECT p.Color, fsi.SalesAmount, d.FullDateAlternateKey AS [date]FROM FactInternetSales fsi INNER JOIN DimProduct p ON p.ProductKey = fsi.ProductKey INNER JOIN DimDate d ON d.DateKey = fsi.OrderDateKeyWHERE d.FullDateAlternateKey >= @dFrom AND d.FullDateAlternateKey <= @dTo;" }, { "code": null, "e": 6105, "s": 5947, "text": "Basically, I want to show product color, sales amount, and date for every single transaction from my FactInternetSales table. As I said, quite a basic setup." }, { "code": null, "e": 6415, "s": 6105, "text": "Since my query is parameterized, I need to map parameters (in my case, those are starting and ending date). In case you’re using additional parameters (for example, color), make sure that you map them too. I’ve put a simple matrix on the report canvas, and I’m ready now to publish the report to my workspace:" }, { "code": null, "e": 6666, "s": 6415, "text": "You can immediately notice that the Paginated report differs from the “classic” Power BI report by looking at the icons next to the report name. And, if I run the Paginated report, it renders nice to show me results based on date parameters I’ve set:" }, { "code": null, "e": 6768, "s": 6666, "text": "So far, nothing special, as you had to decide whether you want to use Power BI or Paginated report..." }, { "code": null, "e": 6950, "s": 6768, "text": "And, here is where the real magic happens! Now, you can integrate the Paginated report into your Power BI report and run it from there! Let’s go step by step to see how it’s done..." }, { "code": null, "e": 7244, "s": 6950, "text": "Within Power BI Desktop, I’m using exactly the same dataset (AdventureWorksDW2017) and I’ve created the same matrix as in the Paginated report previously. Now, I’ll drag a brand new Paginated Report visual on the report canvas and follow the instructions to connect to the My Paginated Report." }, { "code": null, "e": 7594, "s": 7244, "text": "Now follows the interesting part, as you’ll need to configure a few things. After I’ve selected the paginated report I want to connect to (in my case, My Paginated Report), I need to provide parameter values, so that the visual can be cross filtered from within Power BI! Therefore, I’ll create two measures to use them to feed the parameter values:" }, { "code": null, "e": 7675, "s": 7594, "text": "dFrom = MIN(FactInternetSales[OrderDate])dTo = MAX(FactInternetSales[OrderDate])" }, { "code": null, "e": 7799, "s": 7675, "text": "I will drag these measures as Parameters for the Paginated report visual and assign those values to my original parameters:" }, { "code": null, "e": 7987, "s": 7799, "text": "And once I click on See report, you can notice that I’m getting my Paginated report rendered within Power BI directly! How cool is that! And results are the same between the two matrices:" }, { "code": null, "e": 8220, "s": 7987, "text": "There are also additional formatting options for the Paginated Report visual. Obviously, not as many possibilities for customization as with “regular” Power BI visuals, but still useful, especially Toolbar and Parameters properties:" }, { "code": null, "e": 8342, "s": 8220, "text": "Since the visual is fully responsive in terms of cross-filtering, let’s check what happens if I change the slicer values:" }, { "code": null, "e": 8889, "s": 8342, "text": "As you would expect, the Power BI visual immediately reflects the changes, but for the Paginated report visual nothing changed. By default, you need to explicitly click on this Apply changes button for new slicer values to be propagated to an underlying data source. You can change this behavior by enabling Auto-apply filters in the Format pane, but I would suggest not to do it, as the default setup was specified with query reduction in mind. We will come soon to explain what is going on in the background when you change the slicer values..." }, { "code": null, "e": 9105, "s": 8889, "text": "So, I was curious to see what happens under the hood when you render paginated report within Power BI and how the data is being retrieved. Let’s first launch DAX Studio and capture the queries generated by Power BI:" }, { "code": null, "e": 9393, "s": 9105, "text": "Hm, that’s strange, as there is no SQL code generated, and I would expect to see something like a SQL statement. This query basically calculates only our measures for dFrom and dTo parameters. So, I’m turning on a good old SQL Server Profiler to check what is really going on down there." }, { "code": null, "e": 9785, "s": 9393, "text": "And here it is! This is the SQL statement that retrieves the data from the AdventureWorksDW2017 database. Looks familiar? Yes, exactly, that’s the query we’ve used to create our original dataset for the paginated report! However, Power BI generated a dynamic SQL statement, wrapping our original query with parameters grabbed from the Power BI slicer (that’s the query we saw in DAX Studio)!" }, { "code": null, "e": 9960, "s": 9785, "text": "If I change the slicers values, we should see the new dynamic SQL query with different parameter values (I’ll set starting date to June 25th). Let’s check if that’s the case:" }, { "code": null, "e": 10145, "s": 9960, "text": "BAM! There you go! As expected, we have a new SQL statement — in fact, the base statement is the same, but parameter values were changed and new dynamic SQL was generated and executed." }, { "code": null, "e": 10230, "s": 10145, "text": "This leads to a conclusion that Paginated Report visual works in a DirectQuery mode!" }, { "code": null, "e": 10476, "s": 10230, "text": "Well, that was all nice, but I hear you asking: why do I need Paginated Report visual in my Power BI report in the first place? I’ll publish our Power BI report that includes Paginated report visual to a workspace and I’ll show you the use case." }, { "code": null, "e": 10561, "s": 10476, "text": "Let’s imagine that one of the users requests is to export the data from the visuals." }, { "code": null, "e": 10767, "s": 10561, "text": "When you’re exporting the data from Power BI original matrix, the only available format is xlsx. On the other hand, if I click on Export within the Paginated Report visual, look what I have at my disposal:" }, { "code": null, "e": 11122, "s": 10767, "text": "Wow! Not just Excel! I can export to a whole range of different formats, including pdf if I need to print out something (oh, yes, believe me, there are a lot of people around that still prefer to print their reports), or pptx in case I need it for my fancy PowerPoint presentation! Don’t forget why are Paginated reports called Paginated at first place:)" }, { "code": null, "e": 11280, "s": 11122, "text": "Next, what happens if I have more data in my visual than it can fit on one page and want to export it to pdf? Let’s check how Power BI matrix renders to pdf:" }, { "code": null, "e": 11512, "s": 11280, "text": "Oh, man, I’m missing data! Why is that? Where are my dates between June 3rd and June 30th? I saw them in my Power BI report. Yes, you did. But, you can scroll the table in the Power BI report, and you can’t scroll the image in pdf!" }, { "code": null, "e": 11589, "s": 11512, "text": "Let’s check what happens if we export data from the Paginated Report visual:" }, { "code": null, "e": 11624, "s": 11589, "text": "Oh, how nice and clean that looks!" }, { "code": null, "e": 11908, "s": 11624, "text": "The possibility to render Paginated Report directly within Power BI report is an immense addition to the already wide range of capabilities that Power BI offers. Having another (very powerful) tool under the belt can only increase the business value your reporting solution provides." }, { "code": null, "e": 12253, "s": 11908, "text": "There will always be users that insist on pixel-perfect, print-friendly data, and Power BI on its own couldn’t address these requests properly. But, now, by integration of mature and established technology, such as Paginated reports, you can satisfy all requests from within a single location, even applying all the filters to the data at once!" }, { "code": null, "e": 12376, "s": 12253, "text": "Despite some limitations, I believe that Paginated Report visual is one of the greatest improvements in Power BI recently!" }, { "code": null, "e": 12396, "s": 12376, "text": "Thanks for reading!" } ]
Balancing and Augmenting Structured Data | by Bruce H. Cottman, Ph.D. | Towards Data Science
When data augmentation is discussed, it is almost always about increasing the image data set by rotation, flipping, or in some way, changing the existing images to create more images. You may even come across methods for augmented unstructured data, such as words in documents. Structured Data Augmentation is rarely discussed in theoretical approaches and rarely appears in real-world production systems. When it does, it is not called augmentation but rather class balancing or over-sampling. I will show a simplistic approach to Structured Data Augmentation. In a future follow-on to this article, I will demonstrate a complete strategy that avoids a simple k-means clustering that is at the heart of over-sampling techniques such as SMOOT and ADASYN. Along the way, we will introduce paso Class Balancing tools. As was shown in the previous article, paso supports and is compatible with current machine learning and deep learning frameworks. paso is a package written in Python and some C(for speed) that was initially intended to bundle best-practices and state-of-the-art services, classes, and functions for the Machine Learning and Deep Learning community. paso has grown beyond this to offer decorators, classes, and methods you can use in your pipelines or custom code with or without adopting the entire paso package. A pipeline is composed of steps. Each step transforms the input dataset. A step will return a measurement (or dictionary of measurements), output a graph or the transformed dataset. Note: this is different but compatible with the Scikit-Learn pipeline. Paso currently offers the following classes: Inputer, Splitters, Cleaners, Encoders, Scalers, Balancers, Augmenters, and Learners. All classes provide logging, description files, and checkpointing. The last class, Learners, implements the methods: train, predict, evaluate, cross-validate, and hyper-parameter optimization. The discussion will divide into the following major segments: First, we load an imbalanced class dataset with a paso Inputer. Second, I will survey some of the class balancing methods offered in paso. Next, I will show that some of the structured data augmentation offered in paso derive from the class balancing methods. Then, I hint that these methods might be inadequate for more than just balancing the augmentation of structured data. Finally, I finish this article with a Discussion and Summary section. As usual, the source code for all examples sampled in this article is also available as one complete notebook (ipynb). paso’s Offering of Logging and Parameter Services for your Python Projectmedium.com As we saw in the above article, we can startup paso services with: from paso.base import Paso,Log,PasoErrorfrom loguru import loggersession = Paso(parameters_filepath='../parameters/default-lesson.3.yaml').startup() Imbalanced data sets are a particular case for classification problems where the class distribution is not uniform. Typically, they compose by two classes: the majority (negative) class and the minority (positive) class. I have picked the yeast3dataset as it has studied by biologists and machine learning scientists since the late 1990s. It downloads from https://sci2s.ugr.es/keel/imbalanced.php. We load the yeast3 data set into the dataset dataframe. The feature class will contain the class values. The features for this dataset are: Class: predicted or dependent or target feature. The 0th class has an 8:1 ratio to the 1st class. Mcg: McGeoch’s method for signal sequence recognition. Gvh: von Heijne’s method for signal sequence recognition. Alm: Score of the ALOM membrane-spanning region prediction program. Mit: Score of discriminant analysis of the amino acid content of the N-terminal region (20 residues long) of mitochondrial and non-mitochondrial proteins. Erl: Presence of “HDEL” substring (thought to act as a signal for retention in the endoplasmic reticulum lumen). Binary attribute. Pox: Peroxisomal targeting signal in the C-terminus. Vac: Score of discriminant analysis of the amino acid content of vacuolar and extracellular proteins. Nuc: Score of discriminant analysis of nuclear localization signals of nuclear and non-nuclear protein. These features are different types of measurements of the yeast strains. Do not worry if you do not know what they mean, as it is not essential for this article. Instead of using keyword arguments cemented in code, I will use a description file. One working definition of description (from Wikipedia) is: “showing the relations between the concepts and categories in a subject area or domain.” We are using description files because: the description of an object (dataset, model, etc.) changes without changing code; The parsing performance of a description file and python are about the same as both use dynamic typing. Performance concerns probably would not be the case for statically typed language. However, an object’s metadata parsing compute is very tiny compared to the action(s) performed by the class instance in all cases encountered so far. A description file is language independent. It is currently formatted as a YAML file but can also cast as a JSON or XML file. Description files consist of a hierarchy of key-value pairs. In a future article, I will cover description files in detail — different description files viewed at https://github.com/bcottman/paso/tree/master/descriptions. Before training the learner, it is imperative to balance only the dataset we will train. We want to know the effect of balancing data on the learner, while not corrupting our validation dataset with augmented data. Validation draws from the initial train dataset in the hopes it is a sample of the past and future data that the test dataset draws from the training set remainder. In this case, our validation set is referenced asX_test, y_test. The other situation where train, valid, and test from the original dataset is covered is by splitting the initial dataset to result in a train dataset and validation dataset. Then split on a train again to get train and test. The order does not matter so long as the second split is also on the train dataset. Here the training set will be 70%, and the validation (test) set will be 30% of the original dataset. X, y = DataFrame_to_Xy(dataset, inputer.target)splitter = Splitters(description_filepath=splitter_file)X_train,X_test, y_train, y_test = splitter.transform(X, y,random_state=11)train = X_train.copy()Xy_to_DataFrame(train, y_train, inputer.target)train.groupby([inputer.target]).count() Before we balance the class, let us run RandomForest learner with generic classification hyper-parameters (shown above in the description file for RadomForest) on the yeast3dataset. from paso.learners.learners import Learnerslearner = Learners(description_filepath=learner_file)learner.train(X_train,y_train)learner.cross_validate(X_train,y_train,description_filepath=cv_file)learner.evaluate(X_test, y_test) This is a fairly good fit with an f1 of 0.8207.What happens when we balance class 1 with class 0 by oversampling? In a future article, I will cover in detail how to use paso’s cross-validation for learners that train and predict. In the meantime, you can find a good overview of cross-validation in: towardsdatascience.com and a detailed discussion of cross-validation in: scikit-learn.org In this article, I usesklearn.cross_validate.This is hopefully a good choice for the structured datasets we will be using. www.jeremyjordan.me Imbalanced data typically refers to a classification problem where the number of observations per class is not equally distributed; often you’ll have a large amount of data/observations for one class (referred to as the majority class), and much fewer observations for one or more other classes (referred to as the minority classes). medium.com Imbalanced data is not always a bad thing, and in real data sets, there is always some degree of imbalance. That said, there should not be any big impact on your model performance if the level of imbalance is relatively low. sampling techniques perform differently under different levels of imbalance. There are currently four different types of approaches to class balance: weight assignment: These various methods put a higher weight on minority classes and lower weight on majority classes. No real information is added to the dataset. Instead, this is regulation by different classes. We have encountered no cases that have this been better than the others, except when extreme undersampling or oversampling is accomplished.Outlier elimination: After cluster analysis, eliminate data points that are farthest from the centroid and outside the cluster. Datapoint elimination should be accomplished under human supervision (i.e., manually). For example, a salary of $2,000,000/year is probably a real datapoint of the underlying distribution, whereas a spider’s length of 50 meters is probably wrong. Some would argue the entire row should not be eliminated, but rather, the spurious value is replaced with something more sensical, like the median or the mean. In any case, elimination results in lower information content.Undersampling: The majority class(es) members decrease through different strategies of sampling. Undersampling is usually one of the worst approaches as the amount of data in the dataset is reduced. Again, information loss in which most models fit worse with a decrease in data. You also must be careful of underfitting, which when the training dataset (with the undersample) never has a better loss metric than the validation or test dataset.Oversampling: The minority class(es) members increase through different strategies of synthetic data generation. SMOTE (Synthetic Minority Oversampling Technique) and ADASYN( Adaptive Synthetic) are the most well known in the oversampling category. Oversampling is usually one of the best approaches as the number of samples is increased. All models fit better with an increase in data. However, it would be best if you were careful of overfitting Overfitting occurs when the training dataset (with the oversample) has a better loss metric than the validation or test dataset. weight assignment: These various methods put a higher weight on minority classes and lower weight on majority classes. No real information is added to the dataset. Instead, this is regulation by different classes. We have encountered no cases that have this been better than the others, except when extreme undersampling or oversampling is accomplished. Outlier elimination: After cluster analysis, eliminate data points that are farthest from the centroid and outside the cluster. Datapoint elimination should be accomplished under human supervision (i.e., manually). For example, a salary of $2,000,000/year is probably a real datapoint of the underlying distribution, whereas a spider’s length of 50 meters is probably wrong. Some would argue the entire row should not be eliminated, but rather, the spurious value is replaced with something more sensical, like the median or the mean. In any case, elimination results in lower information content. Undersampling: The majority class(es) members decrease through different strategies of sampling. Undersampling is usually one of the worst approaches as the amount of data in the dataset is reduced. Again, information loss in which most models fit worse with a decrease in data. You also must be careful of underfitting, which when the training dataset (with the undersample) never has a better loss metric than the validation or test dataset. Oversampling: The minority class(es) members increase through different strategies of synthetic data generation. SMOTE (Synthetic Minority Oversampling Technique) and ADASYN( Adaptive Synthetic) are the most well known in the oversampling category. Oversampling is usually one of the best approaches as the number of samples is increased. All models fit better with an increase in data. However, it would be best if you were careful of overfitting Overfitting occurs when the training dataset (with the oversample) has a better loss metric than the validation or test dataset. Warning:Only SMOTEC can balance datasets with categorical features. All others will accept a dataset only with continuous features. The given oversampling techniques are: RandomeOverSample SMOTE ADASYN BorderLineSMOTE SVSMOTE SMOTENC ADASYN focuses on generating samples next to the original samples which are wrongly classified using a k-Nearest Neighbors classifier while the basic implementation of SMOTE will not make any distinction between easy and hard samples to be classified using the nearest neighbors rule. Therefore, the decision function found during training will be different among the algorithms. However, because of distance from centroid metric, the class clusters need to be circular in shape for either method to work well. The given undersampling techniques are: RandomUnderSample ClusterCentroids various versions of SMOTE ADASYN The outlier elimination (results in undersampling) techniques are: NearMiss EditedNearestNeighbour CondensedNearestNeighbour You can read in detail about these class balance techniques as well as examples in the extensive imbalance-sklearn documentation. All available class balance strategies are shown with: from paso.pre.cleaners import Balancersclass_balancer = Balancers(description_filepath=balancer_file)o.classBalancers() I am going to oversample the minority classes by using SMOTE. I recommend reading, towardsdatascience.com for more detail on how to balance class-imbalanced datasets. balancer = Balancers(description_filepath=balancer_file)X_train,y_train = balancer.transform(X_train,y_train)train = X_train.copy()Xy_to_DataFrame(train, y_train, inputer.target)train.groupby([inputer.target]).count() from paso.learners.learners import Learnerslearner = Learners(description_filepath=learner_file)learner.train(X_train,y_train)learner.cross_validate(X_train,y_train,description_filepath=cv_file)learner.evaluate(X_test, y_test) Notice with class balancing the False-Positive for the former minority, class 1 has decreased from 21 to 15 (good) (as shown in the confusion-matrix). Whereas the former majority class has increased False-Positive from 6 to 9 (bad). More importantly, f1 has increased to 0.8356andlogloss has decreased to 0.1346.It appears SMOTEclass balancing has helped in our fit of the yeast3 dataset. Now we can augment (increase by 100% the amount data) with synthetic data generated by a class imbalance method using SMOTE. The result is similar to image augmentation in that we accomplished structured data augmentation by increasing the row count of theyeast3dataset with synthetic data. from paso.pre.cleaners import Augmentersaugmenter = Augmenters(description_filepath=balancer_file)ratio = 1.0X_augment,y_augment = augmenter.transform(X_train,y_train,ratio=ratio, verbose=True)_, _, occurCount = np.unique( y_augment, return_index=True, return_counts=True)occurCount learner = Learners(description_filepath=learner_file,target=inputer.target)learner.train(X_augment,y_augment )learner.cross_validate(X_augment,y_augment ,description_filepath=cv_file)learner.evaluate(X_test, y_test) Oversampling the data using SMOTE''s cluster sampling is ambiguous at best. Both loglossand f1 have increased! This indicates that the clusters of yeast3are not the circular shape required by SMOTE.Next, I will further augment the dataset using SMOTE three more times, doubling the dataset row count each time. Graphing the logloss versus the row count and f1shows: I can not state that SMOTE does not generate good pseudo-data. For that, we need to optimize the hyper-parameters of the learner for each augmentation, look at the shape of the data with PCA and cluster-analysis, try different learners, and try different data augmenters besides SMOTE. I will do this in Part 2 of this article. We have introduced paso’s data input class, Inputer, and the Spitterclass to split data into train, valid, and test datasets. I also lightly brushed over description files that capture the description of the actions we want one of our classes to take. I stated, through casual argument, that description files are better than coded keyword arguments. Yes, we gain some language independence from description files. Finally, I made a light foray into the use of learners and cross-validation of those learners. I have focused on the major topics of this article, Balancersand Augmenters. We saw how to augment structured data. Balancing improved the predictive power of the learner, but in this minimal study, we failed to show further data augmentation increased predictive power using SMOTE. Other articles on paso are: paso’s Offering of Logging and Parameter Services for your Python Projectmedium.com In future articles, I will cover paso in more depth with: augmenting structured data with other augmentation methods. and more If you have a service or feature or see a bug, then leave the paso project a note. Thanks for reading. I hope this gives you a better understanding of the basics of paso and its usage for your machine learning task.
[ { "code": null, "e": 450, "s": 172, "text": "When data augmentation is discussed, it is almost always about increasing the image data set by rotation, flipping, or in some way, changing the existing images to create more images. You may even come across methods for augmented unstructured data, such as words in documents." }, { "code": null, "e": 667, "s": 450, "text": "Structured Data Augmentation is rarely discussed in theoretical approaches and rarely appears in real-world production systems. When it does, it is not called augmentation but rather class balancing or over-sampling." }, { "code": null, "e": 927, "s": 667, "text": "I will show a simplistic approach to Structured Data Augmentation. In a future follow-on to this article, I will demonstrate a complete strategy that avoids a simple k-means clustering that is at the heart of over-sampling techniques such as SMOOT and ADASYN." }, { "code": null, "e": 1501, "s": 927, "text": "Along the way, we will introduce paso Class Balancing tools. As was shown in the previous article, paso supports and is compatible with current machine learning and deep learning frameworks. paso is a package written in Python and some C(for speed) that was initially intended to bundle best-practices and state-of-the-art services, classes, and functions for the Machine Learning and Deep Learning community. paso has grown beyond this to offer decorators, classes, and methods you can use in your pipelines or custom code with or without adopting the entire paso package." }, { "code": null, "e": 1754, "s": 1501, "text": "A pipeline is composed of steps. Each step transforms the input dataset. A step will return a measurement (or dictionary of measurements), output a graph or the transformed dataset. Note: this is different but compatible with the Scikit-Learn pipeline." }, { "code": null, "e": 2078, "s": 1754, "text": "Paso currently offers the following classes: Inputer, Splitters, Cleaners, Encoders, Scalers, Balancers, Augmenters, and Learners. All classes provide logging, description files, and checkpointing. The last class, Learners, implements the methods: train, predict, evaluate, cross-validate, and hyper-parameter optimization." }, { "code": null, "e": 2140, "s": 2078, "text": "The discussion will divide into the following major segments:" }, { "code": null, "e": 2204, "s": 2140, "text": "First, we load an imbalanced class dataset with a paso Inputer." }, { "code": null, "e": 2279, "s": 2204, "text": "Second, I will survey some of the class balancing methods offered in paso." }, { "code": null, "e": 2400, "s": 2279, "text": "Next, I will show that some of the structured data augmentation offered in paso derive from the class balancing methods." }, { "code": null, "e": 2518, "s": 2400, "text": "Then, I hint that these methods might be inadequate for more than just balancing the augmentation of structured data." }, { "code": null, "e": 2588, "s": 2518, "text": "Finally, I finish this article with a Discussion and Summary section." }, { "code": null, "e": 2707, "s": 2588, "text": "As usual, the source code for all examples sampled in this article is also available as one complete notebook (ipynb)." }, { "code": null, "e": 2791, "s": 2707, "text": "paso’s Offering of Logging and Parameter Services for your Python Projectmedium.com" }, { "code": null, "e": 2858, "s": 2791, "text": "As we saw in the above article, we can startup paso services with:" }, { "code": null, "e": 3007, "s": 2858, "text": "from paso.base import Paso,Log,PasoErrorfrom loguru import loggersession = Paso(parameters_filepath='../parameters/default-lesson.3.yaml').startup()" }, { "code": null, "e": 3228, "s": 3007, "text": "Imbalanced data sets are a particular case for classification problems where the class distribution is not uniform. Typically, they compose by two classes: the majority (negative) class and the minority (positive) class." }, { "code": null, "e": 3406, "s": 3228, "text": "I have picked the yeast3dataset as it has studied by biologists and machine learning scientists since the late 1990s. It downloads from https://sci2s.ugr.es/keel/imbalanced.php." }, { "code": null, "e": 3511, "s": 3406, "text": "We load the yeast3 data set into the dataset dataframe. The feature class will contain the class values." }, { "code": null, "e": 3546, "s": 3511, "text": "The features for this dataset are:" }, { "code": null, "e": 3644, "s": 3546, "text": "Class: predicted or dependent or target feature. The 0th class has an 8:1 ratio to the 1st class." }, { "code": null, "e": 3699, "s": 3644, "text": "Mcg: McGeoch’s method for signal sequence recognition." }, { "code": null, "e": 3757, "s": 3699, "text": "Gvh: von Heijne’s method for signal sequence recognition." }, { "code": null, "e": 3825, "s": 3757, "text": "Alm: Score of the ALOM membrane-spanning region prediction program." }, { "code": null, "e": 3980, "s": 3825, "text": "Mit: Score of discriminant analysis of the amino acid content of the N-terminal region (20 residues long) of mitochondrial and non-mitochondrial proteins." }, { "code": null, "e": 4111, "s": 3980, "text": "Erl: Presence of “HDEL” substring (thought to act as a signal for retention in the endoplasmic reticulum lumen). Binary attribute." }, { "code": null, "e": 4164, "s": 4111, "text": "Pox: Peroxisomal targeting signal in the C-terminus." }, { "code": null, "e": 4266, "s": 4164, "text": "Vac: Score of discriminant analysis of the amino acid content of vacuolar and extracellular proteins." }, { "code": null, "e": 4370, "s": 4266, "text": "Nuc: Score of discriminant analysis of nuclear localization signals of nuclear and non-nuclear protein." }, { "code": null, "e": 4532, "s": 4370, "text": "These features are different types of measurements of the yeast strains. Do not worry if you do not know what they mean, as it is not essential for this article." }, { "code": null, "e": 4675, "s": 4532, "text": "Instead of using keyword arguments cemented in code, I will use a description file. One working definition of description (from Wikipedia) is:" }, { "code": null, "e": 4764, "s": 4675, "text": "“showing the relations between the concepts and categories in a subject area or domain.”" }, { "code": null, "e": 4804, "s": 4764, "text": "We are using description files because:" }, { "code": null, "e": 4887, "s": 4804, "text": "the description of an object (dataset, model, etc.) changes without changing code;" }, { "code": null, "e": 5224, "s": 4887, "text": "The parsing performance of a description file and python are about the same as both use dynamic typing. Performance concerns probably would not be the case for statically typed language. However, an object’s metadata parsing compute is very tiny compared to the action(s) performed by the class instance in all cases encountered so far." }, { "code": null, "e": 5350, "s": 5224, "text": "A description file is language independent. It is currently formatted as a YAML file but can also cast as a JSON or XML file." }, { "code": null, "e": 5572, "s": 5350, "text": "Description files consist of a hierarchy of key-value pairs. In a future article, I will cover description files in detail — different description files viewed at https://github.com/bcottman/paso/tree/master/descriptions." }, { "code": null, "e": 5787, "s": 5572, "text": "Before training the learner, it is imperative to balance only the dataset we will train. We want to know the effect of balancing data on the learner, while not corrupting our validation dataset with augmented data." }, { "code": null, "e": 6429, "s": 5787, "text": "Validation draws from the initial train dataset in the hopes it is a sample of the past and future data that the test dataset draws from the training set remainder. In this case, our validation set is referenced asX_test, y_test. The other situation where train, valid, and test from the original dataset is covered is by splitting the initial dataset to result in a train dataset and validation dataset. Then split on a train again to get train and test. The order does not matter so long as the second split is also on the train dataset. Here the training set will be 70%, and the validation (test) set will be 30% of the original dataset." }, { "code": null, "e": 6715, "s": 6429, "text": "X, y = DataFrame_to_Xy(dataset, inputer.target)splitter = Splitters(description_filepath=splitter_file)X_train,X_test, y_train, y_test = splitter.transform(X, y,random_state=11)train = X_train.copy()Xy_to_DataFrame(train, y_train, inputer.target)train.groupby([inputer.target]).count()" }, { "code": null, "e": 6897, "s": 6715, "text": "Before we balance the class, let us run RandomForest learner with generic classification hyper-parameters (shown above in the description file for RadomForest) on the yeast3dataset." }, { "code": null, "e": 7124, "s": 6897, "text": "from paso.learners.learners import Learnerslearner = Learners(description_filepath=learner_file)learner.train(X_train,y_train)learner.cross_validate(X_train,y_train,description_filepath=cv_file)learner.evaluate(X_test, y_test)" }, { "code": null, "e": 7238, "s": 7124, "text": "This is a fairly good fit with an f1 of 0.8207.What happens when we balance class 1 with class 0 by oversampling?" }, { "code": null, "e": 7424, "s": 7238, "text": "In a future article, I will cover in detail how to use paso’s cross-validation for learners that train and predict. In the meantime, you can find a good overview of cross-validation in:" }, { "code": null, "e": 7447, "s": 7424, "text": "towardsdatascience.com" }, { "code": null, "e": 7497, "s": 7447, "text": "and a detailed discussion of cross-validation in:" }, { "code": null, "e": 7514, "s": 7497, "text": "scikit-learn.org" }, { "code": null, "e": 7637, "s": 7514, "text": "In this article, I usesklearn.cross_validate.This is hopefully a good choice for the structured datasets we will be using." }, { "code": null, "e": 7657, "s": 7637, "text": "www.jeremyjordan.me" }, { "code": null, "e": 7991, "s": 7657, "text": "Imbalanced data typically refers to a classification problem where the number of observations per class is not equally distributed; often you’ll have a large amount of data/observations for one class (referred to as the majority class), and much fewer observations for one or more other classes (referred to as the minority classes)." }, { "code": null, "e": 8002, "s": 7991, "text": "medium.com" }, { "code": null, "e": 8227, "s": 8002, "text": "Imbalanced data is not always a bad thing, and in real data sets, there is always some degree of imbalance. That said, there should not be any big impact on your model performance if the level of imbalance is relatively low." }, { "code": null, "e": 8304, "s": 8227, "text": "sampling techniques perform differently under different levels of imbalance." }, { "code": null, "e": 8377, "s": 8304, "text": "There are currently four different types of approaches to class balance:" }, { "code": null, "e": 10347, "s": 8377, "text": "weight assignment: These various methods put a higher weight on minority classes and lower weight on majority classes. No real information is added to the dataset. Instead, this is regulation by different classes. We have encountered no cases that have this been better than the others, except when extreme undersampling or oversampling is accomplished.Outlier elimination: After cluster analysis, eliminate data points that are farthest from the centroid and outside the cluster. Datapoint elimination should be accomplished under human supervision (i.e., manually). For example, a salary of $2,000,000/year is probably a real datapoint of the underlying distribution, whereas a spider’s length of 50 meters is probably wrong. Some would argue the entire row should not be eliminated, but rather, the spurious value is replaced with something more sensical, like the median or the mean. In any case, elimination results in lower information content.Undersampling: The majority class(es) members decrease through different strategies of sampling. Undersampling is usually one of the worst approaches as the amount of data in the dataset is reduced. Again, information loss in which most models fit worse with a decrease in data. You also must be careful of underfitting, which when the training dataset (with the undersample) never has a better loss metric than the validation or test dataset.Oversampling: The minority class(es) members increase through different strategies of synthetic data generation. SMOTE (Synthetic Minority Oversampling Technique) and ADASYN( Adaptive Synthetic) are the most well known in the oversampling category. Oversampling is usually one of the best approaches as the number of samples is increased. All models fit better with an increase in data. However, it would be best if you were careful of overfitting Overfitting occurs when the training dataset (with the oversample) has a better loss metric than the validation or test dataset." }, { "code": null, "e": 10701, "s": 10347, "text": "weight assignment: These various methods put a higher weight on minority classes and lower weight on majority classes. No real information is added to the dataset. Instead, this is regulation by different classes. We have encountered no cases that have this been better than the others, except when extreme undersampling or oversampling is accomplished." }, { "code": null, "e": 11299, "s": 10701, "text": "Outlier elimination: After cluster analysis, eliminate data points that are farthest from the centroid and outside the cluster. Datapoint elimination should be accomplished under human supervision (i.e., manually). For example, a salary of $2,000,000/year is probably a real datapoint of the underlying distribution, whereas a spider’s length of 50 meters is probably wrong. Some would argue the entire row should not be eliminated, but rather, the spurious value is replaced with something more sensical, like the median or the mean. In any case, elimination results in lower information content." }, { "code": null, "e": 11743, "s": 11299, "text": "Undersampling: The majority class(es) members decrease through different strategies of sampling. Undersampling is usually one of the worst approaches as the amount of data in the dataset is reduced. Again, information loss in which most models fit worse with a decrease in data. You also must be careful of underfitting, which when the training dataset (with the undersample) never has a better loss metric than the validation or test dataset." }, { "code": null, "e": 12320, "s": 11743, "text": "Oversampling: The minority class(es) members increase through different strategies of synthetic data generation. SMOTE (Synthetic Minority Oversampling Technique) and ADASYN( Adaptive Synthetic) are the most well known in the oversampling category. Oversampling is usually one of the best approaches as the number of samples is increased. All models fit better with an increase in data. However, it would be best if you were careful of overfitting Overfitting occurs when the training dataset (with the oversample) has a better loss metric than the validation or test dataset." }, { "code": null, "e": 12452, "s": 12320, "text": "Warning:Only SMOTEC can balance datasets with categorical features. All others will accept a dataset only with continuous features." }, { "code": null, "e": 12491, "s": 12452, "text": "The given oversampling techniques are:" }, { "code": null, "e": 12509, "s": 12491, "text": "RandomeOverSample" }, { "code": null, "e": 12515, "s": 12509, "text": "SMOTE" }, { "code": null, "e": 12522, "s": 12515, "text": "ADASYN" }, { "code": null, "e": 12538, "s": 12522, "text": "BorderLineSMOTE" }, { "code": null, "e": 12546, "s": 12538, "text": "SVSMOTE" }, { "code": null, "e": 12554, "s": 12546, "text": "SMOTENC" }, { "code": null, "e": 13065, "s": 12554, "text": "ADASYN focuses on generating samples next to the original samples which are wrongly classified using a k-Nearest Neighbors classifier while the basic implementation of SMOTE will not make any distinction between easy and hard samples to be classified using the nearest neighbors rule. Therefore, the decision function found during training will be different among the algorithms. However, because of distance from centroid metric, the class clusters need to be circular in shape for either method to work well." }, { "code": null, "e": 13105, "s": 13065, "text": "The given undersampling techniques are:" }, { "code": null, "e": 13123, "s": 13105, "text": "RandomUnderSample" }, { "code": null, "e": 13140, "s": 13123, "text": "ClusterCentroids" }, { "code": null, "e": 13166, "s": 13140, "text": "various versions of SMOTE" }, { "code": null, "e": 13173, "s": 13166, "text": "ADASYN" }, { "code": null, "e": 13240, "s": 13173, "text": "The outlier elimination (results in undersampling) techniques are:" }, { "code": null, "e": 13249, "s": 13240, "text": "NearMiss" }, { "code": null, "e": 13272, "s": 13249, "text": "EditedNearestNeighbour" }, { "code": null, "e": 13298, "s": 13272, "text": "CondensedNearestNeighbour" }, { "code": null, "e": 13428, "s": 13298, "text": "You can read in detail about these class balance techniques as well as examples in the extensive imbalance-sklearn documentation." }, { "code": null, "e": 13483, "s": 13428, "text": "All available class balance strategies are shown with:" }, { "code": null, "e": 13603, "s": 13483, "text": "from paso.pre.cleaners import Balancersclass_balancer = Balancers(description_filepath=balancer_file)o.classBalancers()" }, { "code": null, "e": 13686, "s": 13603, "text": "I am going to oversample the minority classes by using SMOTE. I recommend reading," }, { "code": null, "e": 13709, "s": 13686, "text": "towardsdatascience.com" }, { "code": null, "e": 13770, "s": 13709, "text": "for more detail on how to balance class-imbalanced datasets." }, { "code": null, "e": 13988, "s": 13770, "text": "balancer = Balancers(description_filepath=balancer_file)X_train,y_train = balancer.transform(X_train,y_train)train = X_train.copy()Xy_to_DataFrame(train, y_train, inputer.target)train.groupby([inputer.target]).count()" }, { "code": null, "e": 14215, "s": 13988, "text": "from paso.learners.learners import Learnerslearner = Learners(description_filepath=learner_file)learner.train(X_train,y_train)learner.cross_validate(X_train,y_train,description_filepath=cv_file)learner.evaluate(X_test, y_test)" }, { "code": null, "e": 14604, "s": 14215, "text": "Notice with class balancing the False-Positive for the former minority, class 1 has decreased from 21 to 15 (good) (as shown in the confusion-matrix). Whereas the former majority class has increased False-Positive from 6 to 9 (bad). More importantly, f1 has increased to 0.8356andlogloss has decreased to 0.1346.It appears SMOTEclass balancing has helped in our fit of the yeast3 dataset." }, { "code": null, "e": 14895, "s": 14604, "text": "Now we can augment (increase by 100% the amount data) with synthetic data generated by a class imbalance method using SMOTE. The result is similar to image augmentation in that we accomplished structured data augmentation by increasing the row count of theyeast3dataset with synthetic data." }, { "code": null, "e": 15181, "s": 14895, "text": "from paso.pre.cleaners import Augmentersaugmenter = Augmenters(description_filepath=balancer_file)ratio = 1.0X_augment,y_augment = augmenter.transform(X_train,y_train,ratio=ratio, verbose=True)_, _, occurCount = np.unique( y_augment, return_index=True, return_counts=True)occurCount" }, { "code": null, "e": 15397, "s": 15181, "text": "learner = Learners(description_filepath=learner_file,target=inputer.target)learner.train(X_augment,y_augment )learner.cross_validate(X_augment,y_augment ,description_filepath=cv_file)learner.evaluate(X_test, y_test)" }, { "code": null, "e": 15763, "s": 15397, "text": "Oversampling the data using SMOTE''s cluster sampling is ambiguous at best. Both loglossand f1 have increased! This indicates that the clusters of yeast3are not the circular shape required by SMOTE.Next, I will further augment the dataset using SMOTE three more times, doubling the dataset row count each time. Graphing the logloss versus the row count and f1shows:" }, { "code": null, "e": 16091, "s": 15763, "text": "I can not state that SMOTE does not generate good pseudo-data. For that, we need to optimize the hyper-parameters of the learner for each augmentation, look at the shape of the data with PCA and cluster-analysis, try different learners, and try different data augmenters besides SMOTE. I will do this in Part 2 of this article." }, { "code": null, "e": 16601, "s": 16091, "text": "We have introduced paso’s data input class, Inputer, and the Spitterclass to split data into train, valid, and test datasets. I also lightly brushed over description files that capture the description of the actions we want one of our classes to take. I stated, through casual argument, that description files are better than coded keyword arguments. Yes, we gain some language independence from description files. Finally, I made a light foray into the use of learners and cross-validation of those learners." }, { "code": null, "e": 16884, "s": 16601, "text": "I have focused on the major topics of this article, Balancersand Augmenters. We saw how to augment structured data. Balancing improved the predictive power of the learner, but in this minimal study, we failed to show further data augmentation increased predictive power using SMOTE." }, { "code": null, "e": 16912, "s": 16884, "text": "Other articles on paso are:" }, { "code": null, "e": 16996, "s": 16912, "text": "paso’s Offering of Logging and Parameter Services for your Python Projectmedium.com" }, { "code": null, "e": 17054, "s": 16996, "text": "In future articles, I will cover paso in more depth with:" }, { "code": null, "e": 17114, "s": 17054, "text": "augmenting structured data with other augmentation methods." }, { "code": null, "e": 17123, "s": 17114, "text": "and more" }, { "code": null, "e": 17206, "s": 17123, "text": "If you have a service or feature or see a bug, then leave the paso project a note." } ]
Comprehensive LightGBM Tutorial (2021) | Towards Data Science
Learn how to crush XGBoost in this comprehensive LightGBM tutorial. I am confused. So many people are drawn to XGBoost like a moth to a flame. Yes, it has seen some glorious days in prestigious competitions, and it’s still the most widely-used ML library. But, it has been 4 years since XGBoost lost its top spot in terms of performance. In 2017, Microsoft open-sourced LightGBM (Light Gradient Boosting Machine) that gives equally high accuracy with 2–10 times less training speed. This is a game-changing advantage considering the ubiquity of massive, million-row datasets. There are other distinctions that tip the scales towards LightGBM and give it an edge over XGBoost. By the end of this post, you will learn about these advantages, including: how to develop LightGBM models for classification and regression tasks structural differences between XGBoost and LGBM how to use early stopping and evaluation sets enabling powerful categorical feature support for up 8x times speed increase implementing successful cross-validation with LGBM hyperparameter tuning with Optuna (Part II) When LGBM got released, it came with ground-breaking changes to the way it grows decision trees. Both XGBoost and LightGBM are ensebmle algorithms. They use a special type of decision trees, also called weak learners, to capture complex, non-linear patterns. In XGBoost (and many other libraries), decision trees were built one level at a time: This type of structure tends to result in unnecessary nodes and leaves because the trees continued to build until the max_depth reached. This led to higher model complexity and training cost runtime. In contrast, LightGBM takes a leaf-wise approach: The structure continues to grow with the most promising branches and leaves (nodes with the most delta loss), holding the number of the decision leaves constant. (If this doesn’t make sense to you, don’t sweat. This won’t prevent you from effectively using LGBM). This is one of the main reasons LGBM crushed XGBoost in terms of speed when it first came out. Above is a benchmark comparison of XGBoost with traditional decision trees and LGBM with leaf-wise structure (first and last columns) on datasets with ~500k-13M samples. It shows that LGBM is orders of magnitude faster than XGB. LGBM also uses histogram binning of continuous features, which provides even more speed-up than traditional gradient boosting. Binning numeric values significantly decrease the number of split points to consider in decision trees, and they remove the need to use sorting algorithms, which are always computation-heavy. Inspired by LGBM, XGBoost also introduced histogram-binning, which gave massive speed-up but still not enough to match LGBM’s: We will continue exploring the differences in the coming sections. Like XGBoost, LGBM has two APIs — core learning API and Sklearn-compatible one. You know I am a big fan of Sklearn, so this tutorial will focus on that version. Sklearn-compatible API of XGBoost and LGBM allows you to integrate their models in the Sklearn ecosystem so that you can use them inside pipelines in combination with other transformers. Sklearn API exposes LGBMRegressor and LGBMClassifier, with the familiar fit/predict/predict_proba pattern: objective specifies the type of learning task. Besides the common ones like binary, multiclass and regression tasks, there are others like poisson, tweedie regressions. See this section of the documentation for the full list of objectives. >>> reg.fit(X, y)LGBMRegressor() The number of decision trees inside the ensemble significantly affects the results. You can control it using the n_estimators parameter in both the classifier and regressor. Below, we will fit an LGBM binary classifier on the Kaggle TPS March dataset with 1000 decision trees: Adding more trees leads to more accuracy but increases the risk of overfitting. To combat this, you can create many trees (+2000) and choose a smaller learning_rate (more on this later). Like in XGBoost, fitting a single decision tree to the data is called a boosting round. Each tree in the ensemble builds on the predictions of the last tree — i.e., each boosting round is an improvement of the last. If the predictions don’t improve after a sequence of rounds, it is sensible to stop the training of the ensemble even if we are not at a hard stop for n_estimators. To achieve this, LGBM provides early_stopping_rounds parameter inside the fit function. For example, setting it to 100 means we stop the training if the predictions have not improved for the last 100 rounds. Before looking at a code example, we should learn a couple of concepts connected to early stopping. Early stopping is only enabled when you pass a set of evaluation sets to eval_set parameter of the fit method. These evaluation sets are used to keep track of the quality of the predictions from one boosting round to the next: In each round of n_estimators, a single decision tree is fit to (X_train, y_train) and predictions are made on the passed evaluation set (X_eval, y_eval). The quality of predictions is measured with a passed metric in eval_metric. The training stops at the 738th iteration because the validation score has not improved since the 638th one — early stopping of 100 rounds. Now, we have the luxury of creating as many trees as we want and early_stopping_rounds can discard the unnecessary ones. Let’s establish a baseline score with what we know so far. We will do the same for XGBoost so that we can compare the results: LGBM achieved a smaller loss in ~4 times less runtime. Let’s see a final LGBM trick before we move on to cross-validation. Histogram binning in LGBM comes with built-in support for handling missing values and categorical features. TPS March dataset contains 19 categoricals, and we have been using one-hot encoding up to this point. This time, we will let LGBM deal with categoricals and compare the results with XGBoost once again: To specify the categorical features, pass a list of their indices to categorical_feature parameter in the fit method: You can achieve up to 8x speed up if you use pandas.Categorical data type when using LGBM. The table shows the final scores and runtimes of both models. As you can see, the version with default categorical handling beat others both in accuracy and speed. Cheers! The most common way of doing CV with LGBM is to use Sklearn CV splitters. I am not talking about utility functions like cross_validate or cross_val_score but splitters like KFold or StratifiedKFold with their split method. Doing CV in this way gives you more control over the whole process. I have talked many times about the importance of cross-validation. You can read this post for more details. Also, it enables you to use early stopping during cross-validation in a hassle-free manner. Here is what this looks like for the TPS March data: First, create a CV splitter — we are choosing StratifiedKFold because it is a classification problem. Then, loop through each train/test sets using split. In each fold, initialize and train a new LGBM model and optionally report the score and runtime. That's it! That's how most people do CV, including on Kaggle. In this post, we learned pure modeling techniques with LightGBM. Next up, we will explore how to squeeze every bit of performance out of LGBM models using Optuna. Specifically, Part II of this article will include a detailed overview of the most important LGBM hyperparameters and introduce a well-tested hyperparameter tuning workflow. It is already out — read it here.
[ { "code": null, "e": 239, "s": 171, "text": "Learn how to crush XGBoost in this comprehensive LightGBM tutorial." }, { "code": null, "e": 254, "s": 239, "text": "I am confused." }, { "code": null, "e": 427, "s": 254, "text": "So many people are drawn to XGBoost like a moth to a flame. Yes, it has seen some glorious days in prestigious competitions, and it’s still the most widely-used ML library." }, { "code": null, "e": 654, "s": 427, "text": "But, it has been 4 years since XGBoost lost its top spot in terms of performance. In 2017, Microsoft open-sourced LightGBM (Light Gradient Boosting Machine) that gives equally high accuracy with 2–10 times less training speed." }, { "code": null, "e": 847, "s": 654, "text": "This is a game-changing advantage considering the ubiquity of massive, million-row datasets. There are other distinctions that tip the scales towards LightGBM and give it an edge over XGBoost." }, { "code": null, "e": 922, "s": 847, "text": "By the end of this post, you will learn about these advantages, including:" }, { "code": null, "e": 993, "s": 922, "text": "how to develop LightGBM models for classification and regression tasks" }, { "code": null, "e": 1041, "s": 993, "text": "structural differences between XGBoost and LGBM" }, { "code": null, "e": 1087, "s": 1041, "text": "how to use early stopping and evaluation sets" }, { "code": null, "e": 1164, "s": 1087, "text": "enabling powerful categorical feature support for up 8x times speed increase" }, { "code": null, "e": 1215, "s": 1164, "text": "implementing successful cross-validation with LGBM" }, { "code": null, "e": 1259, "s": 1215, "text": "hyperparameter tuning with Optuna (Part II)" }, { "code": null, "e": 1356, "s": 1259, "text": "When LGBM got released, it came with ground-breaking changes to the way it grows decision trees." }, { "code": null, "e": 1518, "s": 1356, "text": "Both XGBoost and LightGBM are ensebmle algorithms. They use a special type of decision trees, also called weak learners, to capture complex, non-linear patterns." }, { "code": null, "e": 1604, "s": 1518, "text": "In XGBoost (and many other libraries), decision trees were built one level at a time:" }, { "code": null, "e": 1804, "s": 1604, "text": "This type of structure tends to result in unnecessary nodes and leaves because the trees continued to build until the max_depth reached. This led to higher model complexity and training cost runtime." }, { "code": null, "e": 1854, "s": 1804, "text": "In contrast, LightGBM takes a leaf-wise approach:" }, { "code": null, "e": 2118, "s": 1854, "text": "The structure continues to grow with the most promising branches and leaves (nodes with the most delta loss), holding the number of the decision leaves constant. (If this doesn’t make sense to you, don’t sweat. This won’t prevent you from effectively using LGBM)." }, { "code": null, "e": 2213, "s": 2118, "text": "This is one of the main reasons LGBM crushed XGBoost in terms of speed when it first came out." }, { "code": null, "e": 2442, "s": 2213, "text": "Above is a benchmark comparison of XGBoost with traditional decision trees and LGBM with leaf-wise structure (first and last columns) on datasets with ~500k-13M samples. It shows that LGBM is orders of magnitude faster than XGB." }, { "code": null, "e": 2761, "s": 2442, "text": "LGBM also uses histogram binning of continuous features, which provides even more speed-up than traditional gradient boosting. Binning numeric values significantly decrease the number of split points to consider in decision trees, and they remove the need to use sorting algorithms, which are always computation-heavy." }, { "code": null, "e": 2888, "s": 2761, "text": "Inspired by LGBM, XGBoost also introduced histogram-binning, which gave massive speed-up but still not enough to match LGBM’s:" }, { "code": null, "e": 2955, "s": 2888, "text": "We will continue exploring the differences in the coming sections." }, { "code": null, "e": 3116, "s": 2955, "text": "Like XGBoost, LGBM has two APIs — core learning API and Sklearn-compatible one. You know I am a big fan of Sklearn, so this tutorial will focus on that version." }, { "code": null, "e": 3303, "s": 3116, "text": "Sklearn-compatible API of XGBoost and LGBM allows you to integrate their models in the Sklearn ecosystem so that you can use them inside pipelines in combination with other transformers." }, { "code": null, "e": 3410, "s": 3303, "text": "Sklearn API exposes LGBMRegressor and LGBMClassifier, with the familiar fit/predict/predict_proba pattern:" }, { "code": null, "e": 3650, "s": 3410, "text": "objective specifies the type of learning task. Besides the common ones like binary, multiclass and regression tasks, there are others like poisson, tweedie regressions. See this section of the documentation for the full list of objectives." }, { "code": null, "e": 3683, "s": 3650, "text": ">>> reg.fit(X, y)LGBMRegressor()" }, { "code": null, "e": 3960, "s": 3683, "text": "The number of decision trees inside the ensemble significantly affects the results. You can control it using the n_estimators parameter in both the classifier and regressor. Below, we will fit an LGBM binary classifier on the Kaggle TPS March dataset with 1000 decision trees:" }, { "code": null, "e": 4147, "s": 3960, "text": "Adding more trees leads to more accuracy but increases the risk of overfitting. To combat this, you can create many trees (+2000) and choose a smaller learning_rate (more on this later)." }, { "code": null, "e": 4235, "s": 4147, "text": "Like in XGBoost, fitting a single decision tree to the data is called a boosting round." }, { "code": null, "e": 4363, "s": 4235, "text": "Each tree in the ensemble builds on the predictions of the last tree — i.e., each boosting round is an improvement of the last." }, { "code": null, "e": 4528, "s": 4363, "text": "If the predictions don’t improve after a sequence of rounds, it is sensible to stop the training of the ensemble even if we are not at a hard stop for n_estimators." }, { "code": null, "e": 4736, "s": 4528, "text": "To achieve this, LGBM provides early_stopping_rounds parameter inside the fit function. For example, setting it to 100 means we stop the training if the predictions have not improved for the last 100 rounds." }, { "code": null, "e": 4836, "s": 4736, "text": "Before looking at a code example, we should learn a couple of concepts connected to early stopping." }, { "code": null, "e": 5063, "s": 4836, "text": "Early stopping is only enabled when you pass a set of evaluation sets to eval_set parameter of the fit method. These evaluation sets are used to keep track of the quality of the predictions from one boosting round to the next:" }, { "code": null, "e": 5294, "s": 5063, "text": "In each round of n_estimators, a single decision tree is fit to (X_train, y_train) and predictions are made on the passed evaluation set (X_eval, y_eval). The quality of predictions is measured with a passed metric in eval_metric." }, { "code": null, "e": 5555, "s": 5294, "text": "The training stops at the 738th iteration because the validation score has not improved since the 638th one — early stopping of 100 rounds. Now, we have the luxury of creating as many trees as we want and early_stopping_rounds can discard the unnecessary ones." }, { "code": null, "e": 5682, "s": 5555, "text": "Let’s establish a baseline score with what we know so far. We will do the same for XGBoost so that we can compare the results:" }, { "code": null, "e": 5805, "s": 5682, "text": "LGBM achieved a smaller loss in ~4 times less runtime. Let’s see a final LGBM trick before we move on to cross-validation." }, { "code": null, "e": 6015, "s": 5805, "text": "Histogram binning in LGBM comes with built-in support for handling missing values and categorical features. TPS March dataset contains 19 categoricals, and we have been using one-hot encoding up to this point." }, { "code": null, "e": 6115, "s": 6015, "text": "This time, we will let LGBM deal with categoricals and compare the results with XGBoost once again:" }, { "code": null, "e": 6233, "s": 6115, "text": "To specify the categorical features, pass a list of their indices to categorical_feature parameter in the fit method:" }, { "code": null, "e": 6324, "s": 6233, "text": "You can achieve up to 8x speed up if you use pandas.Categorical data type when using LGBM." }, { "code": null, "e": 6496, "s": 6324, "text": "The table shows the final scores and runtimes of both models. As you can see, the version with default categorical handling beat others both in accuracy and speed. Cheers!" }, { "code": null, "e": 6570, "s": 6496, "text": "The most common way of doing CV with LGBM is to use Sklearn CV splitters." }, { "code": null, "e": 6787, "s": 6570, "text": "I am not talking about utility functions like cross_validate or cross_val_score but splitters like KFold or StratifiedKFold with their split method. Doing CV in this way gives you more control over the whole process." }, { "code": null, "e": 6895, "s": 6787, "text": "I have talked many times about the importance of cross-validation. You can read this post for more details." }, { "code": null, "e": 7040, "s": 6895, "text": "Also, it enables you to use early stopping during cross-validation in a hassle-free manner. Here is what this looks like for the TPS March data:" }, { "code": null, "e": 7354, "s": 7040, "text": "First, create a CV splitter — we are choosing StratifiedKFold because it is a classification problem. Then, loop through each train/test sets using split. In each fold, initialize and train a new LGBM model and optionally report the score and runtime. That's it! That's how most people do CV, including on Kaggle." }, { "code": null, "e": 7517, "s": 7354, "text": "In this post, we learned pure modeling techniques with LightGBM. Next up, we will explore how to squeeze every bit of performance out of LGBM models using Optuna." } ]
Machine Learning Prediction in Real Time Using Docker and Python REST APIs with Flask | by Xavier Vasques | Towards Data Science
A quick example of a Docker container and REST APIs to perform online inference The idea of this article is to do a quick and easy build of a Docker container to perform online inference with trained machine learning models using Python APIs with Flask. Before reading this article, do not hesitate to read Why use Docker for Machine Learning, Quick Install and First Use of Docker, and Build and Run a Docker Container for your Machine Learning Model in which we learn how to use Docker to perform model training and batch inference. Batch inference is great when you have time to compute your predictions. Let’s imagine you need real time predictions. In this case, batch inference is not more suitable and we need online inference. Many applications would not work or would not be very useful without online predictions such as autonomous vehicles, fraud detection, high-frequency trading, applications based on localization data, object recognition and tracking or brain computer interfaces. Sometimes, the prediction needs to be provided in milliseconds. To learn this concept, we will implement online inferences (Linear Discriminant Analysis and Multi-layer Perceptron Neural Network models) with Docker and Flask-RESTful. To start, let’s consider the following files: Dockerfile, train.py, api.py, requirements.txt, train.csv, test.json. The train.py is a python script that ingest and normalize EEG data and train two models to classify the data. The Dockerfile will be used to build our Docker image, requirements.txt (flask, flask-restful, joblib) is for the Python dependencies and api.py is the script that will be called to perform the online inference using REST APIs. train.csv are the data used to train our models, and test.json is a file containing new EEG data that will be used with our inference models. You can find all files on GitHub. The first step in building APIs is to think about the data we want to handle, how we want to handle it and what output we want with our APIs. In our example, we will use the test.json file in which we have 1300 rows of EEG data with 160 features each (columns). We want our APIs to the following: - API 1: We will give a row number to the API which will extract for us the data from the selected row and print it. - API 2: We will give a row number to the API which will extract the selected row, inject the new data into the models and retrieve the classification prediction (Letter variable in the data) - API 3: We will ask the API to take all the data in the test.json file and instantly print us the classification score of the models. At the end, we want to access those processes by making an HTTP request. Let’s have a look at the api.py file: The first step, after importing dependencies including the open source web microframework Flask, is to set the environment variables that are written in the Dockerfile. We also need to load our Linear Discriminant Analysis and Multi-layer Perceptron Neural Network serialized models. We create our Flask application by writing app = Flask(__name__). Then, we create our three Flask routes so that we can serve HTTP traffic on that route: - http://0.0.0.0:5000/line/250: Get data from test.json and return the requested row defined by the variable Line (in this example we want to extract the data of row number 250) - http://0.0.0.0:5000/prediction/51: Returns classification prediction from both LDA and Neural Network trained models by injecting the requested data (in this example, we want to inject the data of row number 51) - http://0.0.0.0:5000/score: Return classification score for both the Neural Network and LDA inference models on all the available data (test.json). The Flask routes allows us to request what we need from the API by adding the name of our procedure (/line/<Line>, /prediction/<int:Line>, /score) to the URL (http://0.0.0.0:5000). Whatever the data we add, api.py will always return the output we request. The train.py is a python script that ingests and normalizes EEG data in a csv file (train.csv) and train two models to classify the data (using scikit-learn). The script saves two models: Linear Discriminant Analysis (clf_lda) and Neural Networks multi-layer perceptron (clf_NN): We have all to build our Docker image. To start, we need our Dockerfile with the jupyter/scipy-notebook image as our base image. We also need to set our environment variables and install joblib to allow serialization and deserialization of our trained models and flask (requirements.txt). We copy the train.csv, test.json, train.py and api.py files into the image. Then, we run train.py which will fit and serialize the machine learning models as part of our image build process. Here it is: To build this image, run the following command: docker build -t my-docker-api -f Dockerfile . We obtain the following output: Now the goal is to run our online inference meaning that each time a client issues a POST request to the /line/<Line>, /prediction/<Line>, /score endpoints, we will show the requested data (row), predict the class of the data we inject using our pre-trained models, and the score of our pre-trained models using all the available data. To launch the web server, we will run a Docker container and run the api.py script: docker run -it -p 5000:5000 my-docker-api python3 api.py The -p flag exposes port 5000 in the container to port 5000 on our host machine, -it flag allows us to see the logs from the container and we run python3 api.py in the my-api image. The output is the following: You can see that we are running on http://0.0.0.0:5000/ and we can now use our web browser or the curl command to issue a POST request to the IP address. If we type: curl http://0.0.0.0:5000/line/232 We will get row number 232 extracted from our data (test.json): Same result using the web browser: If we type the following curl command: curl http://0.0.0.0:5000/prediction/232 We will see the following output: The above output means that the LDA model classified the provided data (row 232) as letter 21 (U) while Multi-layer Perceptron Neural Network classified the data as letter 8 (H). The two models do not agree. If we type curl http://0.0.0.0:5000/score We will see the score of our models on the entire dataset: As we can read, we should trust more the Multi-layer Perceptron Neural Network with an accuracy score of 0.59 even if the score is not so high. Some work to do to improve the accuracy! I hope you can see the simplicity of containerizing your machine/deep learning applications using Docker and flask to perform online inference. This is an essential step when we want to put our models into production. Of course, it’s a simple view as we need to take into account many more aspects such as the network, security, monitoring, infrastructure, orchestration or add a database to store the data instead of using a json file.
[ { "code": null, "e": 251, "s": 171, "text": "A quick example of a Docker container and REST APIs to perform online inference" }, { "code": null, "e": 706, "s": 251, "text": "The idea of this article is to do a quick and easy build of a Docker container to perform online inference with trained machine learning models using Python APIs with Flask. Before reading this article, do not hesitate to read Why use Docker for Machine Learning, Quick Install and First Use of Docker, and Build and Run a Docker Container for your Machine Learning Model in which we learn how to use Docker to perform model training and batch inference." }, { "code": null, "e": 1231, "s": 706, "text": "Batch inference is great when you have time to compute your predictions. Let’s imagine you need real time predictions. In this case, batch inference is not more suitable and we need online inference. Many applications would not work or would not be very useful without online predictions such as autonomous vehicles, fraud detection, high-frequency trading, applications based on localization data, object recognition and tracking or brain computer interfaces. Sometimes, the prediction needs to be provided in milliseconds." }, { "code": null, "e": 1401, "s": 1231, "text": "To learn this concept, we will implement online inferences (Linear Discriminant Analysis and Multi-layer Perceptron Neural Network models) with Docker and Flask-RESTful." }, { "code": null, "e": 1517, "s": 1401, "text": "To start, let’s consider the following files: Dockerfile, train.py, api.py, requirements.txt, train.csv, test.json." }, { "code": null, "e": 1997, "s": 1517, "text": "The train.py is a python script that ingest and normalize EEG data and train two models to classify the data. The Dockerfile will be used to build our Docker image, requirements.txt (flask, flask-restful, joblib) is for the Python dependencies and api.py is the script that will be called to perform the online inference using REST APIs. train.csv are the data used to train our models, and test.json is a file containing new EEG data that will be used with our inference models." }, { "code": null, "e": 2031, "s": 1997, "text": "You can find all files on GitHub." }, { "code": null, "e": 2328, "s": 2031, "text": "The first step in building APIs is to think about the data we want to handle, how we want to handle it and what output we want with our APIs. In our example, we will use the test.json file in which we have 1300 rows of EEG data with 160 features each (columns). We want our APIs to the following:" }, { "code": null, "e": 2445, "s": 2328, "text": "- API 1: We will give a row number to the API which will extract for us the data from the selected row and print it." }, { "code": null, "e": 2637, "s": 2445, "text": "- API 2: We will give a row number to the API which will extract the selected row, inject the new data into the models and retrieve the classification prediction (Letter variable in the data)" }, { "code": null, "e": 2772, "s": 2637, "text": "- API 3: We will ask the API to take all the data in the test.json file and instantly print us the classification score of the models." }, { "code": null, "e": 2845, "s": 2772, "text": "At the end, we want to access those processes by making an HTTP request." }, { "code": null, "e": 2883, "s": 2845, "text": "Let’s have a look at the api.py file:" }, { "code": null, "e": 3321, "s": 2883, "text": "The first step, after importing dependencies including the open source web microframework Flask, is to set the environment variables that are written in the Dockerfile. We also need to load our Linear Discriminant Analysis and Multi-layer Perceptron Neural Network serialized models. We create our Flask application by writing app = Flask(__name__). Then, we create our three Flask routes so that we can serve HTTP traffic on that route:" }, { "code": null, "e": 3499, "s": 3321, "text": "- http://0.0.0.0:5000/line/250: Get data from test.json and return the requested row defined by the variable Line (in this example we want to extract the data of row number 250)" }, { "code": null, "e": 3713, "s": 3499, "text": "- http://0.0.0.0:5000/prediction/51: Returns classification prediction from both LDA and Neural Network trained models by injecting the requested data (in this example, we want to inject the data of row number 51)" }, { "code": null, "e": 3862, "s": 3713, "text": "- http://0.0.0.0:5000/score: Return classification score for both the Neural Network and LDA inference models on all the available data (test.json)." }, { "code": null, "e": 4118, "s": 3862, "text": "The Flask routes allows us to request what we need from the API by adding the name of our procedure (/line/<Line>, /prediction/<int:Line>, /score) to the URL (http://0.0.0.0:5000). Whatever the data we add, api.py will always return the output we request." }, { "code": null, "e": 4398, "s": 4118, "text": "The train.py is a python script that ingests and normalizes EEG data in a csv file (train.csv) and train two models to classify the data (using scikit-learn). The script saves two models: Linear Discriminant Analysis (clf_lda) and Neural Networks multi-layer perceptron (clf_NN):" }, { "code": null, "e": 4878, "s": 4398, "text": "We have all to build our Docker image. To start, we need our Dockerfile with the jupyter/scipy-notebook image as our base image. We also need to set our environment variables and install joblib to allow serialization and deserialization of our trained models and flask (requirements.txt). We copy the train.csv, test.json, train.py and api.py files into the image. Then, we run train.py which will fit and serialize the machine learning models as part of our image build process." }, { "code": null, "e": 4890, "s": 4878, "text": "Here it is:" }, { "code": null, "e": 4938, "s": 4890, "text": "To build this image, run the following command:" }, { "code": null, "e": 4985, "s": 4938, "text": "docker build -t my-docker-api -f Dockerfile . " }, { "code": null, "e": 5017, "s": 4985, "text": "We obtain the following output:" }, { "code": null, "e": 5437, "s": 5017, "text": "Now the goal is to run our online inference meaning that each time a client issues a POST request to the /line/<Line>, /prediction/<Line>, /score endpoints, we will show the requested data (row), predict the class of the data we inject using our pre-trained models, and the score of our pre-trained models using all the available data. To launch the web server, we will run a Docker container and run the api.py script:" }, { "code": null, "e": 5494, "s": 5437, "text": "docker run -it -p 5000:5000 my-docker-api python3 api.py" }, { "code": null, "e": 5676, "s": 5494, "text": "The -p flag exposes port 5000 in the container to port 5000 on our host machine, -it flag allows us to see the logs from the container and we run python3 api.py in the my-api image." }, { "code": null, "e": 5705, "s": 5676, "text": "The output is the following:" }, { "code": null, "e": 5859, "s": 5705, "text": "You can see that we are running on http://0.0.0.0:5000/ and we can now use our web browser or the curl command to issue a POST request to the IP address." }, { "code": null, "e": 5871, "s": 5859, "text": "If we type:" }, { "code": null, "e": 5905, "s": 5871, "text": "curl http://0.0.0.0:5000/line/232" }, { "code": null, "e": 5969, "s": 5905, "text": "We will get row number 232 extracted from our data (test.json):" }, { "code": null, "e": 6004, "s": 5969, "text": "Same result using the web browser:" }, { "code": null, "e": 6043, "s": 6004, "text": "If we type the following curl command:" }, { "code": null, "e": 6083, "s": 6043, "text": "curl http://0.0.0.0:5000/prediction/232" }, { "code": null, "e": 6117, "s": 6083, "text": "We will see the following output:" }, { "code": null, "e": 6325, "s": 6117, "text": "The above output means that the LDA model classified the provided data (row 232) as letter 21 (U) while Multi-layer Perceptron Neural Network classified the data as letter 8 (H). The two models do not agree." }, { "code": null, "e": 6336, "s": 6325, "text": "If we type" }, { "code": null, "e": 6367, "s": 6336, "text": "curl http://0.0.0.0:5000/score" }, { "code": null, "e": 6426, "s": 6367, "text": "We will see the score of our models on the entire dataset:" }, { "code": null, "e": 6611, "s": 6426, "text": "As we can read, we should trust more the Multi-layer Perceptron Neural Network with an accuracy score of 0.59 even if the score is not so high. Some work to do to improve the accuracy!" } ]
Erlang - write
This method is used to write the contents to a file. write(FileHandler,text) FileHandler − This is the handle to a file. This handle is the one that would be returned when the file:openoperation is used. FileHandler − This is the handle to a file. This handle is the one that would be returned when the file:openoperation is used. Text − The text which needs to be added to the file. Text − The text which needs to be added to the file. None -module(helloworld). -export([start/0]). start() -> {ok, Fd} = file:open("Newfile.txt", [write]), file:write(Fd,"New Line"). Whenever the above code is run, the line “New Line” will be written to the file. Note that because the mode is set to write, if there were any previous contents to the file, they will be overwritten. To append to the existing contents of the file, you need to change the mode to append as shown in the following program. -module(helloworld). -export([start/0]). start() -> {ok, Fd} = file:open("Newfile.txt", [append]), file:write(Fd,"New Line"). Print Add Notes Bookmark this page
[ { "code": null, "e": 2354, "s": 2301, "text": "This method is used to write the contents to a file." }, { "code": null, "e": 2379, "s": 2354, "text": "write(FileHandler,text)\n" }, { "code": null, "e": 2506, "s": 2379, "text": "FileHandler − This is the handle to a file. This handle is the one that would be returned when the file:openoperation is used." }, { "code": null, "e": 2633, "s": 2506, "text": "FileHandler − This is the handle to a file. This handle is the one that would be returned when the file:openoperation is used." }, { "code": null, "e": 2686, "s": 2633, "text": "Text − The text which needs to be added to the file." }, { "code": null, "e": 2739, "s": 2686, "text": "Text − The text which needs to be added to the file." }, { "code": null, "e": 2744, "s": 2739, "text": "None" }, { "code": null, "e": 2880, "s": 2744, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n {ok, Fd} = file:open(\"Newfile.txt\", [write]), \n file:write(Fd,\"New Line\")." }, { "code": null, "e": 3080, "s": 2880, "text": "Whenever the above code is run, the line “New Line” will be written to the file. Note that because the mode is set to write, if there were any previous contents to the file, they will be overwritten." }, { "code": null, "e": 3201, "s": 3080, "text": "To append to the existing contents of the file, you need to change the mode to append as shown in the following program." }, { "code": null, "e": 3338, "s": 3201, "text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n {ok, Fd} = file:open(\"Newfile.txt\", [append]), \n file:write(Fd,\"New Line\")." }, { "code": null, "e": 3345, "s": 3338, "text": " Print" }, { "code": null, "e": 3356, "s": 3345, "text": " Add Notes" } ]
How to set the font size of a Tkinter Canvas text item?
Canvas is one of the flexible widgets in tkinter which controls the widgets with its power of functions, methods, and attributes. However, tkinter canvas can be used to create text using the create_text(options) constructor. We can define the text along with other properties in the constructor. After defining the text, we can control over the text style such as font-family, font-size and font-style by using font(property). Let us have a look at the following example where we will add a new text and then resize it using the font property. #Import tkinter library from tkinter import * from tkinter import ttk #Create an instance of tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Creating a canvas canvas= Canvas(win, width= 430, height= 450) #Create a text inside canvas text= canvas.create_text(200,40,text="Hey, Developers!", font=('Helvetica','30','bold')) canvas.pack() win.mainloop() Running the above code will display a window that contains a text in the canvas. We can resize the text in the canvas by using the font(options) attribute. Now, change the font size from the property and run the code to see the reflected changes.
[ { "code": null, "e": 1489, "s": 1062, "text": "Canvas is one of the flexible widgets in tkinter which controls the widgets with its power of functions, methods, and attributes. However, tkinter canvas can be used to create text using the create_text(options) constructor. We can define the text along with other properties in the constructor. After defining the text, we can control over the text style such as font-family, font-size and font-style by using font(property)." }, { "code": null, "e": 1606, "s": 1489, "text": "Let us have a look at the following example where we will add a new text and then resize it using the font property." }, { "code": null, "e": 2003, "s": 1606, "text": "#Import tkinter library\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n#Creating a canvas\ncanvas= Canvas(win, width= 430, height= 450)\n#Create a text inside canvas\ntext= canvas.create_text(200,40,text=\"Hey, Developers!\", font=('Helvetica','30','bold'))\ncanvas.pack()\nwin.mainloop()" }, { "code": null, "e": 2159, "s": 2003, "text": "Running the above code will display a window that contains a text in the canvas. We can resize the text in the canvas by using the font(options) attribute." }, { "code": null, "e": 2250, "s": 2159, "text": "Now, change the font size from the property and run the code to see the reflected changes." } ]
Publish Python Project Documentation on Confluence/HTML using Sphinx | by Shravankumar Hiregoudar | Towards Data Science
The code documentation is essential in every project. Code documentation can be split into multiple parts. The first one is comment blocks, most helpful for programmers; These will be found through every file explaining classes, methods, parameters, possible errors. Then comes the file documentations. These are usually generated through a script that will parse a file and, based on the description in the docstrings, will create an explicit PDF. Afterwards, there should be information about the location of the code repository; additionally, there should be detailed instructions on how to run the project. In this article, We will look into the file documentation which is generated by Sphinx. This documentation generator can be used to create .pdf, .HTML or publish the technical documentation page to a Confluence instance. Confluence is a great place to create, collaborate, and organize all your work in one place. Can Be Used Company-WideAllows You to Engage Colleagues and ReadersWeb-Based, No need to download any softwareIdeal for Agile Environments Can Be Used Company-Wide Allows You to Engage Colleagues and Readers Web-Based, No need to download any software Ideal for Agile Environments Create a confluence account and create a space where you want to store the documentation Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of multiple reStructuredText sources), written by Georg Brandl. It was originally created for the new Python documentation and has excellent facilities for Python project documentation, but C/C++ is supported as well, and more languages are planned. Sphinx uses reStructuredText as its markup language, and many of its strengths come from the power and straightforwardness of reStructuredText and its parsing and translating suite, the Docutils. The steps involved in creating the documentation; GitHub code Go to the root directory of the python project. In the case of a small project go to the directory which contains all the .py filesCreate a Python 3 virtual environment. In my case, venv is the name of the virtual environment Go to the root directory of the python project. In the case of a small project go to the directory which contains all the .py files Create a Python 3 virtual environment. In my case, venv is the name of the virtual environment Open the cmd; shift + right click and open command window here virtualenv -p python3 venv 3. Activate the virtual environment. cd venv/Scriptsactivate.bat 4. Install all the project requirements pip install -r requirements.txtORpip install Sphinxpip install rinohtype# The recommended method of installation is using pip for confluencepip install sphinxcontrib-confluencebuilder Sphinx and Rinohtype are already inside the requirements.txt file. 5. Create a docs directory and cd into this directory. This is where all the files of documentation will be present. mkdir docscd docs 6. Setup Sphinx sphinx-quickstart Docstring format for Sphinx documentation; 7. Open source/conf.py Configure the path to the root directory import osimport syssys.path.insert(0, os.path.abspath('../..')) The path should point to the root directory of the project and looking at the project structure, from conf.py we should reach the root by going up two parent directories. Add these extensions in the conf.py extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', 'sphinxcontrib.confluencebuilder']# 'sphinxcontrib.confluencebuilder' is for confluence Add latex elements in the conf.py latex_elements = {# The paper size ('letterpaper' or 'a4paper'). 'papersize': 'letterpaper',# The font size ('10pt', '11pt' or '12pt'). 'pointsize': '10pt',# Additional stuff for the LaTeX preamble. 'preamble': '',# Latex figure (float) alignment 'figure_align': 'htbp',} Include a series of publish-related settings to the configuration file: (*optional, only if you want to publish in confluence) confluence_publish = Trueconfluence_space_name = 'TEST'# (for confluence cloud)confluence_server_url = 'https://example.atlassian.net/wiki/'confluence_server_user = 'myawesomeuser@example.com'confluence_server_pass = 'myapikey'# (or for confluence server)confluence_server_url = 'https://intranet-wiki.example.com/'confluence_server_user = 'myawesomeuser'confluence_server_pass = 'mypassword' For example: confluence_publish = Trueconfluence_space_name = 'SPEC'# (for confluence cloud)confluence_server_url = 'https://spectrra.atlassian.net/wiki/'confluence_server_user = 'email@gmail.com'confluence_server_pass = 'jhfgjsdfjhasdjfg' How to get the confluence_server_pass for your project: Get API Key For detailed installation: Atlassian Confluence Builder for Sphinx 8. Open the index.rst and change the content to the following. (Click the index.rst link for full content) Documentation for the Code**************************.. toctree:: :maxdepth: 2 :caption: Contents:codename1===================.. automodule:: codename1 :members:codename2=====================.. automodule:: codename2 :members:# In case of many modules;main===================.. automodule:: app :members:controller=====================.. automodule:: main.controller :members:models=================.. automodule:: main.models :members: 9. Create the documentation files. Type the commands in the docs directory Create HTML make html Building the pdf file would fail if your Python version is ≥3.7.0 (Github issue reference) Snapshot of the HTML page; This would produce the HTML file in docs/build/html/index.html Publish on confluence make confluence NOTE: Run make clean before make confluence, If the confluence fails to load. IMP: You can export the confluence page as PDF Snapshot of the confluence page; Once everything is setup; If you make any changes in the documentation of the code, Then open cmd and run the following; To learn more please refer to the following links; Writing docstrings: https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html and https://pythonhosted.org/an_example_pypi_project/sphinx.html Sphinx: https://www.sphinx-doc.org/en/master/index.html Atlassian Confluence Builder for Sphinx: https://sphinxcontrib-confluencebuilder.readthedocs.io/en/latest/index.html Link to the GitHub repo: https://github.com/Shravankumarhiregoudar/sphinxDocumentation Thanks for your time. I hope this article helped you.
[ { "code": null, "e": 783, "s": 172, "text": "The code documentation is essential in every project. Code documentation can be split into multiple parts. The first one is comment blocks, most helpful for programmers; These will be found through every file explaining classes, methods, parameters, possible errors. Then comes the file documentations. These are usually generated through a script that will parse a file and, based on the description in the docstrings, will create an explicit PDF. Afterwards, there should be information about the location of the code repository; additionally, there should be detailed instructions on how to run the project." }, { "code": null, "e": 1004, "s": 783, "text": "In this article, We will look into the file documentation which is generated by Sphinx. This documentation generator can be used to create .pdf, .HTML or publish the technical documentation page to a Confluence instance." }, { "code": null, "e": 1097, "s": 1004, "text": "Confluence is a great place to create, collaborate, and organize all your work in one place." }, { "code": null, "e": 1236, "s": 1097, "text": "Can Be Used Company-WideAllows You to Engage Colleagues and ReadersWeb-Based, No need to download any softwareIdeal for Agile Environments" }, { "code": null, "e": 1261, "s": 1236, "text": "Can Be Used Company-Wide" }, { "code": null, "e": 1305, "s": 1261, "text": "Allows You to Engage Colleagues and Readers" }, { "code": null, "e": 1349, "s": 1305, "text": "Web-Based, No need to download any software" }, { "code": null, "e": 1378, "s": 1349, "text": "Ideal for Agile Environments" }, { "code": null, "e": 1467, "s": 1378, "text": "Create a confluence account and create a space where you want to store the documentation" }, { "code": null, "e": 1854, "s": 1467, "text": "Sphinx is a tool that makes it easy to create intelligent and beautiful documentation for Python projects (or other documents consisting of multiple reStructuredText sources), written by Georg Brandl. It was originally created for the new Python documentation and has excellent facilities for Python project documentation, but C/C++ is supported as well, and more languages are planned." }, { "code": null, "e": 2050, "s": 1854, "text": "Sphinx uses reStructuredText as its markup language, and many of its strengths come from the power and straightforwardness of reStructuredText and its parsing and translating suite, the Docutils." }, { "code": null, "e": 2100, "s": 2050, "text": "The steps involved in creating the documentation;" }, { "code": null, "e": 2112, "s": 2100, "text": "GitHub code" }, { "code": null, "e": 2338, "s": 2112, "text": "Go to the root directory of the python project. In the case of a small project go to the directory which contains all the .py filesCreate a Python 3 virtual environment. In my case, venv is the name of the virtual environment" }, { "code": null, "e": 2470, "s": 2338, "text": "Go to the root directory of the python project. In the case of a small project go to the directory which contains all the .py files" }, { "code": null, "e": 2565, "s": 2470, "text": "Create a Python 3 virtual environment. In my case, venv is the name of the virtual environment" }, { "code": null, "e": 2628, "s": 2565, "text": "Open the cmd; shift + right click and open command window here" }, { "code": null, "e": 2655, "s": 2628, "text": "virtualenv -p python3 venv" }, { "code": null, "e": 2692, "s": 2655, "text": "3. Activate the virtual environment." }, { "code": null, "e": 2720, "s": 2692, "text": "cd venv/Scriptsactivate.bat" }, { "code": null, "e": 2760, "s": 2720, "text": "4. Install all the project requirements" }, { "code": null, "e": 2944, "s": 2760, "text": "pip install -r requirements.txtORpip install Sphinxpip install rinohtype# The recommended method of installation is using pip for confluencepip install sphinxcontrib-confluencebuilder" }, { "code": null, "e": 3011, "s": 2944, "text": "Sphinx and Rinohtype are already inside the requirements.txt file." }, { "code": null, "e": 3128, "s": 3011, "text": "5. Create a docs directory and cd into this directory. This is where all the files of documentation will be present." }, { "code": null, "e": 3146, "s": 3128, "text": "mkdir docscd docs" }, { "code": null, "e": 3162, "s": 3146, "text": "6. Setup Sphinx" }, { "code": null, "e": 3180, "s": 3162, "text": "sphinx-quickstart" }, { "code": null, "e": 3223, "s": 3180, "text": "Docstring format for Sphinx documentation;" }, { "code": null, "e": 3246, "s": 3223, "text": "7. Open source/conf.py" }, { "code": null, "e": 3287, "s": 3246, "text": "Configure the path to the root directory" }, { "code": null, "e": 3351, "s": 3287, "text": "import osimport syssys.path.insert(0, os.path.abspath('../..'))" }, { "code": null, "e": 3522, "s": 3351, "text": "The path should point to the root directory of the project and looking at the project structure, from conf.py we should reach the root by going up two parent directories." }, { "code": null, "e": 3558, "s": 3522, "text": "Add these extensions in the conf.py" }, { "code": null, "e": 3799, "s": 3558, "text": "extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', 'sphinxcontrib.confluencebuilder']# 'sphinxcontrib.confluencebuilder' is for confluence" }, { "code": null, "e": 3833, "s": 3799, "text": "Add latex elements in the conf.py" }, { "code": null, "e": 4117, "s": 3833, "text": "latex_elements = {# The paper size ('letterpaper' or 'a4paper'). 'papersize': 'letterpaper',# The font size ('10pt', '11pt' or '12pt'). 'pointsize': '10pt',# Additional stuff for the LaTeX preamble. 'preamble': '',# Latex figure (float) alignment 'figure_align': 'htbp',}" }, { "code": null, "e": 4244, "s": 4117, "text": "Include a series of publish-related settings to the configuration file: (*optional, only if you want to publish in confluence)" }, { "code": null, "e": 4637, "s": 4244, "text": "confluence_publish = Trueconfluence_space_name = 'TEST'# (for confluence cloud)confluence_server_url = 'https://example.atlassian.net/wiki/'confluence_server_user = 'myawesomeuser@example.com'confluence_server_pass = 'myapikey'# (or for confluence server)confluence_server_url = 'https://intranet-wiki.example.com/'confluence_server_user = 'myawesomeuser'confluence_server_pass = 'mypassword'" }, { "code": null, "e": 4650, "s": 4637, "text": "For example:" }, { "code": null, "e": 4877, "s": 4650, "text": "confluence_publish = Trueconfluence_space_name = 'SPEC'# (for confluence cloud)confluence_server_url = 'https://spectrra.atlassian.net/wiki/'confluence_server_user = 'email@gmail.com'confluence_server_pass = 'jhfgjsdfjhasdjfg'" }, { "code": null, "e": 4945, "s": 4877, "text": "How to get the confluence_server_pass for your project: Get API Key" }, { "code": null, "e": 5012, "s": 4945, "text": "For detailed installation: Atlassian Confluence Builder for Sphinx" }, { "code": null, "e": 5119, "s": 5012, "text": "8. Open the index.rst and change the content to the following. (Click the index.rst link for full content)" }, { "code": null, "e": 5569, "s": 5119, "text": "Documentation for the Code**************************.. toctree:: :maxdepth: 2 :caption: Contents:codename1===================.. automodule:: codename1 :members:codename2=====================.. automodule:: codename2 :members:# In case of many modules;main===================.. automodule:: app :members:controller=====================.. automodule:: main.controller :members:models=================.. automodule:: main.models :members:" }, { "code": null, "e": 5604, "s": 5569, "text": "9. Create the documentation files." }, { "code": null, "e": 5644, "s": 5604, "text": "Type the commands in the docs directory" }, { "code": null, "e": 5656, "s": 5644, "text": "Create HTML" }, { "code": null, "e": 5666, "s": 5656, "text": "make html" }, { "code": null, "e": 5757, "s": 5666, "text": "Building the pdf file would fail if your Python version is ≥3.7.0 (Github issue reference)" }, { "code": null, "e": 5784, "s": 5757, "text": "Snapshot of the HTML page;" }, { "code": null, "e": 5847, "s": 5784, "text": "This would produce the HTML file in docs/build/html/index.html" }, { "code": null, "e": 5869, "s": 5847, "text": "Publish on confluence" }, { "code": null, "e": 5885, "s": 5869, "text": "make confluence" }, { "code": null, "e": 5963, "s": 5885, "text": "NOTE: Run make clean before make confluence, If the confluence fails to load." }, { "code": null, "e": 6010, "s": 5963, "text": "IMP: You can export the confluence page as PDF" }, { "code": null, "e": 6043, "s": 6010, "text": "Snapshot of the confluence page;" }, { "code": null, "e": 6164, "s": 6043, "text": "Once everything is setup; If you make any changes in the documentation of the code, Then open cmd and run the following;" }, { "code": null, "e": 6215, "s": 6164, "text": "To learn more please refer to the following links;" }, { "code": null, "e": 6369, "s": 6215, "text": "Writing docstrings: https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html and https://pythonhosted.org/an_example_pypi_project/sphinx.html" }, { "code": null, "e": 6425, "s": 6369, "text": "Sphinx: https://www.sphinx-doc.org/en/master/index.html" }, { "code": null, "e": 6542, "s": 6425, "text": "Atlassian Confluence Builder for Sphinx: https://sphinxcontrib-confluencebuilder.readthedocs.io/en/latest/index.html" }, { "code": null, "e": 6629, "s": 6542, "text": "Link to the GitHub repo: https://github.com/Shravankumarhiregoudar/sphinxDocumentation" } ]
How to operate callback-based fs.readFile() method with promises in Node.js ?
18 Jul, 2020 The fs.readFile() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.readFile() method is based on callback. Using callback method leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way. Syntax: fs.readFile(path, options) Note: Callback not required since we operate the method with promises. Parameters: This method accept two parameters as mentioned above and described below: path: It is a String, Buffer or URL that specifies the path to the file whose contents we try to read. options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.encoding: It is a string that specifies the encoding technique, default is null.flag: It is a string that specifies the file system flags. Its default value is ‘r’. encoding: It is a string that specifies the encoding technique, default is null. flag: It is a string that specifies the file system flags. Its default value is ‘r’. Approach: The fs.readFile() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method. Example 1: Filename: index.js // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to// promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./testFile.txt')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);}); Implementing the same functionality using async-await. // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to// promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)} fetchFile('./testFile.txt') // If promise get rejected.catch(err => { console.log(`Error Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);}); Run the index.js file using the following command: node index.js Output: Example 2: If given path to the file does not exist.Filename: index.js // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./false/path.txt')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`\nError occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);}) Implementing the same functionality using async-await. // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)} fetchFile('./false/path') // If promise get rejected.catch(err => { console.log(`\nError Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);}); Run the index.js file using the following command: node index.js Output: Explanation: The fs.readFile() method reads the contents of the file and hence it expected a path to the file that exist. Since the given path to the file does not exist, an error occurs with error code ‘ENOENT’ and error number ‘-4058’. The ‘ENOENT’ error occurs when a specified pathname does not exist. Example 3: When given path is path to a folder not file.Filename: index.js // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./testFolder')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`\nError occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);}); Implementing the same functionality using async-await. // Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\nContents of the file :\n${contents}`)} fetchFile('./testFolder') // If promise get rejected.catch(err => { console.log(`\nError Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);}); Run the index.js file using the following command: node index.js Output: Explanation: The fs.readFile() method reads the contents of the file and hence it expected path to a file. Since the given path is a path to a folder, an error occurs with error code ‘EISDIR’ and error number ‘-4068’. The ‘EISDIR’ error occurs when an operation expected a file, but the pathname of directory is given. Node.js-fs-module Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function Installation of Node.js on Windows JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2020" }, { "code": null, "e": 317, "s": 28, "text": "The fs.readFile() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data." }, { "code": null, "e": 621, "s": 317, "text": "The fs.readFile() method is based on callback. Using callback method leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way." }, { "code": null, "e": 629, "s": 621, "text": "Syntax:" }, { "code": null, "e": 656, "s": 629, "text": "fs.readFile(path, options)" }, { "code": null, "e": 727, "s": 656, "text": "Note: Callback not required since we operate the method with promises." }, { "code": null, "e": 813, "s": 727, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 916, "s": 813, "text": "path: It is a String, Buffer or URL that specifies the path to the file whose contents we try to read." }, { "code": null, "e": 1208, "s": 916, "text": "options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.encoding: It is a string that specifies the encoding technique, default is null.flag: It is a string that specifies the file system flags. Its default value is ‘r’." }, { "code": null, "e": 1289, "s": 1208, "text": "encoding: It is a string that specifies the encoding technique, default is null." }, { "code": null, "e": 1374, "s": 1289, "text": "flag: It is a string that specifies the file system flags. Its default value is ‘r’." }, { "code": null, "e": 1565, "s": 1374, "text": "Approach: The fs.readFile() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method." }, { "code": null, "e": 1595, "s": 1565, "text": "Example 1: Filename: index.js" }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to// promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./testFile.txt')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`Error occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);});", "e": 2206, "s": 1595, "text": null }, { "code": null, "e": 2261, "s": 2206, "text": "Implementing the same functionality using async-await." }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to// promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)} fetchFile('./testFile.txt') // If promise get rejected.catch(err => { console.log(`Error Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);});", "e": 2900, "s": 2261, "text": null }, { "code": null, "e": 2951, "s": 2900, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 2965, "s": 2951, "text": "node index.js" }, { "code": null, "e": 2973, "s": 2965, "text": "Output:" }, { "code": null, "e": 3044, "s": 2973, "text": "Example 2: If given path to the file does not exist.Filename: index.js" }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./false/path.txt')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`\\nError occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);})", "e": 3657, "s": 3044, "text": null }, { "code": null, "e": 3712, "s": 3657, "text": "Implementing the same functionality using async-await." }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)} fetchFile('./false/path') // If promise get rejected.catch(err => { console.log(`\\nError Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);});", "e": 4350, "s": 3712, "text": null }, { "code": null, "e": 4401, "s": 4350, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 4415, "s": 4401, "text": "node index.js" }, { "code": null, "e": 4423, "s": 4415, "text": "Output:" }, { "code": null, "e": 4729, "s": 4423, "text": "Explanation: The fs.readFile() method reads the contents of the file and hence it expected a path to the file that exist. Since the given path to the file does not exist, an error occurs with error code ‘ENOENT’ and error number ‘-4058’. The ‘ENOENT’ error occurs when a specified pathname does not exist." }, { "code": null, "e": 4804, "s": 4729, "text": "Example 3: When given path is path to a folder not file.Filename: index.js" }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) // The readFileContent() method reads the file// and returns buffer form of the data readFileContent('./testFolder')// If promise resolved and datas are read .then(buff => { const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)}) // If promise get rejected.catch(err => { console.log(`\\nError occurs, Error code -> ${err.code}, Error No -> ${err.errno}`);});", "e": 5414, "s": 4804, "text": null }, { "code": null, "e": 5469, "s": 5414, "text": "Implementing the same functionality using async-await." }, { "code": "// Importing File System and Utilities moduleconst fs = require('fs')const util = require('util') // Convert callback based methods to // promise based methodsconst readFileContent = util.promisify(fs.readFile) const fetchFile = async (path) => { // The readFileContent() method reads the file // and returns buffer form of the data const buff = await readFileContent(path) const contents = buff.toString() console.log(`\\nContents of the file :\\n${contents}`)} fetchFile('./testFolder') // If promise get rejected.catch(err => { console.log(`\\nError Occurs, Error code -> ${err.code}, Error NO -> ${err.errno}`);});", "e": 6107, "s": 5469, "text": null }, { "code": null, "e": 6158, "s": 6107, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 6172, "s": 6158, "text": "node index.js" }, { "code": null, "e": 6180, "s": 6172, "text": "Output:" }, { "code": null, "e": 6499, "s": 6180, "text": "Explanation: The fs.readFile() method reads the contents of the file and hence it expected path to a file. Since the given path is a path to a folder, an error occurs with error code ‘EISDIR’ and error number ‘-4068’. The ‘EISDIR’ error occurs when an operation expected a file, but the pathname of directory is given." }, { "code": null, "e": 6517, "s": 6499, "text": "Node.js-fs-module" }, { "code": null, "e": 6530, "s": 6517, "text": "Node.js-Misc" }, { "code": null, "e": 6538, "s": 6530, "text": "Node.js" }, { "code": null, "e": 6555, "s": 6538, "text": "Web Technologies" }, { "code": null, "e": 6653, "s": 6555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6710, "s": 6653, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 6764, "s": 6710, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 6804, "s": 6764, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 6839, "s": 6804, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 6871, "s": 6839, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 6933, "s": 6871, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6994, "s": 6933, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7044, "s": 6994, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7087, "s": 7044, "text": "How to fetch data from an API in ReactJS ?" } ]
Sums of ASCII values of each word in a sentence
22 Jun, 2022 We are given a sentence of English language(can also contain digits), we need to compute and print the sum of ASCII values of characters of each word in that sentence.Examples: Input : GeeksforGeeks, a computer science portal for geeks Output : Sentence representation as sum of ASCII each character in a word: 1361 97 879 730 658 327 527 Total sum -> 4579 Here, [GeeksforGeeks, ] -> 1361, [a] -> 97, [computer] -> 879, [science] -> 730 [portal] -> 658, [for] -> 327, [geeks] -> 527 Input : I am a geek Output : Sum of ASCII values: 73 206 97 412 Total sum -> 788 Approach: Iterate over the length of the string and keep converting the characters to their ASCIIKeep adding up the values till the end of sentence.When we come across a space character, we store the sum calculated for that word and set the sum equal to zero again.Later, we print elements Iterate over the length of the string and keep converting the characters to their ASCII Keep adding up the values till the end of sentence. When we come across a space character, we store the sum calculated for that word and set the sum equal to zero again. Later, we print elements C++ Java Python 3 C# Javascript // C++ implementation for representing// each word in a sentence as sum of// ASCII values of each word#include <iostream>#include <string>#include <vector>using namespace std; // Function to compute the sum of ASCII values of each// word separated by a space and return the total sum// of the ASCII values, excluding the space.long long int ASCIIWordSum(string str, vector<long long int>& sumArr){ int l = str.length(); int sum = 0; long long int bigSum = 0L; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr.push_back(sum); sum = 0; } else // Implicit type casting sum += str[i]; } // Storing the value of last word sumArr.push_back(sum); bigSum += sum; return bigSum;}// Driver functionint main(){ string str = "GeeksforGeeks a computer science " "portal for Geeks"; vector<long long int> sumArr; // Calling function long long int sum = ASCIIWordSum(str, sumArr); cout << "Sum of ASCII values:" << std::endl; for (auto x : sumArr) cout << x << " "; cout << endl << "Total sum -> " << sum; return 0;} // Java program for representing// each word in a sentence as sum of// ASCII values of each wordimport java.util.*;import java.lang.*; class Rextester { // Function to compute the sum of ASCII values of // each word separated by a space and return the // total sum of the ASCII values, excluding the // space. static long ASCIIWordSum(String str, long sumArr[]) { int l = str.length(); int pos = 0; long sum = 0; long bigSum = 0; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str.charAt(i) == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str.charAt(i); } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function public static void main(String args[]) { String str = "GeeksforGeeks, a computer science portal for geeks"; // Counting the number of words in the input sentence int ctr = 0; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == ' ') ctr++; long sumArr[] = new long[ctr + 1]; // Calling function long sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of the words in the // sentence System.out.println("Sum of ASCII values:"); for (int i = 0; i <= ctr; i++) System.out.print(sumArr[i] + " "); System.out.println(); System.out.print("Total sum -> " + sum); }} # Python 3 implementation for representing# each word in a sentence as sum of# ASCII values of each word # Function to compute the sum of ASCII# values of each word separated by a space# and return the total sum of the ASCII# values, excluding the space.def ASCIIWordSum(str, sumArr): l = len(str) sum = 0 bigSum = 0 for i in range(l): # Separate each word by a space # and store values corresponding # to each word if (str[i] == ' '): bigSum += sum sumArr.append(sum) sum = 0 else: # Implicit type casting sum += ord(str[i]) # Storing the value of last word sumArr.append(sum) bigSum += sum return bigSum # Driver Codeif __name__ == "__main__": str = "GeeksforGeeks a computer science portal for Geeks" sumArr = [] # Calling function sum = ASCIIWordSum(str, sumArr) print("Sum of ASCII values:" ) for x in sumArr: print(x, end = " ") print() print("Total sum -> ", sum) # This code is contributed by ita_c // C# program for representing each// word in a sentence as sum of// ASCII values of each wordusing System; class GFG { // Function to compute the sum of ASCII // values of each word separated by a // space and return the total sum of // the ASCII values, excluding the space. static long ASCIIWordSum(String str, long []sumArr) { int l = str.Length; int pos = 0; long sum = 0; long bigSum = 0; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str[i]; } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function public static void Main() { String str = "GeeksforGeeks, a computer " + "science portal for geeks"; // Counting the number of words // in the input sentence int ctr = 0; for (int i = 0; i < str.Length; i++) if (str[i] == ' ') ctr++; long []sumArr = new long[ctr + 1]; // Calling function long sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of // the words in the sentence Console.WriteLine("Sum of ASCII values:"); for (int i = 0; i <= ctr; i++) Console.Write(sumArr[i] + " "); Console.WriteLine(); Console.Write("Total sum -> " + sum); }} // This code is contributed by nitin mittal <script> // Javascript program for representing// each word in a sentence as sum of// ASCII values of each word // Function to compute the sum of ASCII values of // each word separated by a space and return the // total sum of the ASCII values, excluding the // space. function ASCIIWordSum(str,sumArr) { let l = str.length; let pos = 0; let sum = 0; let bigSum = 0; for (let i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str[i].charCodeAt(0); } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function let str = "GeeksforGeeks, a computer science portal for geeks"; // Counting the number of words // in the input sentence let ctr = 0; for (let i = 0; i < str.length; i++) if (str[i] == ' ') ctr++; let sumArr = new Array(ctr + 1); // Calling function let sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of the words in the // sentence document.write("Sum of ASCII values:<br>"); for (let i = 0; i <= ctr; i++) document.write(sumArr[i] + " "); document.write("<br>"); document.write("Total sum -> " + sum); // This code is contributed by avanitrachhadiya2155 </script> Output: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Sum of ASCII values: 1317 97 879 730 658 327 495 Total sum -> 4503 Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string that is number of characters in the sentence. Auxiliary Space: O(W), as we are using extra space for the sumArr. Where W is the number of words in the sentence. https://youtu.be/B3dghSG2R -Y nitin mittal ukasp avanitrachhadiya2155 rohitsingh07052 cpp-vector Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Check whether two strings are anagram of each other Convert string to char array in C++ Reverse words in a given string
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 207, "s": 28, "text": "We are given a sentence of English language(can also contain digits), we need to compute and print the sum of ASCII values of characters of each word in that sentence.Examples: " }, { "code": null, "e": 641, "s": 207, "text": "Input : GeeksforGeeks, a computer science portal for geeks\nOutput : Sentence representation as sum of ASCII each character in a word:\n 1361 97 879 730 658 327 527 \n Total sum -> 4579\nHere, [GeeksforGeeks, ] -> 1361, [a] -> 97, [computer] -> 879, [science] -> 730\n [portal] -> 658, [for] -> 327, [geeks] -> 527 \n\nInput : I am a geek\nOutput : Sum of ASCII values:\n 73 206 97 412 \n Total sum -> 788" }, { "code": null, "e": 655, "s": 643, "text": "Approach: " }, { "code": null, "e": 935, "s": 655, "text": "Iterate over the length of the string and keep converting the characters to their ASCIIKeep adding up the values till the end of sentence.When we come across a space character, we store the sum calculated for that word and set the sum equal to zero again.Later, we print elements" }, { "code": null, "e": 1023, "s": 935, "text": "Iterate over the length of the string and keep converting the characters to their ASCII" }, { "code": null, "e": 1075, "s": 1023, "text": "Keep adding up the values till the end of sentence." }, { "code": null, "e": 1193, "s": 1075, "text": "When we come across a space character, we store the sum calculated for that word and set the sum equal to zero again." }, { "code": null, "e": 1218, "s": 1193, "text": "Later, we print elements" }, { "code": null, "e": 1224, "s": 1220, "text": "C++" }, { "code": null, "e": 1229, "s": 1224, "text": "Java" }, { "code": null, "e": 1238, "s": 1229, "text": "Python 3" }, { "code": null, "e": 1241, "s": 1238, "text": "C#" }, { "code": null, "e": 1252, "s": 1241, "text": "Javascript" }, { "code": "// C++ implementation for representing// each word in a sentence as sum of// ASCII values of each word#include <iostream>#include <string>#include <vector>using namespace std; // Function to compute the sum of ASCII values of each// word separated by a space and return the total sum// of the ASCII values, excluding the space.long long int ASCIIWordSum(string str, vector<long long int>& sumArr){ int l = str.length(); int sum = 0; long long int bigSum = 0L; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr.push_back(sum); sum = 0; } else // Implicit type casting sum += str[i]; } // Storing the value of last word sumArr.push_back(sum); bigSum += sum; return bigSum;}// Driver functionint main(){ string str = \"GeeksforGeeks a computer science \" \"portal for Geeks\"; vector<long long int> sumArr; // Calling function long long int sum = ASCIIWordSum(str, sumArr); cout << \"Sum of ASCII values:\" << std::endl; for (auto x : sumArr) cout << x << \" \"; cout << endl << \"Total sum -> \" << sum; return 0;}", "e": 2573, "s": 1252, "text": null }, { "code": "// Java program for representing// each word in a sentence as sum of// ASCII values of each wordimport java.util.*;import java.lang.*; class Rextester { // Function to compute the sum of ASCII values of // each word separated by a space and return the // total sum of the ASCII values, excluding the // space. static long ASCIIWordSum(String str, long sumArr[]) { int l = str.length(); int pos = 0; long sum = 0; long bigSum = 0; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str.charAt(i) == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str.charAt(i); } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function public static void main(String args[]) { String str = \"GeeksforGeeks, a computer science portal for geeks\"; // Counting the number of words in the input sentence int ctr = 0; for (int i = 0; i < str.length(); i++) if (str.charAt(i) == ' ') ctr++; long sumArr[] = new long[ctr + 1]; // Calling function long sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of the words in the // sentence System.out.println(\"Sum of ASCII values:\"); for (int i = 0; i <= ctr; i++) System.out.print(sumArr[i] + \" \"); System.out.println(); System.out.print(\"Total sum -> \" + sum); }}", "e": 4324, "s": 2573, "text": null }, { "code": "# Python 3 implementation for representing# each word in a sentence as sum of# ASCII values of each word # Function to compute the sum of ASCII# values of each word separated by a space# and return the total sum of the ASCII# values, excluding the space.def ASCIIWordSum(str, sumArr): l = len(str) sum = 0 bigSum = 0 for i in range(l): # Separate each word by a space # and store values corresponding # to each word if (str[i] == ' '): bigSum += sum sumArr.append(sum) sum = 0 else: # Implicit type casting sum += ord(str[i]) # Storing the value of last word sumArr.append(sum) bigSum += sum return bigSum # Driver Codeif __name__ == \"__main__\": str = \"GeeksforGeeks a computer science portal for Geeks\" sumArr = [] # Calling function sum = ASCIIWordSum(str, sumArr) print(\"Sum of ASCII values:\" ) for x in sumArr: print(x, end = \" \") print() print(\"Total sum -> \", sum) # This code is contributed by ita_c", "e": 5410, "s": 4324, "text": null }, { "code": "// C# program for representing each// word in a sentence as sum of// ASCII values of each wordusing System; class GFG { // Function to compute the sum of ASCII // values of each word separated by a // space and return the total sum of // the ASCII values, excluding the space. static long ASCIIWordSum(String str, long []sumArr) { int l = str.Length; int pos = 0; long sum = 0; long bigSum = 0; for (int i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str[i]; } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function public static void Main() { String str = \"GeeksforGeeks, a computer \" + \"science portal for geeks\"; // Counting the number of words // in the input sentence int ctr = 0; for (int i = 0; i < str.Length; i++) if (str[i] == ' ') ctr++; long []sumArr = new long[ctr + 1]; // Calling function long sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of // the words in the sentence Console.WriteLine(\"Sum of ASCII values:\"); for (int i = 0; i <= ctr; i++) Console.Write(sumArr[i] + \" \"); Console.WriteLine(); Console.Write(\"Total sum -> \" + sum); }} // This code is contributed by nitin mittal", "e": 7180, "s": 5410, "text": null }, { "code": "<script> // Javascript program for representing// each word in a sentence as sum of// ASCII values of each word // Function to compute the sum of ASCII values of // each word separated by a space and return the // total sum of the ASCII values, excluding the // space. function ASCIIWordSum(str,sumArr) { let l = str.length; let pos = 0; let sum = 0; let bigSum = 0; for (let i = 0; i < l; i++) { // Separate each word by // a space and store values // corresponding to each word if (str[i] == ' ') { bigSum += sum; sumArr[pos++] = sum; sum = 0; } else // Implicit type casting sum += str[i].charCodeAt(0); } // Storing the sum of last word sumArr[pos] = sum; bigSum += sum; return bigSum; } // Driver function let str = \"GeeksforGeeks, a computer science portal for geeks\"; // Counting the number of words // in the input sentence let ctr = 0; for (let i = 0; i < str.length; i++) if (str[i] == ' ') ctr++; let sumArr = new Array(ctr + 1); // Calling function let sum = ASCIIWordSum(str, sumArr); // Printing equivalent sum of the words in the // sentence document.write(\"Sum of ASCII values:<br>\"); for (let i = 0; i <= ctr; i++) document.write(sumArr[i] + \" \"); document.write(\"<br>\"); document.write(\"Total sum -> \" + sum); // This code is contributed by avanitrachhadiya2155 </script>", "e": 8923, "s": 7180, "text": null }, { "code": null, "e": 8933, "s": 8923, "text": "Output: " }, { "code": null, "e": 8942, "s": 8933, "text": "Chapters" }, { "code": null, "e": 8969, "s": 8942, "text": "descriptions off, selected" }, { "code": null, "e": 9019, "s": 8969, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 9042, "s": 9019, "text": "captions off, selected" }, { "code": null, "e": 9050, "s": 9042, "text": "English" }, { "code": null, "e": 9074, "s": 9050, "text": "This is a modal window." }, { "code": null, "e": 9143, "s": 9074, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 9165, "s": 9143, "text": "End of dialog window." }, { "code": null, "e": 9233, "s": 9165, "text": "Sum of ASCII values:\n1317 97 879 730 658 327 495 \nTotal sum -> 4503" }, { "code": null, "e": 9382, "s": 9233, "text": "Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string that is number of characters in the sentence." }, { "code": null, "e": 9497, "s": 9382, "text": "Auxiliary Space: O(W), as we are using extra space for the sumArr. Where W is the number of words in the sentence." }, { "code": null, "e": 9524, "s": 9497, "text": "https://youtu.be/B3dghSG2R" }, { "code": null, "e": 9528, "s": 9524, "text": "-Y " }, { "code": null, "e": 9541, "s": 9528, "text": "nitin mittal" }, { "code": null, "e": 9547, "s": 9541, "text": "ukasp" }, { "code": null, "e": 9568, "s": 9547, "text": "avanitrachhadiya2155" }, { "code": null, "e": 9584, "s": 9568, "text": "rohitsingh07052" }, { "code": null, "e": 9595, "s": 9584, "text": "cpp-vector" }, { "code": null, "e": 9603, "s": 9595, "text": "Strings" }, { "code": null, "e": 9611, "s": 9603, "text": "Strings" }, { "code": null, "e": 9709, "s": 9611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9754, "s": 9709, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 9811, "s": 9754, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 9886, "s": 9811, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 9922, "s": 9886, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 9960, "s": 9922, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 10021, "s": 9960, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 10066, "s": 10021, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 10118, "s": 10066, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 10154, "s": 10118, "text": "Convert string to char array in C++" } ]
Types of Three-address codes
10 Sep, 2021 Three-address code is a sequence of statements of the general form A := B op C, where A, B, C are either programmer defined names, constants or compiler-generated temporary names; op stands for an operation which is applied on A, B.In simple words, a code having at most three addresses in a line is called three address codes. Example: (a+b)*(a+b+c) The three address code for above expression is: t1=a+b t2=t1+c t3=t1*t2 In compiler design the most popular intermediate code representation is Three-address code. It is globally accepted and is most widely used. There are a lot of three-address statements. All the complex three-address statements are generally a combination of simpler three-address statements. These statements come under following seven categories and can be called as building block for three-address statements- Now, by using the above statements let us convert some popular high level constructs in Three-address code. 1. While Statement – while E do S Three-address Code: L:if(E==0) goto L1 S goto L L1:end 2. For Statement – for(E1;E2;E3) do S Three-address Code: E1 L:if(E2) goto L1 goto L2 L1:S E3 goto L L2:end 3. Switch Statement – switch(E){ case 1: S1 break; case 2: S2 break; default: S3 } Three-address Code: t=E goto test L1:S1 goto Last L2:S2 goto Last L3:S3 goto Last test: if(E==1) goto L1 if(E==2) goto L2 goto L3 Last:end Thus, we can see by using the seven statements we can replicate statements from higher level language into address codes. pranavgajera1998 Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Type Checking in Compiler Design Data flow analysis in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Runtime Environments in Compiler Design 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": "\n10 Sep, 2021" }, { "code": null, "e": 381, "s": 52, "text": "Three-address code is a sequence of statements of the general form A := B op C, where A, B, C are either programmer defined names, constants or compiler-generated temporary names; op stands for an operation which is applied on A, B.In simple words, a code having at most three addresses in a line is called three address codes. " }, { "code": null, "e": 392, "s": 381, "text": "Example: " }, { "code": null, "e": 407, "s": 392, "text": "(a+b)*(a+b+c) " }, { "code": null, "e": 457, "s": 407, "text": "The three address code for above expression is: " }, { "code": null, "e": 481, "s": 457, "text": "t1=a+b\nt2=t1+c\nt3=t1*t2" }, { "code": null, "e": 774, "s": 481, "text": "In compiler design the most popular intermediate code representation is Three-address code. It is globally accepted and is most widely used. There are a lot of three-address statements. All the complex three-address statements are generally a combination of simpler three-address statements. " }, { "code": null, "e": 896, "s": 774, "text": "These statements come under following seven categories and can be called as building block for three-address statements- " }, { "code": null, "e": 1007, "s": 898, "text": "Now, by using the above statements let us convert some popular high level constructs in Three-address code. " }, { "code": null, "e": 1030, "s": 1007, "text": "1. While Statement – " }, { "code": null, "e": 1043, "s": 1030, "text": "while E do S" }, { "code": null, "e": 1065, "s": 1043, "text": "Three-address Code: " }, { "code": null, "e": 1104, "s": 1065, "text": "L:if(E==0) goto L1\n S\n goto L\nL1:end" }, { "code": null, "e": 1125, "s": 1104, "text": "2. For Statement – " }, { "code": null, "e": 1144, "s": 1125, "text": "for(E1;E2;E3) do S" }, { "code": null, "e": 1166, "s": 1144, "text": "Three-address Code: " }, { "code": null, "e": 1224, "s": 1166, "text": " E1\nL:if(E2) goto L1\n goto L2\nL1:S\n E3\n goto L\nL2:end" }, { "code": null, "e": 1248, "s": 1224, "text": "3. Switch Statement – " }, { "code": null, "e": 1325, "s": 1248, "text": "switch(E){\ncase 1: S1\n break;\ncase 2: S2\n break;\ndefault: S3\n}" }, { "code": null, "e": 1347, "s": 1325, "text": "Three-address Code: " }, { "code": null, "e": 1490, "s": 1347, "text": " t=E\n goto test\nL1:S1\n goto Last\nL2:S2\n goto Last\nL3:S3\n goto Last\ntest: if(E==1) goto L1\n if(E==2) goto L2\n goto L3\nLast:end" }, { "code": null, "e": 1613, "s": 1490, "text": "Thus, we can see by using the seven statements we can replicate statements from higher level language into address codes. " }, { "code": null, "e": 1630, "s": 1613, "text": "pranavgajera1998" }, { "code": null, "e": 1646, "s": 1630, "text": "Compiler Design" }, { "code": null, "e": 1654, "s": 1646, "text": "GATE CS" }, { "code": null, "e": 1752, "s": 1654, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1810, "s": 1752, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 1843, "s": 1810, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 1874, "s": 1843, "text": "Data flow analysis in Compiler" }, { "code": null, "e": 1944, "s": 1874, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 1984, "s": 1944, "text": "Runtime Environments in Compiler Design" }, { "code": null, "e": 2004, "s": 1984, "text": "Layers of OSI Model" }, { "code": null, "e": 2028, "s": 2004, "text": "ACID Properties in DBMS" }, { "code": null, "e": 2041, "s": 2028, "text": "TCP/IP Model" }, { "code": null, "e": 2068, "s": 2041, "text": "Types of Operating Systems" } ]
Python – Length of shortest string in string list
17 Dec, 2019 Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expressionThe combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return minimum of them using min(). # Python3 code to demonstrate working of# Minimum String length# using min() + generator expression # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # Minimum String length# using min() + generator expressionres = min(len(ele) for ele in test_list) # printing resultprint("Length of minimum string is : " + str(res)) The original list : ['gfg', 'is', 'best'] Length of minimum string is : 2 Method #2 : Using len() + key argument + min()The combination of above functions can be used to perform this task. In this, we extract the minimum length using len() and min(). It is faster than above method as it performs more task built in rather than overhead by generator expression. # Python3 code to demonstrate working of# Minimum String length# using len() + key argument + min() # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print("The original list : " + str(test_list)) # Minimum String length# using len() + key argument + min()res = len(min(test_list, key = len)) # printing resultprint("Length of minimum string is : " + str(res)) The original list : ['gfg', 'is', 'best'] Length of minimum string is : 2 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2019" }, { "code": null, "e": 300, "s": 28, "text": "Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have application in many domains. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 529, "s": 300, "text": "Method #1 : Using min() + generator expressionThe combination of above functionalities can be used to perform this task. In this, we extract all the list lengths using generator expression and return minimum of them using min()." }, { "code": "# Python3 code to demonstrate working of# Minimum String length# using min() + generator expression # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # Minimum String length# using min() + generator expressionres = min(len(ele) for ele in test_list) # printing resultprint(\"Length of minimum string is : \" + str(res))", "e": 925, "s": 529, "text": null }, { "code": null, "e": 1000, "s": 925, "text": "The original list : ['gfg', 'is', 'best']\nLength of minimum string is : 2\n" }, { "code": null, "e": 1290, "s": 1002, "text": "Method #2 : Using len() + key argument + min()The combination of above functions can be used to perform this task. In this, we extract the minimum length using len() and min(). It is faster than above method as it performs more task built in rather than overhead by generator expression." }, { "code": "# Python3 code to demonstrate working of# Minimum String length# using len() + key argument + min() # initialize list test_list = ['gfg', 'is', 'best'] # printing original list print(\"The original list : \" + str(test_list)) # Minimum String length# using len() + key argument + min()res = len(min(test_list, key = len)) # printing resultprint(\"Length of minimum string is : \" + str(res))", "e": 1682, "s": 1290, "text": null }, { "code": null, "e": 1757, "s": 1682, "text": "The original list : ['gfg', 'is', 'best']\nLength of minimum string is : 2\n" }, { "code": null, "e": 1778, "s": 1757, "text": "Python list-programs" }, { "code": null, "e": 1785, "s": 1778, "text": "Python" }, { "code": null, "e": 1801, "s": 1785, "text": "Python Programs" }, { "code": null, "e": 1899, "s": 1801, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1917, "s": 1899, "text": "Python Dictionary" }, { "code": null, "e": 1959, "s": 1917, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1981, "s": 1959, "text": "Enumerate() in Python" }, { "code": null, "e": 2007, "s": 1981, "text": "Python String | replace()" }, { "code": null, "e": 2039, "s": 2007, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2082, "s": 2039, "text": "Python program to convert a list to string" }, { "code": null, "e": 2104, "s": 2082, "text": "Defaultdict in Python" }, { "code": null, "e": 2143, "s": 2104, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2181, "s": 2143, "text": "Python | Convert a list to dictionary" } ]
Python | Working with Pandas and XlsxWriter | Set – 1
26 Dec, 2018 Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel. Pandas writes Excel files using the XlsxWriter modules. XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others. Code #1: Converting a Pandas dataframe to an xlsx file using Pandas and XlsxWriter. # import pandas as pdimport pandas as pd # Create a Pandas dataframe from some data.df = pd.DataFrame({'Data': ['Geeks', 'For', 'geeks', 'is', 'portal', 'for', 'geeks']}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer = pd.ExcelWriter('pandasEx.xlsx', engine ='xlsxwriter') # Write a dataframe to the worksheet.df.to_excel(writer, sheet_name ='Sheet1') # Close the Pandas Excel writer# object and output the Excel file.writer.save() Output : Code #2: Writing multiple dataframes to worksheets using Pandas and XlsxWriter. # import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]}) # Create a Pandas Excel writer object # using XlsxWriter as the engine.writer = pd.ExcelWriter('pandas_multiple.xlsx', engine ='xlsxwriter') # Write each dataframe to a different worksheet.df1.to_excel(writer, sheet_name ='Sheet1')df2.to_excel(writer, sheet_name ='Sheet2')df3.to_excel(writer, sheet_name ='Sheet3') # Close the Pandas Excel writer object# and output the Excel file.writer.save() Output : Code #3: Positioning dataframes in a worksheet using Pandas and XlsxWriter. # import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})df4 = pd.DataFrame({'Data': [41, 42, 43, 44]}) # Create a Pandas Excel writer object# using XlsxWriter as the engine.writer = pd.ExcelWriter('pandas_positioning.xlsx', engine ='xlsxwriter') # write and Positioning the dataframes in the worksheet.# Default position, cell A1.df1.to_excel(writer, sheet_name ='Sheet1') df2.to_excel(writer, sheet_name ='Sheet1', startcol = 3)df3.to_excel(writer, sheet_name ='Sheet1', startrow = 6) # It is also possible to write the# dataframe without the header and index.df4.to_excel(writer, sheet_name ='Sheet1', startrow = 7, startcol = 4, header = False, index = False) # Close the Pandas Excel writer object# and output the Excel file.writer.save() Output : Python-excel Python-pandas Technical Scripter 2018 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 Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n26 Dec, 2018" }, { "code": null, "e": 211, "s": 54, "text": "Python Pandas is a data analysis library. It can read, filter and re-arrange small and large datasets and output them in a range of formats including Excel." }, { "code": null, "e": 267, "s": 211, "text": "Pandas writes Excel files using the XlsxWriter modules." }, { "code": null, "e": 545, "s": 267, "text": "XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others." }, { "code": null, "e": 629, "s": 545, "text": "Code #1: Converting a Pandas dataframe to an xlsx file using Pandas and XlsxWriter." }, { "code": "# import pandas as pdimport pandas as pd # Create a Pandas dataframe from some data.df = pd.DataFrame({'Data': ['Geeks', 'For', 'geeks', 'is', 'portal', 'for', 'geeks']}) # Create a Pandas Excel writer# object using XlsxWriter as the engine.writer = pd.ExcelWriter('pandasEx.xlsx', engine ='xlsxwriter') # Write a dataframe to the worksheet.df.to_excel(writer, sheet_name ='Sheet1') # Close the Pandas Excel writer# object and output the Excel file.writer.save()", "e": 1145, "s": 629, "text": null }, { "code": null, "e": 1155, "s": 1145, "text": "Output : " }, { "code": null, "e": 1235, "s": 1155, "text": "Code #2: Writing multiple dataframes to worksheets using Pandas and XlsxWriter." }, { "code": "# import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]}) # Create a Pandas Excel writer object # using XlsxWriter as the engine.writer = pd.ExcelWriter('pandas_multiple.xlsx', engine ='xlsxwriter') # Write each dataframe to a different worksheet.df1.to_excel(writer, sheet_name ='Sheet1')df2.to_excel(writer, sheet_name ='Sheet2')df3.to_excel(writer, sheet_name ='Sheet3') # Close the Pandas Excel writer object# and output the Excel file.writer.save()", "e": 1890, "s": 1235, "text": null }, { "code": null, "e": 1977, "s": 1890, "text": "Output : Code #3: Positioning dataframes in a worksheet using Pandas and XlsxWriter." }, { "code": "# import pandas as pdimport pandas as pd # Create some Pandas dataframes from some data.df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})df4 = pd.DataFrame({'Data': [41, 42, 43, 44]}) # Create a Pandas Excel writer object# using XlsxWriter as the engine.writer = pd.ExcelWriter('pandas_positioning.xlsx', engine ='xlsxwriter') # write and Positioning the dataframes in the worksheet.# Default position, cell A1.df1.to_excel(writer, sheet_name ='Sheet1') df2.to_excel(writer, sheet_name ='Sheet1', startcol = 3)df3.to_excel(writer, sheet_name ='Sheet1', startrow = 6) # It is also possible to write the# dataframe without the header and index.df4.to_excel(writer, sheet_name ='Sheet1', startrow = 7, startcol = 4, header = False, index = False) # Close the Pandas Excel writer object# and output the Excel file.writer.save()", "e": 2951, "s": 1977, "text": null }, { "code": null, "e": 2960, "s": 2951, "text": "Output :" }, { "code": null, "e": 2973, "s": 2960, "text": "Python-excel" }, { "code": null, "e": 2987, "s": 2973, "text": "Python-pandas" }, { "code": null, "e": 3011, "s": 2987, "text": "Technical Scripter 2018" }, { "code": null, "e": 3018, "s": 3011, "text": "Python" }, { "code": null, "e": 3116, "s": 3018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3144, "s": 3116, "text": "Read JSON file using Python" }, { "code": null, "e": 3194, "s": 3144, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3216, "s": 3194, "text": "Python map() function" }, { "code": null, "e": 3260, "s": 3216, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 3302, "s": 3260, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3324, "s": 3302, "text": "Enumerate() in Python" }, { "code": null, "e": 3359, "s": 3324, "text": "Read a file line by line in Python" }, { "code": null, "e": 3385, "s": 3359, "text": "Python String | replace()" }, { "code": null, "e": 3417, "s": 3385, "text": "How to Install PIP on Windows ?" } ]
Check if a given number is a Perfect square using Binary Search
09 Apr, 2021 Check if a given number N is a perfect square or not. If yes then return the number of which it is a perfect square, Else print -1. Examples: Input: N = 4900 Output 70 Explanation: 4900 is a perfect square number of 70 because 70 * 70 = 4900 Input: N = 81 Output: 9 Explanation: 81 is a perfect square number of 9 because 9 * 9 = 81 Approach: To solve the problem mentioned above we will use the Binary Search Algorithm. Find the mid element from the start and last value and compare the value of the square of mid(mid*mid) with N. If it is equal then return the mid otherwise check if the square(mid*mid) is greater than N then recursive call with the same start value but changed last to mid-1 value and if the square(mid*mid) is less than the N then recursive call with the same last value but changed start value. If the N is not a square root then return -1. Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ program to check if a// given number is Perfect// square using Binary Search #include <iostream>using namespace std; // function to check for// perfect square numberint checkPerfectSquare( long int N, long int start, long int last){ // Find the mid value // from start and last long int mid = (start + last) / 2; if (start > last) { return -1; } // check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // if the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare( N, start, mid - 1); } // if the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare( N, mid + 1, last); }} // Driver codeint main(){ long int N = 65; cout << checkPerfectSquare(N, 1, N); return 0;} // Java program to check if a// given number is Perfect// square using Binary Searchimport java.util.*; class GFG { // Function to check for// perfect square numberstatic int checkPerfectSquare(long N, long start, long last){ // Find the mid value // from start and last long mid = (start + last) / 2; if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return (int)mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare(N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare(N, mid + 1, last); }} // Driver codepublic static void main(String[] args){ long N = 65; System.out.println(checkPerfectSquare(N, 1, N));}} // This code is contributed by offbeat # Python3 program to check if a# given number is perfect# square using Binary Search # Function to check for# perfect square numberdef checkPerfectSquare(N, start, last): # Find the mid value # from start and last mid = int((start + last) / 2) if (start > last): return -1 # Check if we got the number which # is square root of the perfect # square number N if (mid * mid == N): return mid # If the square(mid) is greater than N # it means only lower values then mid # will be possibly the square root of N elif (mid * mid > N): return checkPerfectSquare(N, start, mid - 1) # If the square(mid) is less than N # it means only higher values then mid # will be possibly the square root of N else: return checkPerfectSquare(N, mid + 1, last) # Driver codeN = 65print (checkPerfectSquare(N, 1, N)) # This code is contributed by PratikBasu // C# program to check if a// given number is Perfect// square using Binary Searchusing System; class GFG{ // Function to check for// perfect square numberpublic static int checkPerfectSquare(int N, int start, int last){ // Find the mid value // from start and last int mid = (start + last) / 2; if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare(N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare(N, mid + 1, last); }} // Driver codepublic static int Main(){ int N = 65; Console.Write(checkPerfectSquare(N, 1, N)); return 0;}} // This code is contributed by sayesha <script> // Javascript program to check if a// given number is Perfect// square using Binary Search // Function to check for// perfect square numberfunction checkPerfectSquare(N, start, last){ // Find the mid value // from start and last let mid = parseInt((start + last) / 2); if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare( N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare( N, mid + 1, last); }} // Driver codelet N = 65; document.write(checkPerfectSquare(N, 1, N)); // This code is contributed by rishavmahato348 </script> -1 Time Complexity: O(Logn) PratikBasu offbeat rishavmahato348 Binary Search maths-perfect-square tail-recursion Divide and Conquer Mathematical Recursion Searching Searching Mathematical Recursion Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Binary Search In JavaScript Find cubic root of a number Find a Fixed Point (Value equal to index) in a given array Find element position in given monotonic sequence Binary Search (bisect) in Python Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string Operators in C / C++
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Apr, 2021" }, { "code": null, "e": 184, "s": 52, "text": "Check if a given number N is a perfect square or not. If yes then return the number of which it is a perfect square, Else print -1." }, { "code": null, "e": 195, "s": 184, "text": "Examples: " }, { "code": null, "e": 295, "s": 195, "text": "Input: N = 4900 Output 70 Explanation: 4900 is a perfect square number of 70 because 70 * 70 = 4900" }, { "code": null, "e": 388, "s": 295, "text": "Input: N = 81 Output: 9 Explanation: 81 is a perfect square number of 9 because 9 * 9 = 81 " }, { "code": null, "e": 478, "s": 388, "text": "Approach: To solve the problem mentioned above we will use the Binary Search Algorithm. " }, { "code": null, "e": 589, "s": 478, "text": "Find the mid element from the start and last value and compare the value of the square of mid(mid*mid) with N." }, { "code": null, "e": 875, "s": 589, "text": "If it is equal then return the mid otherwise check if the square(mid*mid) is greater than N then recursive call with the same start value but changed last to mid-1 value and if the square(mid*mid) is less than the N then recursive call with the same last value but changed start value." }, { "code": null, "e": 921, "s": 875, "text": "If the N is not a square root then return -1." }, { "code": null, "e": 969, "s": 921, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 973, "s": 969, "text": "C++" }, { "code": null, "e": 978, "s": 973, "text": "Java" }, { "code": null, "e": 986, "s": 978, "text": "Python3" }, { "code": null, "e": 989, "s": 986, "text": "C#" }, { "code": null, "e": 1000, "s": 989, "text": "Javascript" }, { "code": "// C++ program to check if a// given number is Perfect// square using Binary Search #include <iostream>using namespace std; // function to check for// perfect square numberint checkPerfectSquare( long int N, long int start, long int last){ // Find the mid value // from start and last long int mid = (start + last) / 2; if (start > last) { return -1; } // check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // if the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare( N, start, mid - 1); } // if the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare( N, mid + 1, last); }} // Driver codeint main(){ long int N = 65; cout << checkPerfectSquare(N, 1, N); return 0;}", "e": 2070, "s": 1000, "text": null }, { "code": "// Java program to check if a// given number is Perfect// square using Binary Searchimport java.util.*; class GFG { // Function to check for// perfect square numberstatic int checkPerfectSquare(long N, long start, long last){ // Find the mid value // from start and last long mid = (start + last) / 2; if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return (int)mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare(N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare(N, mid + 1, last); }} // Driver codepublic static void main(String[] args){ long N = 65; System.out.println(checkPerfectSquare(N, 1, N));}} // This code is contributed by offbeat", "e": 3292, "s": 2070, "text": null }, { "code": "# Python3 program to check if a# given number is perfect# square using Binary Search # Function to check for# perfect square numberdef checkPerfectSquare(N, start, last): # Find the mid value # from start and last mid = int((start + last) / 2) if (start > last): return -1 # Check if we got the number which # is square root of the perfect # square number N if (mid * mid == N): return mid # If the square(mid) is greater than N # it means only lower values then mid # will be possibly the square root of N elif (mid * mid > N): return checkPerfectSquare(N, start, mid - 1) # If the square(mid) is less than N # it means only higher values then mid # will be possibly the square root of N else: return checkPerfectSquare(N, mid + 1, last) # Driver codeN = 65print (checkPerfectSquare(N, 1, N)) # This code is contributed by PratikBasu", "e": 4274, "s": 3292, "text": null }, { "code": "// C# program to check if a// given number is Perfect// square using Binary Searchusing System; class GFG{ // Function to check for// perfect square numberpublic static int checkPerfectSquare(int N, int start, int last){ // Find the mid value // from start and last int mid = (start + last) / 2; if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare(N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare(N, mid + 1, last); }} // Driver codepublic static int Main(){ int N = 65; Console.Write(checkPerfectSquare(N, 1, N)); return 0;}} // This code is contributed by sayesha", "e": 5493, "s": 4274, "text": null }, { "code": "<script> // Javascript program to check if a// given number is Perfect// square using Binary Search // Function to check for// perfect square numberfunction checkPerfectSquare(N, start, last){ // Find the mid value // from start and last let mid = parseInt((start + last) / 2); if (start > last) { return -1; } // Check if we got the number which // is square root of the perfect // square number N if (mid * mid == N) { return mid; } // If the square(mid) is greater than N // it means only lower values then mid // will be possibly the square root of N else if (mid * mid > N) { return checkPerfectSquare( N, start, mid - 1); } // If the square(mid) is less than N // it means only higher values then mid // will be possibly the square root of N else { return checkPerfectSquare( N, mid + 1, last); }} // Driver codelet N = 65; document.write(checkPerfectSquare(N, 1, N)); // This code is contributed by rishavmahato348 </script>", "e": 6556, "s": 5493, "text": null }, { "code": null, "e": 6559, "s": 6556, "text": "-1" }, { "code": null, "e": 6587, "s": 6561, "text": "Time Complexity: O(Logn) " }, { "code": null, "e": 6598, "s": 6587, "text": "PratikBasu" }, { "code": null, "e": 6606, "s": 6598, "text": "offbeat" }, { "code": null, "e": 6622, "s": 6606, "text": "rishavmahato348" }, { "code": null, "e": 6636, "s": 6622, "text": "Binary Search" }, { "code": null, "e": 6657, "s": 6636, "text": "maths-perfect-square" }, { "code": null, "e": 6672, "s": 6657, "text": "tail-recursion" }, { "code": null, "e": 6691, "s": 6672, "text": "Divide and Conquer" }, { "code": null, "e": 6704, "s": 6691, "text": "Mathematical" }, { "code": null, "e": 6714, "s": 6704, "text": "Recursion" }, { "code": null, "e": 6724, "s": 6714, "text": "Searching" }, { "code": null, "e": 6734, "s": 6724, "text": "Searching" }, { "code": null, "e": 6747, "s": 6734, "text": "Mathematical" }, { "code": null, "e": 6757, "s": 6747, "text": "Recursion" }, { "code": null, "e": 6776, "s": 6757, "text": "Divide and Conquer" }, { "code": null, "e": 6790, "s": 6776, "text": "Binary Search" }, { "code": null, "e": 6888, "s": 6790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6916, "s": 6888, "text": "Binary Search In JavaScript" }, { "code": null, "e": 6944, "s": 6916, "text": "Find cubic root of a number" }, { "code": null, "e": 7003, "s": 6944, "text": "Find a Fixed Point (Value equal to index) in a given array" }, { "code": null, "e": 7053, "s": 7003, "text": "Find element position in given monotonic sequence" }, { "code": null, "e": 7086, "s": 7053, "text": "Binary Search (bisect) in Python" }, { "code": null, "e": 7116, "s": 7086, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7131, "s": 7116, "text": "C++ Data Types" }, { "code": null, "e": 7174, "s": 7131, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7234, "s": 7174, "text": "Write a program to print all permutations of a given string" } ]
Results of comparison operations in C and C++
28 May, 2017 In C, data type of result of comparison operations is int. For example, see the following program. #include<stdio.h>int main(){ int x = 10, y = 10; printf("%d \n", sizeof(x == y)); printf("%d \n", sizeof(x < y)); return 0;} Output: 4 4 Whereas in C++, type of results of comparison operations is bool. For example, see the following program. #include<iostream>using namespace std; int main(){ int x = 10, y = 10; cout << sizeof(x == y) << endl; cout << sizeof(x < y); return 0;} Output: 1 1 This article is contributed by Rajat. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C-Operators cpp-operator C Language C++ cpp-operator CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C std::string class in C++ Unordered Sets in C++ Standard Template Library Memory Layout of C Programs What is the purpose of a function prototype? 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) Inheritance in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2017" }, { "code": null, "e": 153, "s": 54, "text": "In C, data type of result of comparison operations is int. For example, see the following program." }, { "code": "#include<stdio.h>int main(){ int x = 10, y = 10; printf(\"%d \\n\", sizeof(x == y)); printf(\"%d \\n\", sizeof(x < y)); return 0;}", "e": 290, "s": 153, "text": null }, { "code": null, "e": 298, "s": 290, "text": "Output:" }, { "code": null, "e": 302, "s": 298, "text": "4\n4" }, { "code": null, "e": 408, "s": 302, "text": "Whereas in C++, type of results of comparison operations is bool. For example, see the following program." }, { "code": "#include<iostream>using namespace std; int main(){ int x = 10, y = 10; cout << sizeof(x == y) << endl; cout << sizeof(x < y); return 0;}", "e": 558, "s": 408, "text": null }, { "code": null, "e": 566, "s": 558, "text": "Output:" }, { "code": null, "e": 570, "s": 566, "text": "1\n1" }, { "code": null, "e": 732, "s": 570, "text": "This article is contributed by Rajat. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 744, "s": 732, "text": "C-Operators" }, { "code": null, "e": 757, "s": 744, "text": "cpp-operator" }, { "code": null, "e": 768, "s": 757, "text": "C Language" }, { "code": null, "e": 772, "s": 768, "text": "C++" }, { "code": null, "e": 785, "s": 772, "text": "cpp-operator" }, { "code": null, "e": 789, "s": 785, "text": "CPP" }, { "code": null, "e": 887, "s": 789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 909, "s": 887, "text": "Function Pointer in C" }, { "code": null, "e": 934, "s": 909, "text": "std::string class in C++" }, { "code": null, "e": 982, "s": 934, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1010, "s": 982, "text": "Memory Layout of C Programs" }, { "code": null, "e": 1055, "s": 1010, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 1073, "s": 1055, "text": "Vector in C++ STL" }, { "code": null, "e": 1116, "s": 1073, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 1162, "s": 1116, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 1205, "s": 1162, "text": "Set in C++ Standard Template Library (STL)" } ]
Python Program to replace list elements within a range with a given number
24 Jan, 2021 Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9 Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1] Explanation : List is updated with 9 from 4th to 8th index. Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 8 Output : [4, 6, 8, 1, 8, 8, 8, 8, 12, 3, 9, 1] Explanation : List is updated with 8 from 4th to 8th index. Method 1 : Using slicing and * operator In this, we perform task of getting elements of range using slicing and * operator is used to perform update and provide required elements to fill updates. Program: Python3 # initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing i, ji, j = 4, 8 # initializing KK = 9 # getting range using slicing and# required elements using * operatortest_list[i:j] = [K] * (j - i) # printing resultprint("Range Updated list : " + str(test_list)) Output: The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9] Method 2 : Using repeat() and list slicing The similar task can also be performed using repeat(), which uses unbuilt constructs to get required elements. Program: Python3 from itertools import repeat # initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint("The original list is : " + str(test_list)) # initializing i, ji, j = 4, 8 # initializing KK = 9 # getting range using slicing and# required elements using repeat()test_list[i:j] = repeat(K, (j - i)) # printing resultprint("Range Updated list : " + str(test_list)) Output: The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Split string into list of characters
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 180, "s": 28, "text": "Given a range, the task here is to write a python program that can update the list elements falling under a given index range with a specified number." }, { "code": null, "e": 259, "s": 180, "text": "Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 9" }, { "code": null, "e": 306, "s": 259, "text": "Output : [4, 6, 8, 1, 9, 9, 9, 9, 12, 3, 9, 1]" }, { "code": null, "e": 366, "s": 306, "text": "Explanation : List is updated with 9 from 4th to 8th index." }, { "code": null, "e": 445, "s": 366, "text": "Input : test_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1], i, j = 4, 8, K = 8" }, { "code": null, "e": 492, "s": 445, "text": "Output : [4, 6, 8, 1, 8, 8, 8, 8, 12, 3, 9, 1]" }, { "code": null, "e": 552, "s": 492, "text": "Explanation : List is updated with 8 from 4th to 8th index." }, { "code": null, "e": 592, "s": 552, "text": "Method 1 : Using slicing and * operator" }, { "code": null, "e": 748, "s": 592, "text": "In this, we perform task of getting elements of range using slicing and * operator is used to perform update and provide required elements to fill updates." }, { "code": null, "e": 757, "s": 748, "text": "Program:" }, { "code": null, "e": 765, "s": 757, "text": "Python3" }, { "code": "# initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing i, ji, j = 4, 8 # initializing KK = 9 # getting range using slicing and# required elements using * operatortest_list[i:j] = [K] * (j - i) # printing resultprint(\"Range Updated list : \" + str(test_list))", "e": 1132, "s": 765, "text": null }, { "code": null, "e": 1140, "s": 1132, "text": "Output:" }, { "code": null, "e": 1202, "s": 1140, "text": "The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]" }, { "code": null, "e": 1265, "s": 1202, "text": "Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9]" }, { "code": null, "e": 1308, "s": 1265, "text": "Method 2 : Using repeat() and list slicing" }, { "code": null, "e": 1419, "s": 1308, "text": "The similar task can also be performed using repeat(), which uses unbuilt constructs to get required elements." }, { "code": null, "e": 1428, "s": 1419, "text": "Program:" }, { "code": null, "e": 1436, "s": 1428, "text": "Python3" }, { "code": "from itertools import repeat # initializing listtest_list = [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing i, ji, j = 4, 8 # initializing KK = 9 # getting range using slicing and# required elements using repeat()test_list[i:j] = repeat(K, (j - i)) # printing resultprint(\"Range Updated list : \" + str(test_list))", "e": 1836, "s": 1436, "text": null }, { "code": null, "e": 1844, "s": 1836, "text": "Output:" }, { "code": null, "e": 1906, "s": 1844, "text": "The original list is : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1]" }, { "code": null, "e": 1969, "s": 1906, "text": "Range Updated list : [4, 6, 8, 1, 2, 9, 0, 10, 12, 3, 9, 1, 9]" }, { "code": null, "e": 1990, "s": 1969, "text": "Python list-programs" }, { "code": null, "e": 1997, "s": 1990, "text": "Python" }, { "code": null, "e": 2013, "s": 1997, "text": "Python Programs" }, { "code": null, "e": 2111, "s": 2013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2143, "s": 2111, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2170, "s": 2143, "text": "Python Classes and Objects" }, { "code": null, "e": 2191, "s": 2170, "text": "Python OOPs Concepts" }, { "code": null, "e": 2214, "s": 2191, "text": "Introduction To PYTHON" }, { "code": null, "e": 2270, "s": 2214, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2292, "s": 2270, "text": "Defaultdict in Python" }, { "code": null, "e": 2331, "s": 2292, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2369, "s": 2331, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2406, "s": 2369, "text": "Python Program for Fibonacci numbers" } ]
Python | shutil.move() method
20 Jun, 2019 Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories.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. Syntax: shutil.move(source, destination, copy_function = copy2) Parameters:source: A string representing the path of the source file.destination: A string representing the path of the destination directory.copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy, copytree, etc for this parameter. Return Value: This method returns a string which represents the path of newly created file. Example #1 : Using shutil.move() method to move file from source to destination # Python program to explain shutil.move() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks' # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print("Before moving file:") print(os.listdir(path)) # Source path source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source' # Destination path destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination' # Move the content of # source to destination dest = 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 file print("Destination path:", dest) Before moving file: ['source'] After moving file: ['destination'] Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination Example #2 :Using shutil.move() method to move file by using shutil.copytree() method and the destination directory exists already. # Python program to explain shutil.move() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks' # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print("Before moving file:") print(os.listdir(path)) # Source path source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source' # Destination path destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination' # Move the content of # source to destination# using shutil.copytree() as parameterdest = shutil.move(source, destination, copy_function = shutil.copytree) # List files and directories # in "C:/Users / Rajnish / Desktop / GeeksforGeeks" print("After moving file:") print(os.listdir(path)) # Print path of newly # created file print("Destination path:", dest) Before moving file: ['destination', 'source'] After moving file: ['destination'] Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination\source Python-shutil 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": "\n20 Jun, 2019" }, { "code": null, "e": 639, "s": 53, "text": "Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating the process of copying and removal of files and directories.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": 703, "s": 639, "text": "Syntax: shutil.move(source, destination, copy_function = copy2)" }, { "code": null, "e": 993, "s": 703, "text": "Parameters:source: A string representing the path of the source file.destination: A string representing the path of the destination directory.copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy, copytree, etc for this parameter." }, { "code": null, "e": 1085, "s": 993, "text": "Return Value: This method returns a string which represents the path of newly created file." }, { "code": null, "e": 1098, "s": 1085, "text": "Example #1 :" }, { "code": null, "e": 1165, "s": 1098, "text": "Using shutil.move() method to move file from source to destination" }, { "code": "# Python program to explain shutil.move() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks' # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print(\"Before moving file:\") print(os.listdir(path)) # Source path source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source' # Destination path destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination' # Move the content of # source to destination dest = 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 file print(\"Destination path:\", dest) ", "e": 1937, "s": 1165, "text": null }, { "code": null, "e": 2073, "s": 1937, "text": "Before moving file:\n['source']\nAfter moving file:\n['destination']\nDestination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination\n" }, { "code": null, "e": 2205, "s": 2073, "text": "Example #2 :Using shutil.move() method to move file by using shutil.copytree() method and the destination directory exists already." }, { "code": "# Python program to explain shutil.move() method # importing os module import os # importing shutil module import shutil # path path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks' # List files and directories # in 'C:/Users/Rajnish/Desktop/GeeksforGeeks' print(\"Before moving file:\") print(os.listdir(path)) # Source path source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source' # Destination path destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination' # Move the content of # source to destination# using shutil.copytree() as parameterdest = shutil.move(source, destination, copy_function = shutil.copytree) # List files and directories # in \"C:/Users / Rajnish / Desktop / GeeksforGeeks\" print(\"After moving file:\") print(os.listdir(path)) # Print path of newly # created file print(\"Destination path:\", dest) ", "e": 3047, "s": 2205, "text": null }, { "code": null, "e": 3205, "s": 3047, "text": "Before moving file:\n['destination', 'source']\nAfter moving file:\n['destination']\nDestination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination\\source\n" }, { "code": null, "e": 3219, "s": 3205, "text": "Python-shutil" }, { "code": null, "e": 3226, "s": 3219, "text": "Python" }, { "code": null, "e": 3324, "s": 3226, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3342, "s": 3324, "text": "Python Dictionary" }, { "code": null, "e": 3384, "s": 3342, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3406, "s": 3384, "text": "Enumerate() in Python" }, { "code": null, "e": 3441, "s": 3406, "text": "Read a file line by line in Python" }, { "code": null, "e": 3467, "s": 3441, "text": "Python String | replace()" }, { "code": null, "e": 3499, "s": 3467, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3528, "s": 3499, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3555, "s": 3528, "text": "Python Classes and Objects" }, { "code": null, "e": 3585, "s": 3555, "text": "Iterate over a list in Python" } ]
Python end parameter in print()
24 Jun, 2022 By default python’s print() function ends with a newline. A programmer with C/C++ background may wonder how to print without newline. Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter. Python3 # This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with a <space>print("Welcome to" , end = ' ')print("GeeksforGeeks", end = ' ') Output : Welcome to GeeksforGeeks One more program to demonstrate working of end parameter. Python3 # This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with '@'print("Python" , end = '@')print("GeeksforGeeks") Output : Python@GeeksforGeeks The print() function uses sep parameter to separate the arguments and ends after the last argument. For example, Example of end parameter along with sep in print() function. Python3 print('G','F', sep='', end='')print('G')#\n provides new line after printing the yearprint('09','12','2016', sep='-', end='\n') print('Red','Green','Blue', sep=',', end='@')print('geeksforgeeks') Output: print('G','F', sep='', end='') print('G') #\n provides new line after printing the year print('09','12','2016', sep='-', end='\n') print('Red','Green','Blue', sep=',', end='@') print('geeksforgeeks') This article is contributed by Ankit Bindal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 sagar utekar sheetal18june Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 407, "s": 53, "text": "By default python’s print() function ends with a newline. A programmer with C/C++ background may wonder how to print without newline. Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\\n’, i.e. the new line character. You can end a print statement with any character/string using this parameter. " }, { "code": null, "e": 415, "s": 407, "text": "Python3" }, { "code": "# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with a <space>print(\"Welcome to\" , end = ' ')print(\"GeeksforGeeks\", end = ' ')", "e": 588, "s": 415, "text": null }, { "code": null, "e": 597, "s": 588, "text": "Output :" }, { "code": null, "e": 622, "s": 597, "text": "Welcome to GeeksforGeeks" }, { "code": null, "e": 681, "s": 622, "text": "One more program to demonstrate working of end parameter. " }, { "code": null, "e": 689, "s": 681, "text": "Python3" }, { "code": "# This Python program must be run with# Python 3 as it won't work with 2.7. # ends the output with '@'print(\"Python\" , end = '@')print(\"GeeksforGeeks\")", "e": 841, "s": 689, "text": null }, { "code": null, "e": 850, "s": 841, "text": "Output :" }, { "code": null, "e": 871, "s": 850, "text": "Python@GeeksforGeeks" }, { "code": null, "e": 984, "s": 871, "text": "The print() function uses sep parameter to separate the arguments and ends after the last argument. For example," }, { "code": null, "e": 1045, "s": 984, "text": "Example of end parameter along with sep in print() function." }, { "code": null, "e": 1053, "s": 1045, "text": "Python3" }, { "code": "print('G','F', sep='', end='')print('G')#\\n provides new line after printing the yearprint('09','12','2016', sep='-', end='\\n') print('Red','Green','Blue', sep=',', end='@')print('geeksforgeeks')", "e": 1250, "s": 1053, "text": null }, { "code": null, "e": 1258, "s": 1250, "text": "Output:" }, { "code": null, "e": 1460, "s": 1258, "text": "print('G','F', sep='', end='')\nprint('G')\n#\\n provides new line after printing the year\nprint('09','12','2016', sep='-', end='\\n')\n \nprint('Red','Green','Blue', sep=',', end='@')\nprint('geeksforgeeks')" }, { "code": null, "e": 1851, "s": 1460, "text": "This article is contributed by Ankit Bindal. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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": 1864, "s": 1851, "text": "sagar utekar" }, { "code": null, "e": 1878, "s": 1864, "text": "sheetal18june" }, { "code": null, "e": 1885, "s": 1878, "text": "Python" } ]
How can we write a multiline lambda expression in Java?
Lambda expression is an anonymous method that has used to provide an implementation of a method defined by a functional interface. In Java 8, it is also possible for the body of a lambda expression to be a complex expression or statement, which means a lambda expression consisting of more than one line. In that case, the semicolons are necessary. If the lambda expression returns a result then the return keyword is also required. ([comma seperated argument-list]) -> { multiline statements } interface Employee { String displayName(String s); } public class MultilineLambdaTest { public static void main(String[] s) { Employee emp = (x) -> { // Lambda Expression with multiple lines x = "Jai " + x; System.out.println(x); return x; }; emp.displayName("Adithya"); } } Jai Adithya
[ { "code": null, "e": 1620, "s": 1187, "text": "Lambda expression is an anonymous method that has used to provide an implementation of a method defined by a functional interface. In Java 8, it is also possible for the body of a lambda expression to be a complex expression or statement, which means a lambda expression consisting of more than one line. In that case, the semicolons are necessary. If the lambda expression returns a result then the return keyword is also required." }, { "code": null, "e": 1682, "s": 1620, "text": "([comma seperated argument-list]) -> { multiline statements }" }, { "code": null, "e": 2015, "s": 1682, "text": "interface Employee {\n String displayName(String s);\n}\npublic class MultilineLambdaTest {\n public static void main(String[] s) {\n Employee emp = (x) -> { // Lambda Expression with multiple lines\n x = \"Jai \" + x;\n System.out.println(x);\n return x;\n };\n emp.displayName(\"Adithya\");\n }\n}" }, { "code": null, "e": 2027, "s": 2015, "text": "Jai Adithya" } ]
HTTP - Parameters
This chapter is going to list down few of the important HTTP Protocol Parameters and their syntax the way they are used in the communication. For example, format for date, format of URL, etc. This will help you in constructing your request and response messages while writing HTTP client or server programs. You will see the complete usage of these parameters in subsequent chapters while learning the message structure for HTTP requests and responses. HTTP uses a <major>.<minor> numbering scheme to indicate versions of the protocol. The version of an HTTP message is indicated by an HTTP-Version field in the first line. Here is the general syntax of specifying HTTP version number: HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT HTTP/1.0 or HTTP/1.1 Uniform Resource Identifiers (URI) are simply formatted, case-insensitive string containing name, location, etc. to identify a resource, for example, a website, a web service, etc. A general syntax of URI used for HTTP is as follows: URI = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]] Here if the port is empty or not given, port 80 is assumed for HTTP and an empty abs_path is equivalent to an abs_path of "/". The characters other than those in the reserved and unsafe sets are equivalent to their ""%" HEX HEX" encoding. The following three URIs are equivalent: http://abc.com:80/~smith/home.html http://ABC.com/%7Esmith/home.html http://ABC.com:/%7esmith/home.html All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. HTTP applications are allowed to use any of the following three representations of date/time stamps: Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format We use character sets to specify the character sets that the client prefers. Multiple character sets can be listed separated by commas. If a value is not specified, the default is the US-ASCII. Following are the valid character sets: US-ASCII or ISO-8859-1 or ISO-8859-7 A content encoding value indicates that an encoding algorithm has been used to encode the content before passing it over the network. Content coding are primarily used to allow a document to be compressed or otherwise usefully transformed without losing the identity. All content-coding values are case-insensitive. HTTP/1.1 uses content-coding values in the Accept-Encoding and Content-Encoding header fields which we will see in the subsequent chapters. Following are the valid encoding schemes: Accept-encoding: gzip or Accept-encoding: compress or Accept-encoding: deflate HTTP uses Internet Media Types in the Content-Type and Accept header fields in order to provide open and extensible data typing and type negotiation. All the Media-type values are registered with the Internet Assigned Number Authority (IANA). The general syntax to specify media type is as follows: media-type = type "/" subtype *( ";" parameter ) The type, subtype, and parameter attribute names are case--insensitive. Accept: image/gif HTTP uses language tags within the Accept-Language and Content-Language fields. A language tag is composed of one or more parts: a primary language tag and a possibly empty series of subtags: language-tag = primary-tag *( "-" subtag ) White spaces are not allowed within the tag and all tags are case- insensitive. Example tags include: en, en-US, en-cockney, i-cherokee, x-pig-latin where any two-letter primary-tag is an ISO-639 language abbreviation and any two-letter initial subtag is an ISO-3166 country code.
[ { "code": null, "e": 2366, "s": 1913, "text": "This chapter is going to list down few of the important HTTP Protocol Parameters and their syntax the way they are used in the communication. For example, format for date, format of URL, etc. This will help you in constructing your request and response messages while writing HTTP client or server programs. You will see the complete usage of these parameters in subsequent chapters while learning the message structure for HTTP requests and responses." }, { "code": null, "e": 2599, "s": 2366, "text": "HTTP uses a <major>.<minor> numbering scheme to indicate versions of the protocol. The version of an HTTP message is indicated by an HTTP-Version field in the first line. Here is the general syntax of specifying HTTP version number:" }, { "code": null, "e": 2647, "s": 2599, "text": "HTTP-Version = \"HTTP\" \"/\" 1*DIGIT \".\" 1*DIGIT" }, { "code": null, "e": 2670, "s": 2647, "text": "HTTP/1.0\n\nor\n\nHTTP/1.1" }, { "code": null, "e": 2904, "s": 2670, "text": "Uniform Resource Identifiers (URI) are simply formatted, case-insensitive string containing name, location, etc. to identify a resource, for example, a website, a web service, etc. A general syntax of URI used for HTTP is as follows:" }, { "code": null, "e": 2967, "s": 2904, "text": "URI = \"http:\" \"//\" host [ \":\" port ] [ abs_path [ \"?\" query ]]" }, { "code": null, "e": 3206, "s": 2967, "text": "Here if the port is empty or not given, port 80 is assumed for HTTP and an empty abs_path is equivalent to an abs_path of \"/\". The characters other than those in the reserved and unsafe sets are equivalent to their \"\"%\" HEX HEX\" encoding." }, { "code": null, "e": 3247, "s": 3206, "text": "The following three URIs are equivalent:" }, { "code": null, "e": 3352, "s": 3247, "text": "http://abc.com:80/~smith/home.html\nhttp://ABC.com/%7Esmith/home.html\nhttp://ABC.com:/%7esmith/home.html\n" }, { "code": null, "e": 3548, "s": 3352, "text": "All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. HTTP applications are allowed to use any of the following three representations of date/time stamps:" }, { "code": null, "e": 3734, "s": 3548, "text": "Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123\nSunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036\nSun Nov 6 08:49:37 1994 ; ANSI C's asctime() format\n" }, { "code": null, "e": 3928, "s": 3734, "text": "We use character sets to specify the character sets that the client prefers. Multiple character sets can be listed separated by commas. If a value is not specified, the default is the US-ASCII." }, { "code": null, "e": 3968, "s": 3928, "text": "Following are the valid character sets:" }, { "code": null, "e": 4011, "s": 3968, "text": "US-ASCII\n\nor\n\nISO-8859-1\n\nor \n\nISO-8859-7\n" }, { "code": null, "e": 4280, "s": 4011, "text": "A content encoding value indicates that an encoding algorithm has been used to encode the content before passing it over the network. Content coding are primarily used to allow a document to be compressed or otherwise usefully transformed without losing the identity." }, { "code": null, "e": 4469, "s": 4280, "text": "All content-coding values are case-insensitive. HTTP/1.1 uses content-coding values in the Accept-Encoding and Content-Encoding header fields which we will see in the subsequent chapters." }, { "code": null, "e": 4511, "s": 4469, "text": "Following are the valid encoding schemes:" }, { "code": null, "e": 4596, "s": 4511, "text": "Accept-encoding: gzip\n\nor\n\nAccept-encoding: compress\n\nor \n\nAccept-encoding: deflate\n" }, { "code": null, "e": 4895, "s": 4596, "text": "HTTP uses Internet Media Types in the Content-Type and Accept header fields in order to provide open and extensible data typing and type negotiation. All the Media-type values are registered with the Internet Assigned Number Authority (IANA). The general syntax to specify media type is as follows:" }, { "code": null, "e": 4949, "s": 4895, "text": "media-type = type \"/\" subtype *( \";\" parameter )\n" }, { "code": null, "e": 5021, "s": 4949, "text": "The type, subtype, and parameter attribute names are case--insensitive." }, { "code": null, "e": 5040, "s": 5021, "text": "Accept: image/gif\n" }, { "code": null, "e": 5232, "s": 5040, "text": "HTTP uses language tags within the Accept-Language and Content-Language fields. A language tag is composed of one or more parts: a primary language tag and a possibly empty series of subtags:" }, { "code": null, "e": 5277, "s": 5232, "text": "language-tag = primary-tag *( \"-\" subtag )\n" }, { "code": null, "e": 5357, "s": 5277, "text": "White spaces are not allowed within the tag and all tags are case- insensitive." }, { "code": null, "e": 5379, "s": 5357, "text": "Example tags include:" }, { "code": null, "e": 5427, "s": 5379, "text": "en, en-US, en-cockney, i-cherokee, x-pig-latin\n" } ]
Python program to mask a list using values from another list
05 Apr, 2021 Given two lists, the task is to write a python program that marks 1 for elements present in the other list else mark 0. Input : test_list = [5, 2, 1, 9, 8, 0, 4], search_list = [1, 10, 8, 3, 9] Output : [0, 0, 1, 1, 1, 0, 0] Explanation : 1, 9, 8 are present in test_list at position 2, 3, 4 and are masked by 1. Rest are masked by 0. Input : test_list = [5, 2, 1, 19, 8, 0, 4], search_list = [1, 10, 8, 3, 9] Output : [0, 0, 1, 0, 1, 0, 0] Explanation : 1, 8 are present in test_list at position 2, 4 and are masked by 1. Rest are masked by 0. Method #1: Using list comprehension In this, we iterate through search list and in operator used to check composition using list comprehension and assign 1 for presence and 0 for absence. Python3 # Python3 code to demonstrate working of# Boolean composition mask in list# Using list comprehension # initializing listtest_list = [5, 2, 1, 9, 8, 0, 4] # printing original listprint("The original list is : " + str(test_list)) # initializing search listsearch_list = [1, 10, 8, 3, 9] # list comprehension iteration and in operator# checking compositionres = [1 if ele in search_list else 0 for ele in test_list] # printing resultprint("The Boolean Masked list : " + str(res)) Output: The original list is : [5, 2, 1, 9, 8, 0, 4] The Boolean Masked list : [0, 0, 1, 1, 1, 0, 0] Method #2: Using set() + list comprehension In this, duplicate elements are removed from the search list to reduce search space using set(). Rest all the operations are similar to the above method. Python3 # Python3 code to demonstrate working of# Boolean composition mask in list# Using set() + list comprehension # initializing listtest_list = [5, 2, 1, 9, 8, 0, 4] # printing original listprint("The original list is : " + str(test_list)) # initializing search listsearch_list = [1, 10, 8, 3, 9] # list comprehension iteration and in operator# checking composition# set() removes duplicatesres = [1 if ele in set(search_list) else 0 for ele in test_list] # printing resultprint("The Boolean Masked list : " + str(res)) Output: The original list is : [5, 2, 1, 9, 8, 0, 4] The Boolean Masked list : [0, 0, 1, 1, 1, 0, 0] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Apr, 2021" }, { "code": null, "e": 148, "s": 28, "text": "Given two lists, the task is to write a python program that marks 1 for elements present in the other list else mark 0." }, { "code": null, "e": 222, "s": 148, "text": "Input : test_list = [5, 2, 1, 9, 8, 0, 4], search_list = [1, 10, 8, 3, 9]" }, { "code": null, "e": 253, "s": 222, "text": "Output : [0, 0, 1, 1, 1, 0, 0]" }, { "code": null, "e": 363, "s": 253, "text": "Explanation : 1, 9, 8 are present in test_list at position 2, 3, 4 and are masked by 1. Rest are masked by 0." }, { "code": null, "e": 438, "s": 363, "text": "Input : test_list = [5, 2, 1, 19, 8, 0, 4], search_list = [1, 10, 8, 3, 9]" }, { "code": null, "e": 469, "s": 438, "text": "Output : [0, 0, 1, 0, 1, 0, 0]" }, { "code": null, "e": 573, "s": 469, "text": "Explanation : 1, 8 are present in test_list at position 2, 4 and are masked by 1. Rest are masked by 0." }, { "code": null, "e": 609, "s": 573, "text": "Method #1: Using list comprehension" }, { "code": null, "e": 761, "s": 609, "text": "In this, we iterate through search list and in operator used to check composition using list comprehension and assign 1 for presence and 0 for absence." }, { "code": null, "e": 769, "s": 761, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Boolean composition mask in list# Using list comprehension # initializing listtest_list = [5, 2, 1, 9, 8, 0, 4] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing search listsearch_list = [1, 10, 8, 3, 9] # list comprehension iteration and in operator# checking compositionres = [1 if ele in search_list else 0 for ele in test_list] # printing resultprint(\"The Boolean Masked list : \" + str(res))", "e": 1251, "s": 769, "text": null }, { "code": null, "e": 1259, "s": 1251, "text": "Output:" }, { "code": null, "e": 1352, "s": 1259, "text": "The original list is : [5, 2, 1, 9, 8, 0, 4]\nThe Boolean Masked list : [0, 0, 1, 1, 1, 0, 0]" }, { "code": null, "e": 1396, "s": 1352, "text": "Method #2: Using set() + list comprehension" }, { "code": null, "e": 1550, "s": 1396, "text": "In this, duplicate elements are removed from the search list to reduce search space using set(). Rest all the operations are similar to the above method." }, { "code": null, "e": 1558, "s": 1550, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Boolean composition mask in list# Using set() + list comprehension # initializing listtest_list = [5, 2, 1, 9, 8, 0, 4] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing search listsearch_list = [1, 10, 8, 3, 9] # list comprehension iteration and in operator# checking composition# set() removes duplicatesres = [1 if ele in set(search_list) else 0 for ele in test_list] # printing resultprint(\"The Boolean Masked list : \" + str(res))", "e": 2079, "s": 1558, "text": null }, { "code": null, "e": 2087, "s": 2079, "text": "Output:" }, { "code": null, "e": 2180, "s": 2087, "text": "The original list is : [5, 2, 1, 9, 8, 0, 4]\nThe Boolean Masked list : [0, 0, 1, 1, 1, 0, 0]" }, { "code": null, "e": 2201, "s": 2180, "text": "Python list-programs" }, { "code": null, "e": 2208, "s": 2201, "text": "Python" }, { "code": null, "e": 2224, "s": 2208, "text": "Python Programs" }, { "code": null, "e": 2322, "s": 2224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2354, "s": 2322, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2381, "s": 2354, "text": "Python Classes and Objects" }, { "code": null, "e": 2402, "s": 2381, "text": "Python OOPs Concepts" }, { "code": null, "e": 2425, "s": 2402, "text": "Introduction To PYTHON" }, { "code": null, "e": 2456, "s": 2425, "text": "Python | os.path.join() method" }, { "code": null, "e": 2478, "s": 2456, "text": "Defaultdict in Python" }, { "code": null, "e": 2517, "s": 2478, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2555, "s": 2517, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2604, "s": 2555, "text": "Python | Convert string dictionary to dictionary" } ]
Josh Technology Group Interview Experience for SD (On-Campus)
15 Oct, 2020 Online Selection Test: This comprised of two phases. Both of which were on the same day. Phase 1 (Online Objective round): Set of 50 simple MCQs on C++, aptitude, and logical. Only those who cleared the objective round were allowed to sit for the subjective round. Phase 2 (Online Subjective round): In this round, we had to write the whole program along with appropriate comments. The code should contain explanations wherever required. Many students who wrote the correct code and passed all test cases were not shortlisted because they forgot to write the comments. You could even include some edge cases in the comments and how they are being handled. Technical Rounds: The majority of questions were asked on trees and linked lists. (and a little bit of DP). There was a total of 3 technical rounds followed by an HR Round. In each technical round, we were asked 2 questions. Sometimes if the candidate is unable to come up with the solution to any of the problems then another question is added (depends on the interviewer’s mood). Technical round 1 and 2 held on the same day while 3rd round was after a week. Technical Round 1: Flatten BST into linked listWave-Sort of Linked ListRotation count of sorted array Flatten BST into linked list Wave-Sort of Linked List Rotation count of sorted array Technical Round 2: Maximum sum of elements in array such that no two elements are adjacent to each other.Re-arrange the linked list such that first node=firstnode-last node, second node=second node-2nd last node. Example:Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 Output: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0 Explanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0Shift all the nodes to the right if there is an empty place in a Binary tree. Every level should be filled from the rightmost side. See image for example: Maximum sum of elements in array such that no two elements are adjacent to each other. Re-arrange the linked list such that first node=firstnode-last node, second node=second node-2nd last node. Example:Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 Output: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0 Explanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0 Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 Output: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0 Explanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0 Shift all the nodes to the right if there is an empty place in a Binary tree. Every level should be filled from the rightmost side. See image for example: Technical Round 3: Minimum no. of jumps required to reach the other side of the bridge. The bridge is represented in the form of an array consisting of 1s and 0s. 1 represents a valid step while 0 represents a broken step. We are given another array which consists of no of steps we can cover in one jump. We need to find the minimum jumps required to reach another end. Example: Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps.Given a BST we need to check if all the root nodes value is the average of its left and right node. If the condition is false then delete the root node. Return a BST that follows the above condition.A recent project that you worked on. Minimum no. of jumps required to reach the other side of the bridge. The bridge is represented in the form of an array consisting of 1s and 0s. 1 represents a valid step while 0 represents a broken step. We are given another array which consists of no of steps we can cover in one jump. We need to find the minimum jumps required to reach another end. Example: Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps. Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps. Given a BST we need to check if all the root nodes value is the average of its left and right node. If the condition is false then delete the root node. Return a BST that follows the above condition. A recent project that you worked on. HR Round: Tell me about yourself.Why do you want to join our organisation?One weakness.What if you are asked to work for more than 10 hours every day for a month? Tell me about yourself. Why do you want to join our organisation? One weakness. What if you are asked to work for more than 10 hours every day for a month? Josh Technology Marketing On-Campus Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Oct, 2020" }, { "code": null, "e": 144, "s": 54, "text": "Online Selection Test: This comprised of two phases. Both of which were on the same day. " }, { "code": null, "e": 320, "s": 144, "text": "Phase 1 (Online Objective round): Set of 50 simple MCQs on C++, aptitude, and logical. Only those who cleared the objective round were allowed to sit for the subjective round." }, { "code": null, "e": 711, "s": 320, "text": "Phase 2 (Online Subjective round): In this round, we had to write the whole program along with appropriate comments. The code should contain explanations wherever required. Many students who wrote the correct code and passed all test cases were not shortlisted because they forgot to write the comments. You could even include some edge cases in the comments and how they are being handled." }, { "code": null, "e": 1173, "s": 711, "text": "Technical Rounds: The majority of questions were asked on trees and linked lists. (and a little bit of DP). There was a total of 3 technical rounds followed by an HR Round. In each technical round, we were asked 2 questions. Sometimes if the candidate is unable to come up with the solution to any of the problems then another question is added (depends on the interviewer’s mood). Technical round 1 and 2 held on the same day while 3rd round was after a week. " }, { "code": null, "e": 1193, "s": 1173, "text": "Technical Round 1: " }, { "code": null, "e": 1276, "s": 1193, "text": "Flatten BST into linked listWave-Sort of Linked ListRotation count of sorted array" }, { "code": null, "e": 1305, "s": 1276, "text": "Flatten BST into linked list" }, { "code": null, "e": 1330, "s": 1305, "text": "Wave-Sort of Linked List" }, { "code": null, "e": 1361, "s": 1330, "text": "Rotation count of sorted array" }, { "code": null, "e": 1380, "s": 1361, "text": "Technical Round 2:" }, { "code": null, "e": 1892, "s": 1380, "text": "Maximum sum of elements in array such that no two elements are adjacent to each other.Re-arrange the linked list such that first node=firstnode-last node, second node=second node-2nd last node. Example:Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 \nOutput: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0\nExplanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0Shift all the nodes to the right if there is an empty place in a Binary tree. Every level should be filled from the rightmost side. See image for example:" }, { "code": null, "e": 1979, "s": 1892, "text": "Maximum sum of elements in array such that no two elements are adjacent to each other." }, { "code": null, "e": 2251, "s": 1979, "text": "Re-arrange the linked list such that first node=firstnode-last node, second node=second node-2nd last node. Example:Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 \nOutput: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0\nExplanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0" }, { "code": null, "e": 2407, "s": 2251, "text": "Input : 1 -> 2 -> 3 -> 5 -> 9 -> 6 -> 3 -> 2 -> 0 \nOutput: 1-> 0 -> 0 -> -1 -> 9 -> 6 -> 3 -> 2 -> 0\nExplanation: (1-0)->(2-2)->(3-3)->(5-6)->9->6->3->2->0" }, { "code": null, "e": 2562, "s": 2407, "text": "Shift all the nodes to the right if there is an empty place in a Binary tree. Every level should be filled from the rightmost side. See image for example:" }, { "code": null, "e": 2583, "s": 2564, "text": "Technical Round 3:" }, { "code": null, "e": 3559, "s": 2583, "text": "Minimum no. of jumps required to reach the other side of the bridge. The bridge is represented in the form of an array consisting of 1s and 0s. 1 represents a valid step while 0 represents a broken step. We are given another array which consists of no of steps we can cover in one jump. We need to find the minimum jumps required to reach another end. Example: Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps.Given a BST we need to check if all the root nodes value is the average of its left and right node. If the condition is false then delete the root node. Return a BST that follows the above condition.A recent project that you worked on." }, { "code": null, "e": 4300, "s": 3559, "text": "Minimum no. of jumps required to reach the other side of the bridge. The bridge is represented in the form of an array consisting of 1s and 0s. 1 represents a valid step while 0 represents a broken step. We are given another array which consists of no of steps we can cover in one jump. We need to find the minimum jumps required to reach another end. Example: Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps." }, { "code": null, "e": 4370, "s": 4300, "text": "Bridge=[1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,1] Jumps=[2,3,5,6] Output: 4 " }, { "code": null, "e": 4681, "s": 4370, "text": "Explanation: initially we are at the 0th index. We can take a jump of a maximum 5 (a jump of 6 lands us on 0). From the 5th index we take a jump of 3 and reach on index 8, From 8 we take a jump of 6 and land on 14. From 14 we take a final jump of 2 and reach the other end. We reached the other end in 4 jumps." }, { "code": null, "e": 4881, "s": 4681, "text": "Given a BST we need to check if all the root nodes value is the average of its left and right node. If the condition is false then delete the root node. Return a BST that follows the above condition." }, { "code": null, "e": 4918, "s": 4881, "text": "A recent project that you worked on." }, { "code": null, "e": 4928, "s": 4918, "text": "HR Round:" }, { "code": null, "e": 5081, "s": 4928, "text": "Tell me about yourself.Why do you want to join our organisation?One weakness.What if you are asked to work for more than 10 hours every day for a month?" }, { "code": null, "e": 5105, "s": 5081, "text": "Tell me about yourself." }, { "code": null, "e": 5147, "s": 5105, "text": "Why do you want to join our organisation?" }, { "code": null, "e": 5161, "s": 5147, "text": "One weakness." }, { "code": null, "e": 5237, "s": 5161, "text": "What if you are asked to work for more than 10 hours every day for a month?" }, { "code": null, "e": 5253, "s": 5237, "text": "Josh Technology" }, { "code": null, "e": 5263, "s": 5253, "text": "Marketing" }, { "code": null, "e": 5273, "s": 5263, "text": "On-Campus" }, { "code": null, "e": 5295, "s": 5273, "text": "Interview Experiences" } ]
JavaScript | Generator.prototype.next() Method
16 Apr, 2020 The Generator.prototype.next() method is an inbuilt method in JavaScript which is used to return an object with two properties done and value. Syntax: gen.next( value ); Parameters: This function accepts single parameter as mentioned above and described below: value: This parameter holds the value to be sent to the generator. Return value: This method returns an object containing two properties: done: It has the valuetrue – for the iterator which past the end of the iterated sequence.false – for the iterator which are able to produce the next value in the sequence.value: It contains any JavaScript value which is returned by the iterator. done: It has the valuetrue – for the iterator which past the end of the iterated sequence.false – for the iterator which are able to produce the next value in the sequence. true – for the iterator which past the end of the iterated sequence. false – for the iterator which are able to produce the next value in the sequence. value: It contains any JavaScript value which is returned by the iterator. Below examples illustrate the Generator.prototype.next() method in JavaScript: Example 1: function* GFG() { yield "GeeksforGeeks"; yield "JavaScript"; yield "Generator.prototype.next()";} const geek = GFG(); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); Output: Object { value: "GeeksforGeeks", done: false } Object { value: "JavaScript", done: false } Object { value: "Generator.prototype.next()", done: false } Object { value: undefined, done: true } Example 2: function* GFG(len, list) { let result = []; let val = 0; while (val < list.length) { result = []; let i = val while(i < val + len) { if (list[i]) { result.push(list[i]); } i+=1 } yield result; val += len; }}list = [ 'geeks1','geeks2','geeks3', 'geeks4','geeks5','geeks6', 'geeks7','geeks8','geeks9', 'geeks10','geeks11']; var geek = GFG(4, list); document.writeln(geek.next().value+"<br>"); document.writeln(geek.next().value+"<br>"); document.writeln(geek.next().value+"<br>"); document.writeln(geek.next().value+"<br>"); Output: geeks1,geeks2,geeks3,geeks4 geeks5,geeks6,geeks7,geeks8 geeks9,geeks10,geeks11 undefined Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below: Google Chrome Firefox Opera Safari Edge javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2020" }, { "code": null, "e": 171, "s": 28, "text": "The Generator.prototype.next() method is an inbuilt method in JavaScript which is used to return an object with two properties done and value." }, { "code": null, "e": 179, "s": 171, "text": "Syntax:" }, { "code": null, "e": 198, "s": 179, "text": "gen.next( value );" }, { "code": null, "e": 289, "s": 198, "text": "Parameters: This function accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 356, "s": 289, "text": "value: This parameter holds the value to be sent to the generator." }, { "code": null, "e": 427, "s": 356, "text": "Return value: This method returns an object containing two properties:" }, { "code": null, "e": 674, "s": 427, "text": "done: It has the valuetrue – for the iterator which past the end of the iterated sequence.false – for the iterator which are able to produce the next value in the sequence.value: It contains any JavaScript value which is returned by the iterator." }, { "code": null, "e": 847, "s": 674, "text": "done: It has the valuetrue – for the iterator which past the end of the iterated sequence.false – for the iterator which are able to produce the next value in the sequence." }, { "code": null, "e": 916, "s": 847, "text": "true – for the iterator which past the end of the iterated sequence." }, { "code": null, "e": 999, "s": 916, "text": "false – for the iterator which are able to produce the next value in the sequence." }, { "code": null, "e": 1074, "s": 999, "text": "value: It contains any JavaScript value which is returned by the iterator." }, { "code": null, "e": 1153, "s": 1074, "text": "Below examples illustrate the Generator.prototype.next() method in JavaScript:" }, { "code": null, "e": 1164, "s": 1153, "text": "Example 1:" }, { "code": "function* GFG() { yield \"GeeksforGeeks\"; yield \"JavaScript\"; yield \"Generator.prototype.next()\";} const geek = GFG(); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); console.log(geek.next()); ", "e": 1407, "s": 1164, "text": null }, { "code": null, "e": 1415, "s": 1407, "text": "Output:" }, { "code": null, "e": 1607, "s": 1415, "text": "Object { value: \"GeeksforGeeks\", done: false }\nObject { value: \"JavaScript\", done: false }\nObject { value: \"Generator.prototype.next()\", done: false }\nObject { value: undefined, done: true }\n" }, { "code": null, "e": 1618, "s": 1607, "text": "Example 2:" }, { "code": "function* GFG(len, list) { let result = []; let val = 0; while (val < list.length) { result = []; let i = val while(i < val + len) { if (list[i]) { result.push(list[i]); } i+=1 } yield result; val += len; }}list = [ 'geeks1','geeks2','geeks3', 'geeks4','geeks5','geeks6', 'geeks7','geeks8','geeks9', 'geeks10','geeks11']; var geek = GFG(4, list); document.writeln(geek.next().value+\"<br>\"); document.writeln(geek.next().value+\"<br>\"); document.writeln(geek.next().value+\"<br>\"); document.writeln(geek.next().value+\"<br>\");", "e": 2300, "s": 1618, "text": null }, { "code": null, "e": 2308, "s": 2300, "text": "Output:" }, { "code": null, "e": 2397, "s": 2308, "text": "geeks1,geeks2,geeks3,geeks4\ngeeks5,geeks6,geeks7,geeks8\ngeeks9,geeks10,geeks11\nundefined" }, { "code": null, "e": 2495, "s": 2397, "text": "Supported Browsers: The browsers supported by Generator.prototype.next() method are listed below:" }, { "code": null, "e": 2509, "s": 2495, "text": "Google Chrome" }, { "code": null, "e": 2517, "s": 2509, "text": "Firefox" }, { "code": null, "e": 2523, "s": 2517, "text": "Opera" }, { "code": null, "e": 2530, "s": 2523, "text": "Safari" }, { "code": null, "e": 2535, "s": 2530, "text": "Edge" }, { "code": null, "e": 2556, "s": 2535, "text": "javascript-functions" }, { "code": null, "e": 2567, "s": 2556, "text": "JavaScript" }, { "code": null, "e": 2584, "s": 2567, "text": "Web Technologies" }, { "code": null, "e": 2682, "s": 2584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2743, "s": 2682, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2783, "s": 2743, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2824, "s": 2783, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2866, "s": 2824, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2888, "s": 2866, "text": "JavaScript | Promises" }, { "code": null, "e": 2921, "s": 2888, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2983, "s": 2921, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3044, "s": 2983, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3094, "s": 3044, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Converting HTML to Text with BeautifulSoup
16 Apr, 2021 Many times while working with web automation we need to convert HTML code into Text. This can be done using the BeautifulSoup. This module provides get_text() function that takes HTML as input and returns text as output. Example 1: Python3 # importing the libraryfrom bs4 import BeautifulSoup # Initializing variablegfg = BeautifulSoup("<b>Section </b><br/>BeautifulSoup<ul>\<li>Example <b>1</b></li>") # Calculating resultres = gfg.get_text() # Printing the resultprint(res) Output: Section BeautifulSoupExample 1 Example 2: This example extracts data from the live website then converts it into text. In this example, we used the request module from urllib library to read HTML data from URL. Python3 # importing the libraryfrom bs4 import BeautifulSoupfrom urllib import request # Initializing variableurl = "https://www.geeksforgeeks.org/matrix-introduction/"gfg = BeautifulSoup(request.urlopen(url).read()) # Extracting data for article sectionbodyHtml = gfg.find('article', {'class' : 'content'}) # Calculating resultres = bodyHtml.get_text() # Printing the resultprint(res) Output: arorakashish0911 Picked Python BeautifulSoup Python bs4-Exercises 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": "\n16 Apr, 2021" }, { "code": null, "e": 249, "s": 28, "text": "Many times while working with web automation we need to convert HTML code into Text. This can be done using the BeautifulSoup. This module provides get_text() function that takes HTML as input and returns text as output." }, { "code": null, "e": 260, "s": 249, "text": "Example 1:" }, { "code": null, "e": 268, "s": 260, "text": "Python3" }, { "code": "# importing the libraryfrom bs4 import BeautifulSoup # Initializing variablegfg = BeautifulSoup(\"<b>Section </b><br/>BeautifulSoup<ul>\\<li>Example <b>1</b></li>\") # Calculating resultres = gfg.get_text() # Printing the resultprint(res)", "e": 504, "s": 268, "text": null }, { "code": null, "e": 516, "s": 508, "text": "Output:" }, { "code": null, "e": 549, "s": 518, "text": "Section BeautifulSoupExample 1" }, { "code": null, "e": 731, "s": 551, "text": "Example 2: This example extracts data from the live website then converts it into text. In this example, we used the request module from urllib library to read HTML data from URL." }, { "code": null, "e": 741, "s": 733, "text": "Python3" }, { "code": "# importing the libraryfrom bs4 import BeautifulSoupfrom urllib import request # Initializing variableurl = \"https://www.geeksforgeeks.org/matrix-introduction/\"gfg = BeautifulSoup(request.urlopen(url).read()) # Extracting data for article sectionbodyHtml = gfg.find('article', {'class' : 'content'}) # Calculating resultres = bodyHtml.get_text() # Printing the resultprint(res)", "e": 1119, "s": 741, "text": null }, { "code": null, "e": 1127, "s": 1119, "text": "Output:" }, { "code": null, "e": 1144, "s": 1127, "text": "arorakashish0911" }, { "code": null, "e": 1151, "s": 1144, "text": "Picked" }, { "code": null, "e": 1172, "s": 1151, "text": "Python BeautifulSoup" }, { "code": null, "e": 1193, "s": 1172, "text": "Python bs4-Exercises" }, { "code": null, "e": 1200, "s": 1193, "text": "Python" }, { "code": null, "e": 1298, "s": 1200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1316, "s": 1298, "text": "Python Dictionary" }, { "code": null, "e": 1358, "s": 1316, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1380, "s": 1358, "text": "Enumerate() in Python" }, { "code": null, "e": 1415, "s": 1380, "text": "Read a file line by line in Python" }, { "code": null, "e": 1441, "s": 1415, "text": "Python String | replace()" }, { "code": null, "e": 1473, "s": 1441, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1502, "s": 1473, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1529, "s": 1502, "text": "Python Classes and Objects" }, { "code": null, "e": 1559, "s": 1529, "text": "Iterate over a list in Python" } ]
How to put the caption below the table using CSS ?
25 Mar, 2021 To put the caption below the table we can use the CSS caption-side property. This property is used to specify the position where the table caption is placed. It is used in HTML Tables. This property can be used with any element whose display property set to caption-side. There are several parameters for this property, but we have been asked to put the caption below the table, so we will use a single parameter value that is bottom. Syntax: caption-side: bottom; Example: HTML <!DOCTYPE html> <html> <head> <title>caption-side property</title> <style> .geeks { caption-side: bottom; } </style> </head> <body> <center> <h1 style="color:green;">GeeksForGeeks</h1> <h2>caption-side: bottom:</h2> <table class="geeks" border="1"> <caption>Table 4.1 Student Details</caption> <tr> <th>Student Name</th> <th>Enroll_no.</th> <th>Address</th> </tr> <tr> <td>Hritik Bhatnagar</td> <td>234</td> <td>Delhi</td> </tr> <tr> <td>Govind madan</td> <td>235</td> <td>kolkata</td> </tr> <tr> <td>Suraj Roy</td> <td>236</td> <td>Mumbai</td> </tr> <tr> <td> Dhruv Mishra</td> <td>237</td> <td>Dehadun</td> </tr> </table> </center> </body> </html> Output: caption CSS-Basics CSS-Properties Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Mar, 2021" }, { "code": null, "e": 214, "s": 28, "text": "To put the caption below the table we can use the CSS caption-side property. This property is used to specify the position where the table caption is placed. It is used in HTML Tables. " }, { "code": null, "e": 464, "s": 214, "text": "This property can be used with any element whose display property set to caption-side. There are several parameters for this property, but we have been asked to put the caption below the table, so we will use a single parameter value that is bottom." }, { "code": null, "e": 472, "s": 464, "text": "Syntax:" }, { "code": null, "e": 494, "s": 472, "text": "caption-side: bottom;" }, { "code": null, "e": 503, "s": 494, "text": "Example:" }, { "code": null, "e": 508, "s": 503, "text": "HTML" }, { "code": "<!DOCTYPE html> <html> <head> <title>caption-side property</title> <style> .geeks { caption-side: bottom; } </style> </head> <body> <center> <h1 style=\"color:green;\">GeeksForGeeks</h1> <h2>caption-side: bottom:</h2> <table class=\"geeks\" border=\"1\"> <caption>Table 4.1 Student Details</caption> <tr> <th>Student Name</th> <th>Enroll_no.</th> <th>Address</th> </tr> <tr> <td>Hritik Bhatnagar</td> <td>234</td> <td>Delhi</td> </tr> <tr> <td>Govind madan</td> <td>235</td> <td>kolkata</td> </tr> <tr> <td>Suraj Roy</td> <td>236</td> <td>Mumbai</td> </tr> <tr> <td> Dhruv Mishra</td> <td>237</td> <td>Dehadun</td> </tr> </table> </center> </body> </html> ", "e": 1799, "s": 508, "text": null }, { "code": null, "e": 1807, "s": 1799, "text": "Output:" }, { "code": null, "e": 1815, "s": 1807, "text": "caption" }, { "code": null, "e": 1826, "s": 1815, "text": "CSS-Basics" }, { "code": null, "e": 1841, "s": 1826, "text": "CSS-Properties" }, { "code": null, "e": 1848, "s": 1841, "text": "Picked" }, { "code": null, "e": 1852, "s": 1848, "text": "CSS" }, { "code": null, "e": 1869, "s": 1852, "text": "Web Technologies" }, { "code": null, "e": 1967, "s": 1869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2006, "s": 1967, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2045, "s": 2006, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2084, "s": 2045, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2121, "s": 2084, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2150, "s": 2121, "text": "Form validation using jQuery" }, { "code": null, "e": 2183, "s": 2150, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2244, "s": 2183, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2287, "s": 2244, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2359, "s": 2287, "text": "Differences between Functional Components and Class Components in React" } ]
How to remove the axis tick marks on a Seaborn heatmap?
To remove the axis tick marks on a Seaborn heatmap, we can take the following steps Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create random data points with 4×4 dimension. Create random data points with 4×4 dimension. Plot the rectangular data as a color-encoded matrix. Plot the rectangular data as a color-encoded matrix. Use tick_params() for changing the appearance of ticks and tick labels. Use left=false and bottom=false to remove the tick marks. Use tick_params() for changing the appearance of ticks and tick labels. Use left=false and bottom=false to remove the tick marks. To display the figure, use Show() method. To display the figure, use Show() method. import numpy as np import seaborn as sns from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True data = np.random.rand(4, 4) ax = sns.heatmap(data, vmax=1) ax.tick_params(left=False, bottom=False) plt.show() It will display the following Output −
[ { "code": null, "e": 1271, "s": 1187, "text": "To remove the axis tick marks on a Seaborn heatmap, we can take the following steps" }, { "code": null, "e": 1347, "s": 1271, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1423, "s": 1347, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1469, "s": 1423, "text": "Create random data points with 4×4 dimension." }, { "code": null, "e": 1515, "s": 1469, "text": "Create random data points with 4×4 dimension." }, { "code": null, "e": 1568, "s": 1515, "text": "Plot the rectangular data as a color-encoded matrix." }, { "code": null, "e": 1621, "s": 1568, "text": "Plot the rectangular data as a color-encoded matrix." }, { "code": null, "e": 1751, "s": 1621, "text": "Use tick_params() for changing the appearance of ticks and tick labels. Use left=false and bottom=false to remove the tick marks." }, { "code": null, "e": 1881, "s": 1751, "text": "Use tick_params() for changing the appearance of ticks and tick labels. Use left=false and bottom=false to remove the tick marks." }, { "code": null, "e": 1923, "s": 1881, "text": "To display the figure, use Show() method." }, { "code": null, "e": 1965, "s": 1923, "text": "To display the figure, use Show() method." }, { "code": null, "e": 2245, "s": 1965, "text": "import numpy as np\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = np.random.rand(4, 4)\n\nax = sns.heatmap(data, vmax=1)\nax.tick_params(left=False, bottom=False)\n\nplt.show()" }, { "code": null, "e": 2284, "s": 2245, "text": "It will display the following Output −" } ]
C Program to print environment variables
20 May, 2017 The C standard says following about main function in C. The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): int main(int argc, char *argv[]) { /* ... */ } or equivalent;10) or in some other implementation-defined manner. But most of the compilers also support a third declaration of main that accepts third argument. The third argument stores all environment variables. #include <stdio.h> // Most of the C compilers support a third parameter to main which// store all envorinment variablesint main(int argc, char *argv[], char * envp[]){ int i; for (i = 0; envp[i] != NULL; i++) printf("\n%s", envp[i]); getchar(); return 0;} Output: ALLUSERSPROFILE=C:\ProgramData CommonProgramFiles=C:\Program Files\Common Files HOMEDRIVE=C: NUMBER_OF_PROCESSORS=2 OS=Windows_NT PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=2a07 ProgramData=C:\ProgramData ProgramFiles=C:\Program Files PUBLIC=C:\Users\Public SESSIONNAME=Console SystemDrive=C: SystemRoot=C:\Windows WATCOM=C:\watcom windir=C:\Windows Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above C Basics 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": "\n20 May, 2017" }, { "code": null, "e": 108, "s": 52, "text": "The C standard says following about main function in C." }, { "code": null, "e": 603, "s": 108, "text": "The function called at program startup is named main. The \nimplementation declares no prototype for this function. It shall \nbe defined with a return type of int and with no parameters:\n int main(void) { /* ... */ }\nor with two parameters (referred to here as argc and argv, though \nany names may be used, as they are local to the function in which\nthey are declared):\n int main(int argc, char *argv[]) { /* ... */ }\nor equivalent;10) or in some other implementation-defined manner." }, { "code": null, "e": 752, "s": 603, "text": "But most of the compilers also support a third declaration of main that accepts third argument. The third argument stores all environment variables." }, { "code": "#include <stdio.h> // Most of the C compilers support a third parameter to main which// store all envorinment variablesint main(int argc, char *argv[], char * envp[]){ int i; for (i = 0; envp[i] != NULL; i++) printf(\"\\n%s\", envp[i]); getchar(); return 0;}", "e": 1028, "s": 752, "text": null }, { "code": null, "e": 1036, "s": 1028, "text": "Output:" }, { "code": null, "e": 1537, "s": 1036, "text": "ALLUSERSPROFILE=C:\\ProgramData\nCommonProgramFiles=C:\\Program Files\\Common Files\nHOMEDRIVE=C:\nNUMBER_OF_PROCESSORS=2\nOS=Windows_NT\nPATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\nPROCESSOR_ARCHITECTURE=x86\nPROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel\nPROCESSOR_LEVEL=6\nPROCESSOR_REVISION=2a07\nProgramData=C:\\ProgramData\nProgramFiles=C:\\Program Files\nPUBLIC=C:\\Users\\Public\nSESSIONNAME=Console\nSystemDrive=C:\nSystemRoot=C:\\Windows\nWATCOM=C:\\watcom\nwindir=C:\\Windows" }, { "code": null, "e": 1661, "s": 1537, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1670, "s": 1661, "text": "C Basics" }, { "code": null, "e": 1681, "s": 1670, "text": "C Language" } ]
Create Toolbar in KivyMD
17 Jun, 2021 In this article, we will see how to add the toolbar in mobile applications using KivyMD in Python. KivyMD provide two type of toolbar – Top Toolbar Bottom Toolbar Let’s see how to create each type of toolbar and how to add certain attributes like title, left menu, right menu, etc. Some commonly used attributes are – To add a title to the toolbar use the title attribute. Syntax: title: ‘The title we want to show on the toolbar’ It is represented as follows- MDToolbar: title:'Demo' It is the left and the right menu that you must have seen in certain apps. To create this the following attributes are used. Syntax: Left_action_items: we need to specify a icon and function associated with it that will show on the left side of title. right_action_items: similar to left_action_items but on the right side It is represented as follows: MDToolbar: title:’Demo’ left_action_items:[[‘menu’,lambda x: app.navigation_draw()]] right_action_items:[[‘logout’,lambda x: app.navigation_draw()]] It is used for showing shadow effect below a toolbar Syntax: elevation: to show a shadow effect below toolbar It is represented as follows MDToolbar: title:’Demo’ left_action_items:[[‘menu’,lambda x: app.navigation_draw()]] right_action_items:[[‘logout’,lambda x: app.navigation_draw()]] elevation:10 To change the color of the toolbar md_bg_color is used. Syntax: md_bg_color: Its representation should be an RGB value It is represented as follows: MDToolbar: title:’Demo’ left_action_items:[[‘menu’,lambda x: app.navigation_draw()]] right_action_items:[[‘logout’,lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1 In addition to the top toolbar, we can also add a bottom toolbar. MDBottomAppBar is used to display the toolbar at the bottom. It is represented as follows: MDBottomAppBar: MDToolbar: title:’Bottom’ left_action_items:[[‘menu’,lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1 Let’s see an example where we will create both the top and bottom toolbar. Note: The widgets on the screen will adjust themselves according to the size of the window because widgets use size hinting (adjustment) by default. Python3 from kivymd.app import MDAppfrom kivymd.uix.label import MDLabelfrom kivymd.uix.screen import Screenfrom kivy.lang import Builder # builder methodhelper="""Screen: name:'About us' BoxLayout: orientation:'vertical' MDToolbar: title:'Demo' left_action_items:[['menu',lambda x: app.navigation_draw()]] right_action_items:[['logout',lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1 MDLabel: text:"hi" halign:'center' MDBottomAppBar: MDToolbar: title:'Bottom' left_action_items:[['menu',lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1"""class Demo(MDApp): def build(self): screen=Builder.load_string(helper) return screen # lambda Function def navigation_draw(self): print("NavBar") if __name__ == "__main__": Demo().run() Output: python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 164, "s": 28, "text": "In this article, we will see how to add the toolbar in mobile applications using KivyMD in Python. KivyMD provide two type of toolbar –" }, { "code": null, "e": 176, "s": 164, "text": "Top Toolbar" }, { "code": null, "e": 191, "s": 176, "text": "Bottom Toolbar" }, { "code": null, "e": 346, "s": 191, "text": "Let’s see how to create each type of toolbar and how to add certain attributes like title, left menu, right menu, etc. Some commonly used attributes are –" }, { "code": null, "e": 401, "s": 346, "text": "To add a title to the toolbar use the title attribute." }, { "code": null, "e": 459, "s": 401, "text": "Syntax: title: ‘The title we want to show on the toolbar’" }, { "code": null, "e": 489, "s": 459, "text": "It is represented as follows-" }, { "code": null, "e": 522, "s": 489, "text": "MDToolbar:\n title:'Demo' " }, { "code": null, "e": 647, "s": 522, "text": "It is the left and the right menu that you must have seen in certain apps. To create this the following attributes are used." }, { "code": null, "e": 656, "s": 647, "text": "Syntax: " }, { "code": null, "e": 775, "s": 656, "text": "Left_action_items: we need to specify a icon and function associated with it that will show on the left side of title." }, { "code": null, "e": 847, "s": 775, "text": "right_action_items: similar to left_action_items but on the right side " }, { "code": null, "e": 877, "s": 847, "text": "It is represented as follows:" }, { "code": null, "e": 888, "s": 877, "text": "MDToolbar:" }, { "code": null, "e": 901, "s": 888, "text": "title:’Demo’" }, { "code": null, "e": 962, "s": 901, "text": "left_action_items:[[‘menu’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1026, "s": 962, "text": "right_action_items:[[‘logout’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1080, "s": 1026, "text": " It is used for showing shadow effect below a toolbar" }, { "code": null, "e": 1137, "s": 1080, "text": "Syntax: elevation: to show a shadow effect below toolbar" }, { "code": null, "e": 1166, "s": 1137, "text": "It is represented as follows" }, { "code": null, "e": 1177, "s": 1166, "text": "MDToolbar:" }, { "code": null, "e": 1190, "s": 1177, "text": "title:’Demo’" }, { "code": null, "e": 1255, "s": 1190, "text": " left_action_items:[[‘menu’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1323, "s": 1255, "text": " right_action_items:[[‘logout’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1340, "s": 1323, "text": " elevation:10" }, { "code": null, "e": 1396, "s": 1340, "text": "To change the color of the toolbar md_bg_color is used." }, { "code": null, "e": 1459, "s": 1396, "text": "Syntax: md_bg_color: Its representation should be an RGB value" }, { "code": null, "e": 1489, "s": 1459, "text": "It is represented as follows:" }, { "code": null, "e": 1500, "s": 1489, "text": "MDToolbar:" }, { "code": null, "e": 1513, "s": 1500, "text": "title:’Demo’" }, { "code": null, "e": 1574, "s": 1513, "text": "left_action_items:[[‘menu’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1638, "s": 1574, "text": "right_action_items:[[‘logout’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1655, "s": 1638, "text": " elevation:10" }, { "code": null, "e": 1686, "s": 1655, "text": " md_bg_color: 0,0,100/255,1" }, { "code": null, "e": 1813, "s": 1686, "text": "In addition to the top toolbar, we can also add a bottom toolbar. MDBottomAppBar is used to display the toolbar at the bottom." }, { "code": null, "e": 1843, "s": 1813, "text": "It is represented as follows:" }, { "code": null, "e": 1859, "s": 1843, "text": "MDBottomAppBar:" }, { "code": null, "e": 1870, "s": 1859, "text": "MDToolbar:" }, { "code": null, "e": 1885, "s": 1870, "text": "title:’Bottom’" }, { "code": null, "e": 1948, "s": 1885, "text": " left_action_items:[[‘menu’,lambda x: app.navigation_draw()]]" }, { "code": null, "e": 1965, "s": 1948, "text": " elevation:10" }, { "code": null, "e": 1996, "s": 1965, "text": " md_bg_color: 0,0,100/255,1" }, { "code": null, "e": 2071, "s": 1996, "text": "Let’s see an example where we will create both the top and bottom toolbar." }, { "code": null, "e": 2220, "s": 2071, "text": "Note: The widgets on the screen will adjust themselves according to the size of the window because widgets use size hinting (adjustment) by default." }, { "code": null, "e": 2228, "s": 2220, "text": "Python3" }, { "code": "from kivymd.app import MDAppfrom kivymd.uix.label import MDLabelfrom kivymd.uix.screen import Screenfrom kivy.lang import Builder # builder methodhelper=\"\"\"Screen: name:'About us' BoxLayout: orientation:'vertical' MDToolbar: title:'Demo' left_action_items:[['menu',lambda x: app.navigation_draw()]] right_action_items:[['logout',lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1 MDLabel: text:\"hi\" halign:'center' MDBottomAppBar: MDToolbar: title:'Bottom' left_action_items:[['menu',lambda x: app.navigation_draw()]] elevation:10 md_bg_color: 0,0,100/255,1\"\"\"class Demo(MDApp): def build(self): screen=Builder.load_string(helper) return screen # lambda Function def navigation_draw(self): print(\"NavBar\") if __name__ == \"__main__\": Demo().run()", "e": 3238, "s": 2228, "text": null }, { "code": null, "e": 3246, "s": 3238, "text": "Output:" }, { "code": null, "e": 3261, "s": 3246, "text": "python-modules" }, { "code": null, "e": 3268, "s": 3261, "text": "Python" } ]
How to use rainbow colors in linux terminal
This article is for those who believe that Linux command line is boring and there is not much fun. To create an interesting colorful setting lolcat utility can be used, which produces rainbow colors in Linux terminal. Lolcat utility works for Linux, BSD and OSX which concatenates like similar to cat command. Lolcat utility is one of the gem in Ruby programming language. Hence, if you would like to practice this tip, it is essential to install the latest version of Ruby. To install Ruby use the following command – $ sudo apt-get install ruby The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: gcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386 libasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386 libavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl libcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl libcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl libdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386 libdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386 libffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386 libgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386 libgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386 libglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386 libgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386 libgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386 libgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386 libhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386 libhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386 libjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386 libk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386 libkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386 libltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl libogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386 ................................. To verify the version of ruby, use the following command – $ sudo ruby --version The sample output should be like this – ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux] To get the Lolcat from git repository, use the following command- $ wget https://github.com/busyloop/lolcat/archive/master.zip The sample output should be like this – --2016-03-10 11:43:00-- https://github.com/busyloop/lolcat/archive/master.zip Resolving github.com (github.com)... 192.30.252.128 Connecting to github.com (github.com)|192.30.252.128|:443... connected. HTTP request sent, awaiting response... 302 Found Location: https://codeload.github.com/busyloop/lolcat/zip/master [following] --2016-03-10 11:43:01-- https://codeload.github.com/busyloop/lolcat/zip/master Resolving codeload.github.com (codeload.github.com)... 192.30.252.161 Connecting to codeload.github.com (codeload.github.com)|192.30.252.161|:443... connected. HTTP request sent, awaiting response... 200 OK Length: unspecified [application/zip] Saving to: ‘master.zip’ [ <=> ] 2,03,272 234KB/s in 0.8s 2016-03-10 11:43:03 (234 KB/s) - ‘master.zip’ saved [203272] To unzip master.zip file, use the following command – $ unzip master.zip The sample output should be like this – Archive: master.zip 344e77462f8bab208f776b29bbcf63778aabd7af creating: lolcat-master/ extracting: lolcat-master/.gitignore inflating: lolcat-master/Gemfile inflating: lolcat-master/LICENSE inflating: lolcat-master/README.md extracting: lolcat-master/Rakefile creating: lolcat-master/ass/ inflating: lolcat-master/ass/screenshot.png creating: lolcat-master/bin/ inflating: lolcat-master/bin/lolcat creating: lolcat-master/lib/ inflating: lolcat-master/lib/lolcat.rb creating: lolcat-master/lib/lolcat/ inflating: lolcat-master/lib/lolcat/cat.rb inflating: lolcat-master/lib/lolcat/lol.rb extracting: lolcat-master/lib/lolcat/version.rb inflating: lolcat-master/lolcat.gemspec To enter into lolcat-master/bin directory, use the following command – $ cd lolcat-master/bin To install lolcat gem use the following command – $ gem install lolcat The sample output should be like this – $ sudo gem install lolcat The sample output should be like this – Fetching: paint-1.0.1.gem (100%) Fetching: trollop-2.1.2.gem (100%) Fetching: lolcat-42.1.43.gem (100%) Successfully installed paint-1.0.1 Successfully installed trollop-2.1.2 Successfully installed lolcat-42.1.43 3 gems installed Installing ri documentation for paint-1.0.1... Installing ri documentation for trollop-2.1.2... Installing ri documentation for lolcat-42.1.43... Installing RDoc documentation for paint-1.0.1... Installing RDoc documentation for trollop-2.1.2... Installing RDoc documentation for lolcat-42.1.43.. To get Lolcat version, use the following command – $ lolcat --version The sample output should be like this – lolcat 42.1.43 (c)2011 moe@busyloop.net To get the available option in lolcat, use the following command – $ lolcat -h The sample output should be like this – To print the text with Lolcat, use the following command – $ echo I love Tutorialspoint | lolcat $ figlet I love Tutorialspoint | lolcat The sample output should be like this – In the above command, please note that, we have used figlet. To install figlet, use the following command – $ sudo apt-get install figlet To install Lolcat with cowsay, use the following command – $ sudo apt-get install cowsay The sample output should be like this – Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: gcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386 libasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386 libavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl libcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl libcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl libdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386 libdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386 libffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386 libgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386 libgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386 libglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386 libgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386 libgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386 libgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386 ...................................................... cowsay command supports a lot of other visual graphical animals is shown in the following lines. To get the list of animals, use the following command – $ cowsay -l The sample output should be like this – Cow files in /usr/share/cowsay/cows: apt beavis.zen bong bud-frogs bunny calvin cheese cock cower daemon default dragon dragon-and-cow duck elephant elephant-in-snake eyes flaming-sheep ghostbusters gnu head-in hellokitty kiss kitty koala kosh luke-koala mech-and-cow meow milk moofasa moose mutilated pony pony-smaller ren sheep skeleton snowman sodomized-sheep stegosaurus stimpy suse three-eyes turkey turtle tux unipony unipony-smaller vader vader-koala www As an example, the below image of a pony was created using lolcat utility. Use the following command to get the output – $ cowsay -f pony I love tutorialspoint | lolcat The sample output will be something like the below – Congratulations! Now, you know “How to use Rainbow Colors in Linux Terminal”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
[ { "code": null, "e": 1372, "s": 1062, "text": "This article is for those who believe that Linux command line is boring and there is not much fun. To create an interesting colorful setting lolcat\nutility can be used, which produces rainbow colors in Linux terminal. Lolcat utility works for Linux, BSD and OSX which concatenates like similar to cat command." }, { "code": null, "e": 1537, "s": 1372, "text": "Lolcat utility is one of the gem in Ruby programming language. Hence, if you would like to practice this tip, it is essential to install the latest version of Ruby." }, { "code": null, "e": 1581, "s": 1537, "text": "To install Ruby use the following command –" }, { "code": null, "e": 1609, "s": 1581, "text": "$ sudo apt-get install ruby" }, { "code": null, "e": 1649, "s": 1609, "text": "The sample output should be like this –" }, { "code": null, "e": 3244, "s": 1649, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\ngcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386\nlibasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386\nlibavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl\nlibcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl\nlibcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl\nlibdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386\nlibdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386\nlibffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386\nlibgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386\nlibgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386\nlibglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386\nlibgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386\nlibgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386\nlibgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386\nlibhcrypto4-heimdal:i386 libheimbase1-heimdal:i386 libheimntlm0-heimdal:i386\nlibhx509-5-heimdal:i386 libice6:i386 libieee1284-3:i386\nlibjack-jackd2-0:i386 libjbig0:i386 libjpeg-turbo8:i386 libjpeg8:i386\nlibk5crypto3:i386 libkeyutils1:i386 libkrb5-26-heimdal:i386 libkrb5-3:i386\nlibkrb5support0:i386 liblcms2-2:i386 libldap-2.4-2:i386 libllvm3.6:i386\nlibltdl7:i386 libmouse-perl libmpg123-0:i386 libnet-dropbox-api-perl\nlibogg0:i386 libopenal1:i386 liborc-0.4-0:i386 libosmesa6:i386\n................................." }, { "code": null, "e": 3303, "s": 3244, "text": "To verify the version of ruby, use the following command –" }, { "code": null, "e": 3325, "s": 3303, "text": "$ sudo ruby --version" }, { "code": null, "e": 3365, "s": 3325, "text": "The sample output should be like this –" }, { "code": null, "e": 3423, "s": 3365, "text": "ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]" }, { "code": null, "e": 3489, "s": 3423, "text": "To get the Lolcat from git repository, use the following command-" }, { "code": null, "e": 3550, "s": 3489, "text": "$ wget https://github.com/busyloop/lolcat/archive/master.zip" }, { "code": null, "e": 3590, "s": 3550, "text": "The sample output should be like this –" }, { "code": null, "e": 4361, "s": 3590, "text": "--2016-03-10 11:43:00-- https://github.com/busyloop/lolcat/archive/master.zip\nResolving github.com (github.com)... 192.30.252.128\nConnecting to github.com (github.com)|192.30.252.128|:443... connected.\nHTTP request sent, awaiting response... 302 Found\nLocation: https://codeload.github.com/busyloop/lolcat/zip/master [following]\n--2016-03-10 11:43:01-- https://codeload.github.com/busyloop/lolcat/zip/master\nResolving codeload.github.com (codeload.github.com)... 192.30.252.161\nConnecting to codeload.github.com (codeload.github.com)|192.30.252.161|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: unspecified [application/zip]\nSaving to: ‘master.zip’\n[ <=> ] 2,03,272 234KB/s in 0.8s\n2016-03-10 11:43:03 (234 KB/s) - ‘master.zip’ saved [203272]" }, { "code": null, "e": 4415, "s": 4361, "text": "To unzip master.zip file, use the following command –" }, { "code": null, "e": 4434, "s": 4415, "text": "$ unzip master.zip" }, { "code": null, "e": 4474, "s": 4434, "text": "The sample output should be like this –" }, { "code": null, "e": 5149, "s": 4474, "text": "Archive: master.zip\n344e77462f8bab208f776b29bbcf63778aabd7af\ncreating: lolcat-master/\nextracting: lolcat-master/.gitignore\ninflating: lolcat-master/Gemfile\ninflating: lolcat-master/LICENSE\ninflating: lolcat-master/README.md\nextracting: lolcat-master/Rakefile\ncreating: lolcat-master/ass/\ninflating: lolcat-master/ass/screenshot.png\ncreating: lolcat-master/bin/\ninflating: lolcat-master/bin/lolcat\ncreating: lolcat-master/lib/\ninflating: lolcat-master/lib/lolcat.rb\ncreating: lolcat-master/lib/lolcat/\ninflating: lolcat-master/lib/lolcat/cat.rb\ninflating: lolcat-master/lib/lolcat/lol.rb\nextracting: lolcat-master/lib/lolcat/version.rb\ninflating: lolcat-master/lolcat.gemspec" }, { "code": null, "e": 5220, "s": 5149, "text": "To enter into lolcat-master/bin directory, use the following command –" }, { "code": null, "e": 5243, "s": 5220, "text": "$ cd lolcat-master/bin" }, { "code": null, "e": 5293, "s": 5243, "text": "To install lolcat gem use the following command –" }, { "code": null, "e": 5314, "s": 5293, "text": "$ gem install lolcat" }, { "code": null, "e": 5354, "s": 5314, "text": "The sample output should be like this –" }, { "code": null, "e": 5381, "s": 5354, "text": "$ sudo gem install lolcat\n" }, { "code": null, "e": 5421, "s": 5381, "text": "The sample output should be like this –" }, { "code": null, "e": 5949, "s": 5421, "text": "Fetching: paint-1.0.1.gem (100%)\nFetching: trollop-2.1.2.gem (100%)\nFetching: lolcat-42.1.43.gem (100%)\nSuccessfully installed paint-1.0.1\nSuccessfully installed trollop-2.1.2\nSuccessfully installed lolcat-42.1.43\n3 gems installed\nInstalling ri documentation for paint-1.0.1...\nInstalling ri documentation for trollop-2.1.2...\nInstalling ri documentation for lolcat-42.1.43...\nInstalling RDoc documentation for paint-1.0.1...\nInstalling RDoc documentation for trollop-2.1.2...\nInstalling RDoc documentation for lolcat-42.1.43.." }, { "code": null, "e": 6000, "s": 5949, "text": "To get Lolcat version, use the following command –" }, { "code": null, "e": 6019, "s": 6000, "text": "$ lolcat --version" }, { "code": null, "e": 6059, "s": 6019, "text": "The sample output should be like this –" }, { "code": null, "e": 6099, "s": 6059, "text": "lolcat 42.1.43 (c)2011 moe@busyloop.net" }, { "code": null, "e": 6166, "s": 6099, "text": "To get the available option in lolcat, use the following command –" }, { "code": null, "e": 6178, "s": 6166, "text": "$ lolcat -h" }, { "code": null, "e": 6218, "s": 6178, "text": "The sample output should be like this –" }, { "code": null, "e": 6277, "s": 6218, "text": "To print the text with Lolcat, use the following command –" }, { "code": null, "e": 6355, "s": 6277, "text": "$ echo I love Tutorialspoint | lolcat\n$ figlet I love Tutorialspoint | lolcat" }, { "code": null, "e": 6395, "s": 6355, "text": "The sample output should be like this –" }, { "code": null, "e": 6456, "s": 6395, "text": "In the above command, please note that, we have used figlet." }, { "code": null, "e": 6503, "s": 6456, "text": "To install figlet, use the following command –" }, { "code": null, "e": 6533, "s": 6503, "text": "$ sudo apt-get install figlet" }, { "code": null, "e": 6593, "s": 6533, "text": "To install Lolcat with cowsay, use the following command –" }, { "code": null, "e": 6623, "s": 6593, "text": "$ sudo apt-get install cowsay" }, { "code": null, "e": 6663, "s": 6623, "text": "The sample output should be like this –" }, { "code": null, "e": 7797, "s": 6663, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\ngcc-4.8-base:i386 libasn1-8-heimdal:i386 libasound2:i386\nlibasound2-plugins:i386 libasyncns0:i386 libavahi-client3:i386\nlibavahi-common-data:i386 libavahi-common3:i386 libbit-vector-perl\nlibcapi20-3:i386 libcarp-clan-perl libclass-method-modifiers-perl\nlibcups2:i386 libdata-random-perl libdate-calc-perl libdate-calc-xs-perl\nlibdrm-amdgpu1:i386 libdrm-intel1:i386 libdrm-nouveau2:i386\nlibdrm-radeon1:i386 libedit2:i386 libelf1:i386 libexif12:i386 libexpat1:i386\nlibffi6:i386 libflac8:i386 libfontconfig1:i386 libfreetype6:i386\nlibgcrypt11:i386 libgd-perl libgd3:i386 libgif4:i386\nlibgl1-mesa-dri-lts-wily:i386 libgl1-mesa-glx-lts-wily:i386\nlibglapi-mesa-lts-wily:i386 libglib2.0-0:i386 libglu1-mesa:i386\nlibgnome2-gconf-perl libgnutls26:i386 libgpg-error0:i386 libgphoto2-6:i386\nlibgphoto2-port10:i386 libgssapi-krb5-2:i386 libgssapi3-heimdal:i386\nlibgstreamer-plugins-base0.10-0:i386 libgstreamer0.10-0:i386\n......................................................" }, { "code": null, "e": 7895, "s": 7797, "text": "cowsay command supports a lot of other visual graphical animals is shown in the following lines." }, { "code": null, "e": 7951, "s": 7895, "text": "To get the list of animals, use the following command –" }, { "code": null, "e": 7963, "s": 7951, "text": "$ cowsay -l" }, { "code": null, "e": 8003, "s": 7963, "text": "The sample output should be like this –" }, { "code": null, "e": 8465, "s": 8003, "text": "Cow files in /usr/share/cowsay/cows:\napt beavis.zen bong bud-frogs bunny calvin cheese cock cower daemon default\ndragon dragon-and-cow duck elephant elephant-in-snake eyes flaming-sheep\nghostbusters gnu head-in hellokitty kiss kitty koala kosh luke-koala\nmech-and-cow meow milk moofasa moose mutilated pony pony-smaller ren sheep\nskeleton snowman sodomized-sheep stegosaurus stimpy suse three-eyes turkey\nturtle tux unipony unipony-smaller vader vader-koala www" }, { "code": null, "e": 8540, "s": 8465, "text": "As an example, the below image of a pony was created using lolcat utility." }, { "code": null, "e": 8586, "s": 8540, "text": "Use the following command to get the output –" }, { "code": null, "e": 8634, "s": 8586, "text": "$ cowsay -f pony I love tutorialspoint | lolcat" }, { "code": null, "e": 8687, "s": 8634, "text": "The sample output will be something like the below –" }, { "code": null, "e": 8850, "s": 8687, "text": "Congratulations! Now, you know “How to use Rainbow Colors in Linux Terminal”. We’ll learn more about these types of commands in our next Linux post. Keep reading!" } ]
Find maximum pairwise sum in Linked List that are equidistant from front and back - GeeksforGeeks
17 Feb, 2022 Given a linked list lis of length N, where N is even. The task is to maximize the sum of two equidistant nodes from the front and back ends of the given linked list. Note: Two nodes (i and j) are equidistant from both ends if the distance of ith node from front is same as distance of jth node from back. Examples: Input: lis = {5, 4, 2, 1}Output: 6Explanation: The nodes with pairs present in this linked list are:Node 0 and node 3 are equidistant having a sum of 5 + 1 = 6.Node 1 and node 2 are equidistant having a sum of 4 + 2 = 6.Thus, the maximum sum of equidistant nodes of the linked list is max(6, 6) = 6. Input: lis = {4, 2, 2, 3}Output: 7Explanation: The nodes with pairs present in this linked list are:Node 0 and node 3 are equidistant having a sum of 4 + 3 = 7.Node 1 and node 2 are equidistant having a sum of 2 + 2 = 4.Thus, the maximum sum of equidistant nodes of the linked list is max(7, 4) = 7. Approach: The solution is based on dividing the linked list into two equal halves and then using two pointer approach. Follow the steps mentioned below to solve the problem: Get mid and separate the linked list into two parts. Reverse the second part, for traversing it in the forward direction. Traverse in both parts and get the maximum sum. Recover the Linked List Again, by connecting the parts again, for good practice. Below is the implementation of the above approach. C++ Java C# // C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Structure of a nodestruct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) { } ListNode(int x) : val(x), next(nullptr) { } ListNode(int x, ListNode* next) : val(x), next(next) { }}; // Function to add node in linked listvoid push(struct ListNode** head_ref, int new_data){ // Allocate node struct ListNode* new_node = new ListNode; // Put in the data new_node->val = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point the new node (*head_ref) = new_node;} // Function for reversing the linked listvoid reverse(ListNode** head){ ListNode *curr = *head, *prev = 0, *nxt; while (curr) nxt = curr->next, curr->next = prev, prev = curr, curr = nxt; *head = prev;} // Function to find the maximum sum// of equidistant elementsint pairSum(ListNode* head){ // Get mid and separate // the linked list into two parts ListNode *prev = 0, *slow = head, *fast = head; // Find mid while (fast and fast->next) prev = slow, slow = slow->next, fast = fast->next->next; // Separate them prev->next = 0; // Reverse the second part, // for traversing it // in forward direction reverse(&slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode *ptr1 = head, *ptr2 = slow; while (ptr1) sum = max(sum, (ptr1->val + ptr2->val)), ptr1 = ptr1->next, ptr2 = ptr2->next; // Recover the Linked List again, by // connection the parts again reverse(&slow); prev->next = slow; // Return sum return sum;} // Driver codeint main(){ struct ListNode* head = NULL; push(&head, 4); push(&head, 2); push(&head, 2); push(&head, 3); cout << pairSum(head); return 0;} // Java code to implement above approachclass GFG{ // Structure of a nodestatic class ListNode { int val; ListNode next; ListNode() { this(0); } ListNode(int x) { this.val = x; this.next = null; } ListNode(int x, ListNode next) { this.val = x; this.next = next; }}; // Function to add node in linked liststatic ListNode push(ListNode head_ref, int new_data){ // Allocate node ListNode new_node = new ListNode(); // Put in the data new_node.val = new_data; // Link the old list off the new node new_node.next = head_ref; // Move the head to point the new node head_ref = new_node; return head_ref;} // Function for reversing the linked liststatic ListNode reverse(ListNode head){ ListNode curr = head, prev = new ListNode(), nxt=new ListNode(); while (curr.next!=null) { nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } head = prev; return head;} // Function to find the maximum sum// of equidistant elementsstatic int pairSum(ListNode head){ // Get mid and separate // the linked list into two parts ListNode prev = new ListNode(), slow = head, fast = head; // Find mid while (fast!=null && fast.next!=null) { prev = slow; slow = slow.next; fast = fast.next.next; } // Separate them prev.next = new ListNode(); // Reverse the second part, // for traversing it // in forward direction slow = reverse(slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode ptr1 = head, ptr2 = slow; while (ptr1!=null) { sum = Math.max(sum, (ptr1.val + ptr2.val)); ptr1 = ptr1.next; ptr2 = ptr2.next; } // Recover the Linked List again, by // connection the parts again slow = reverse(slow); prev.next = slow; // Return sum return sum;} // Driver codepublic static void main(String[] args){ ListNode head = new ListNode(); head = push(head, 4); head = push(head, 2); head = push(head, 2); head = push(head, 3); System.out.print(pairSum(head));}} // This code is contributed by 29AjayKumar // C# code to implement above approachusing System; public class GFG{ // Structure of a node class ListNode { public int val; public ListNode next; public ListNode() { new ListNode(0); } public ListNode(int x) { this.val = x; this.next = null; } public ListNode(int x, ListNode next) { this.val = x; this.next = next; } }; // Function to add node in linked list static ListNode push(ListNode head_ref, int new_data) { // Allocate node ListNode new_node = new ListNode(); // Put in the data new_node.val = new_data; // Link the old list off the new node new_node.next = head_ref; // Move the head to point the new node head_ref = new_node; return head_ref; } // Function for reversing the linked list static ListNode reverse(ListNode head) { ListNode curr = head, prev = new ListNode(), nxt=new ListNode(); while (curr.next!=null) { nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } head = prev; return head; } // Function to find the maximum sum // of equidistant elements static int pairSum(ListNode head) { // Get mid and separate // the linked list into two parts ListNode prev = new ListNode(), slow = head, fast = head; // Find mid while (fast!=null && fast.next!=null) { prev = slow; slow = slow.next; fast = fast.next.next; } // Separate them prev.next = new ListNode(); // Reverse the second part, // for traversing it // in forward direction slow = reverse(slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode ptr1 = head, ptr2 = slow; while (ptr1!=null) { sum = Math.Max(sum, (ptr1.val + ptr2.val)); ptr1 = ptr1.next; ptr2 = ptr2.next; } // Recover the Linked List again, by // connection the parts again slow = reverse(slow); prev.next = slow; // Return sum return sum; } // Driver code public static void Main(String[] args) { ListNode head = new ListNode(); head = push(head, 4); head = push(head, 2); head = push(head, 2); head = push(head, 3); Console.Write(pairSum(head)); }} // This code is contributed by shikhasingrajput 7 Time Complexity: O(N)Auxiliary Space: O(1) 29AjayKumar shikhasingrajput nikhatkhan11 simranarora5sos Algo-Geek 2021 Reverse Algo Geek Divide and Conquer Greedy Linked List Linked List Greedy Divide and Conquer Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if the given string is valid English word or not Find One’s Complement of an Integer | Set 2 Encode given String by inserting in Matrix column-wise and printing it row-wise Lexicographically smallest string formed by concatenating any prefix and its mirrored form Sorting given character Array using Linked List Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Program for Tower of Hanoi
[ { "code": null, "e": 26248, "s": 26220, "text": "\n17 Feb, 2022" }, { "code": null, "e": 26414, "s": 26248, "text": "Given a linked list lis of length N, where N is even. The task is to maximize the sum of two equidistant nodes from the front and back ends of the given linked list." }, { "code": null, "e": 26553, "s": 26414, "text": "Note: Two nodes (i and j) are equidistant from both ends if the distance of ith node from front is same as distance of jth node from back." }, { "code": null, "e": 26563, "s": 26553, "text": "Examples:" }, { "code": null, "e": 26864, "s": 26563, "text": "Input: lis = {5, 4, 2, 1}Output: 6Explanation: The nodes with pairs present in this linked list are:Node 0 and node 3 are equidistant having a sum of 5 + 1 = 6.Node 1 and node 2 are equidistant having a sum of 4 + 2 = 6.Thus, the maximum sum of equidistant nodes of the linked list is max(6, 6) = 6. " }, { "code": null, "e": 27165, "s": 26864, "text": "Input: lis = {4, 2, 2, 3}Output: 7Explanation: The nodes with pairs present in this linked list are:Node 0 and node 3 are equidistant having a sum of 4 + 3 = 7.Node 1 and node 2 are equidistant having a sum of 2 + 2 = 4.Thus, the maximum sum of equidistant nodes of the linked list is max(7, 4) = 7. " }, { "code": null, "e": 27339, "s": 27165, "text": "Approach: The solution is based on dividing the linked list into two equal halves and then using two pointer approach. Follow the steps mentioned below to solve the problem:" }, { "code": null, "e": 27392, "s": 27339, "text": "Get mid and separate the linked list into two parts." }, { "code": null, "e": 27461, "s": 27392, "text": "Reverse the second part, for traversing it in the forward direction." }, { "code": null, "e": 27509, "s": 27461, "text": "Traverse in both parts and get the maximum sum." }, { "code": null, "e": 27590, "s": 27509, "text": "Recover the Linked List Again, by connecting the parts again, for good practice." }, { "code": null, "e": 27641, "s": 27590, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27645, "s": 27641, "text": "C++" }, { "code": null, "e": 27650, "s": 27645, "text": "Java" }, { "code": null, "e": 27653, "s": 27650, "text": "C#" }, { "code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Structure of a nodestruct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) { } ListNode(int x) : val(x), next(nullptr) { } ListNode(int x, ListNode* next) : val(x), next(next) { }}; // Function to add node in linked listvoid push(struct ListNode** head_ref, int new_data){ // Allocate node struct ListNode* new_node = new ListNode; // Put in the data new_node->val = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point the new node (*head_ref) = new_node;} // Function for reversing the linked listvoid reverse(ListNode** head){ ListNode *curr = *head, *prev = 0, *nxt; while (curr) nxt = curr->next, curr->next = prev, prev = curr, curr = nxt; *head = prev;} // Function to find the maximum sum// of equidistant elementsint pairSum(ListNode* head){ // Get mid and separate // the linked list into two parts ListNode *prev = 0, *slow = head, *fast = head; // Find mid while (fast and fast->next) prev = slow, slow = slow->next, fast = fast->next->next; // Separate them prev->next = 0; // Reverse the second part, // for traversing it // in forward direction reverse(&slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode *ptr1 = head, *ptr2 = slow; while (ptr1) sum = max(sum, (ptr1->val + ptr2->val)), ptr1 = ptr1->next, ptr2 = ptr2->next; // Recover the Linked List again, by // connection the parts again reverse(&slow); prev->next = slow; // Return sum return sum;} // Driver codeint main(){ struct ListNode* head = NULL; push(&head, 4); push(&head, 2); push(&head, 2); push(&head, 3); cout << pairSum(head); return 0;}", "e": 29688, "s": 27653, "text": null }, { "code": "// Java code to implement above approachclass GFG{ // Structure of a nodestatic class ListNode { int val; ListNode next; ListNode() { this(0); } ListNode(int x) { this.val = x; this.next = null; } ListNode(int x, ListNode next) { this.val = x; this.next = next; }}; // Function to add node in linked liststatic ListNode push(ListNode head_ref, int new_data){ // Allocate node ListNode new_node = new ListNode(); // Put in the data new_node.val = new_data; // Link the old list off the new node new_node.next = head_ref; // Move the head to point the new node head_ref = new_node; return head_ref;} // Function for reversing the linked liststatic ListNode reverse(ListNode head){ ListNode curr = head, prev = new ListNode(), nxt=new ListNode(); while (curr.next!=null) { nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } head = prev; return head;} // Function to find the maximum sum// of equidistant elementsstatic int pairSum(ListNode head){ // Get mid and separate // the linked list into two parts ListNode prev = new ListNode(), slow = head, fast = head; // Find mid while (fast!=null && fast.next!=null) { prev = slow; slow = slow.next; fast = fast.next.next; } // Separate them prev.next = new ListNode(); // Reverse the second part, // for traversing it // in forward direction slow = reverse(slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode ptr1 = head, ptr2 = slow; while (ptr1!=null) { sum = Math.max(sum, (ptr1.val + ptr2.val)); ptr1 = ptr1.next; ptr2 = ptr2.next; } // Recover the Linked List again, by // connection the parts again slow = reverse(slow); prev.next = slow; // Return sum return sum;} // Driver codepublic static void main(String[] args){ ListNode head = new ListNode(); head = push(head, 4); head = push(head, 2); head = push(head, 2); head = push(head, 3); System.out.print(pairSum(head));}} // This code is contributed by 29AjayKumar", "e": 31939, "s": 29688, "text": null }, { "code": "// C# code to implement above approachusing System; public class GFG{ // Structure of a node class ListNode { public int val; public ListNode next; public ListNode() { new ListNode(0); } public ListNode(int x) { this.val = x; this.next = null; } public ListNode(int x, ListNode next) { this.val = x; this.next = next; } }; // Function to add node in linked list static ListNode push(ListNode head_ref, int new_data) { // Allocate node ListNode new_node = new ListNode(); // Put in the data new_node.val = new_data; // Link the old list off the new node new_node.next = head_ref; // Move the head to point the new node head_ref = new_node; return head_ref; } // Function for reversing the linked list static ListNode reverse(ListNode head) { ListNode curr = head, prev = new ListNode(), nxt=new ListNode(); while (curr.next!=null) { nxt = curr.next; curr.next = prev; prev = curr; curr = nxt; } head = prev; return head; } // Function to find the maximum sum // of equidistant elements static int pairSum(ListNode head) { // Get mid and separate // the linked list into two parts ListNode prev = new ListNode(), slow = head, fast = head; // Find mid while (fast!=null && fast.next!=null) { prev = slow; slow = slow.next; fast = fast.next.next; } // Separate them prev.next = new ListNode(); // Reverse the second part, // for traversing it // in forward direction slow = reverse(slow); // Traverse in both parts and // get the maximum sum int sum = 0; ListNode ptr1 = head, ptr2 = slow; while (ptr1!=null) { sum = Math.Max(sum, (ptr1.val + ptr2.val)); ptr1 = ptr1.next; ptr2 = ptr2.next; } // Recover the Linked List again, by // connection the parts again slow = reverse(slow); prev.next = slow; // Return sum return sum; } // Driver code public static void Main(String[] args) { ListNode head = new ListNode(); head = push(head, 4); head = push(head, 2); head = push(head, 2); head = push(head, 3); Console.Write(pairSum(head)); }} // This code is contributed by shikhasingrajput", "e": 34254, "s": 31939, "text": null }, { "code": null, "e": 34256, "s": 34254, "text": "7" }, { "code": null, "e": 34299, "s": 34256, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 34311, "s": 34299, "text": "29AjayKumar" }, { "code": null, "e": 34328, "s": 34311, "text": "shikhasingrajput" }, { "code": null, "e": 34341, "s": 34328, "text": "nikhatkhan11" }, { "code": null, "e": 34357, "s": 34341, "text": "simranarora5sos" }, { "code": null, "e": 34372, "s": 34357, "text": "Algo-Geek 2021" }, { "code": null, "e": 34380, "s": 34372, "text": "Reverse" }, { "code": null, "e": 34390, "s": 34380, "text": "Algo Geek" }, { "code": null, "e": 34409, "s": 34390, "text": "Divide and Conquer" }, { "code": null, "e": 34416, "s": 34409, "text": "Greedy" }, { "code": null, "e": 34428, "s": 34416, "text": "Linked List" }, { "code": null, "e": 34440, "s": 34428, "text": "Linked List" }, { "code": null, "e": 34447, "s": 34440, "text": "Greedy" }, { "code": null, "e": 34466, "s": 34447, "text": "Divide and Conquer" }, { "code": null, "e": 34474, "s": 34466, "text": "Reverse" }, { "code": null, "e": 34572, "s": 34474, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34581, "s": 34572, "text": "Comments" }, { "code": null, "e": 34594, "s": 34581, "text": "Old Comments" }, { "code": null, "e": 34649, "s": 34594, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 34693, "s": 34649, "text": "Find One’s Complement of an Integer | Set 2" }, { "code": null, "e": 34773, "s": 34693, "text": "Encode given String by inserting in Matrix column-wise and printing it row-wise" }, { "code": null, "e": 34864, "s": 34773, "text": "Lexicographically smallest string formed by concatenating any prefix and its mirrored form" }, { "code": null, "e": 34912, "s": 34864, "text": "Sorting given character Array using Linked List" }, { "code": null, "e": 34923, "s": 34912, "text": "Merge Sort" }, { "code": null, "e": 34933, "s": 34923, "text": "QuickSort" }, { "code": null, "e": 34947, "s": 34933, "text": "Binary Search" }, { "code": null, "e": 35015, "s": 34947, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
DB2 - Bufferpools
This chapter introduces you to Bufferpools in the database. The bufferpool is portion of a main memory space which is allocated by the database manager. The purpose of bufferpools is to cache table and index data from disk. All databases have their own bufferpools. A default bufferpool is created at the time of creation of new database. It called as “IBMDEFAULTBP”. Depending on the user requirements, it is possible to create a number of bufferpools. In the bufferpool, the database manager places the table row data as a page. This page stays in the bufferpool until the database is shutdown or until the space is written with new data. The pages in the bufferpool, which are updated with data but are not written onto the disk, are called “Dirty” pages. After the updated data pages in the bufferpool are written on the disk, the bufferpool is ready to take another data. Each table space is associated with a specific buffer pool in a database. One tablespace is associated with one bufferpool. The size of bufferpool and tablespace must be same. Multiple bufferpools allow you to configure the memory used by the database to increase its overall performance. The size of the bufferpool page is set when you use the “CREATE DATABASE” command. If you do not specify the page size, it will take default page size, which is 4KB. Once the bufferpool is created, it is not possible to modify the page size later Syntax: [The syntax below shows all available bufferpools in database] db2 select * from syscat.bufferpools Example: [To see available bufferpools in current database] db2 select * from syscat.bufferpools Output: BPNAME BUFFERPOOLID DBPGNAME NPAGES PAGESIZE ESTORE NUMBLOCKPAGES BLOCKSIZE NGNAME ------------------------------------------------------------ IBMDEFAULTBP 1 - -2 4096 N 0 0 - 1 record(s) selected. To create a new bufferpool for database server, you need two parameters namely, “bufferpool name” and “size of page”. The following query is executed to create a new bufferpool. Syntax: [In the syntax below,‘bp_name’ indicates bufferpool name and ‘size’ indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)] db2 create bufferpool <bp_name> pagesize <size> Example: [To create a new bufferpool with name “bpnew” and size “8192”(8Kb).] db2 create bufferpool bpnew pagesize 8192 Output DB20000I The SQL command completed successfully. Before dropping the bufferpool, it is required to check if any tablespace is assigned to it. Syntax: [To drop the bufferpool] drop bufferpool <bp_name> Example: [To drop ‘bpnew’ named bufferpool] db2 drop bufferpool bpnew Output DB20000I The SQL command completed successfully. 10 Lectures 1.5 hours Nishant Malik 41 Lectures 8.5 hours Parth Panjabi 53 Lectures 11.5 hours Parth Panjabi 33 Lectures 7 hours Parth Panjabi 44 Lectures 3 hours Arnab Chakraborty 178 Lectures 14.5 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 1988, "s": 1928, "text": "This chapter introduces you to Bufferpools in the database." }, { "code": null, "e": 2805, "s": 1988, "text": "The bufferpool is portion of a main memory space which is allocated by the database manager. The purpose of bufferpools is to cache table and index data from disk. All databases have their own bufferpools. A default bufferpool is created at the time of creation of new database. It called as “IBMDEFAULTBP”. Depending on the user requirements, it is possible to create a number of bufferpools. In the bufferpool, the database manager places the table row data as a page. This page stays in the bufferpool until the database is shutdown or until the space is written with new data. The pages in the bufferpool, which are updated with data but are not written onto the disk, are called “Dirty” pages. After the updated data pages in the bufferpool are written on the disk, the bufferpool is ready to take another data." }, { "code": null, "e": 3094, "s": 2805, "text": "Each table space is associated with a specific buffer pool in a database. One tablespace is associated with one bufferpool. The size of bufferpool and tablespace must be same. Multiple bufferpools allow you to configure the memory used by the database to increase its overall performance." }, { "code": null, "e": 3341, "s": 3094, "text": "The size of the bufferpool page is set when you use the “CREATE DATABASE” command. If you do not specify the page size, it will take default page size, which is 4KB. Once the bufferpool is created, it is not possible to modify the page size later" }, { "code": null, "e": 3412, "s": 3341, "text": "Syntax: [The syntax below shows all available bufferpools in database]" }, { "code": null, "e": 3452, "s": 3412, "text": "db2 select * from syscat.bufferpools " }, { "code": null, "e": 3512, "s": 3452, "text": "Example: [To see available bufferpools in current database]" }, { "code": null, "e": 3551, "s": 3512, "text": "db2 select * from syscat.bufferpools " }, { "code": null, "e": 3559, "s": 3551, "text": "Output:" }, { "code": null, "e": 4034, "s": 3559, "text": "BPNAME BUFFERPOOLID DBPGNAME NPAGES PAGESIZE ESTORE \nNUMBLOCKPAGES BLOCKSIZE NGNAME\n------------------------------------------------------------ \nIBMDEFAULTBP \n 1 - \n -2 4096 N 0 0 - \n \n 1 record(s) selected. " }, { "code": null, "e": 4213, "s": 4034, "text": "To create a new bufferpool for database server, you need two parameters namely, “bufferpool name” and “size of page”. The following query is executed to create a new bufferpool." }, { "code": null, "e": 4366, "s": 4213, "text": "Syntax: [In the syntax below,‘bp_name’ indicates bufferpool name and ‘size’ indicates size for page you need to declare for bufferpools (4K,8K,16K,32K)]" }, { "code": null, "e": 4415, "s": 4366, "text": "db2 create bufferpool <bp_name> pagesize <size> " }, { "code": null, "e": 4493, "s": 4415, "text": "Example: [To create a new bufferpool with name “bpnew” and size “8192”(8Kb).]" }, { "code": null, "e": 4537, "s": 4493, "text": "db2 create bufferpool bpnew pagesize 8192 " }, { "code": null, "e": 4544, "s": 4537, "text": "Output" }, { "code": null, "e": 4595, "s": 4544, "text": "DB20000I The SQL command completed successfully. " }, { "code": null, "e": 4688, "s": 4595, "text": "Before dropping the bufferpool, it is required to check if any tablespace is assigned to it." }, { "code": null, "e": 4721, "s": 4688, "text": "Syntax: [To drop the bufferpool]" }, { "code": null, "e": 4749, "s": 4721, "text": "drop bufferpool <bp_name> " }, { "code": null, "e": 4793, "s": 4749, "text": "Example: [To drop ‘bpnew’ named bufferpool]" }, { "code": null, "e": 4821, "s": 4793, "text": "db2 drop bufferpool bpnew " }, { "code": null, "e": 4828, "s": 4821, "text": "Output" }, { "code": null, "e": 4879, "s": 4828, "text": "DB20000I The SQL command completed successfully. " }, { "code": null, "e": 4914, "s": 4879, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4929, "s": 4914, "text": " Nishant Malik" }, { "code": null, "e": 4964, "s": 4929, "text": "\n 41 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4979, "s": 4964, "text": " Parth Panjabi" }, { "code": null, "e": 5015, "s": 4979, "text": "\n 53 Lectures \n 11.5 hours \n" }, { "code": null, "e": 5030, "s": 5015, "text": " Parth Panjabi" }, { "code": null, "e": 5063, "s": 5030, "text": "\n 33 Lectures \n 7 hours \n" }, { "code": null, "e": 5078, "s": 5063, "text": " Parth Panjabi" }, { "code": null, "e": 5111, "s": 5078, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 5130, "s": 5111, "text": " Arnab Chakraborty" }, { "code": null, "e": 5167, "s": 5130, "text": "\n 178 Lectures \n 14.5 hours \n" }, { "code": null, "e": 5186, "s": 5167, "text": " Arnab Chakraborty" }, { "code": null, "e": 5193, "s": 5186, "text": " Print" }, { "code": null, "e": 5204, "s": 5193, "text": " Add Notes" } ]
Clojure - Case Statement
Clojure offers the ‘case’ statement which is similar to the ‘switch’ statement available in the Java programming language. Following is the general form of the case statement. case expression value1 statement #1 value2 statement #2 valueN statement #N statement #Default The general working of this statement is as follows − The expression to be evaluated is placed in the ‘case’ statement. This generally will evaluate to a value, which is used in the subsequent statements. The expression to be evaluated is placed in the ‘case’ statement. This generally will evaluate to a value, which is used in the subsequent statements. Each value is evaluated against that which is passed by the ‘case’ expression. Depending on which value holds true, subsequent statement will be executed. Each value is evaluated against that which is passed by the ‘case’ expression. Depending on which value holds true, subsequent statement will be executed. There is also a default statement which gets executed if none of the prior values evaluate to be true. There is also a default statement which gets executed if none of the prior values evaluate to be true. Following diagram shows the flow of the ‘if’ statement. Following is an example of the ‘case’ statement in Clojure. (ns clojure.examples.hello (:gen-class)) ;; This program displays Hello World (defn Example [] (def x 5) (case x 5 (println "x is 5") 10 (println "x is 10") (println "x is neither 5 nor 10"))) (Example) In the above example, we are first initializing a variable ‘x’ to a value of 5. We then have a ‘case’ statement which evaluates the value of the variable ‘x’. Based on the value of the variable, it will execute the relevant case set of statements. The last statement is the default statement, if none of the previous statements are executed. The above code produces the following output. x is 5 Print Add Notes Bookmark this page
[ { "code": null, "e": 2550, "s": 2374, "text": "Clojure offers the ‘case’ statement which is similar to the ‘switch’ statement available in the Java programming language. Following is the general form of the case statement." }, { "code": null, "e": 2646, "s": 2550, "text": "case expression\nvalue1 statement #1\nvalue2 statement #2\nvalueN statement #N\nstatement #Default\n" }, { "code": null, "e": 2700, "s": 2646, "text": "The general working of this statement is as follows −" }, { "code": null, "e": 2851, "s": 2700, "text": "The expression to be evaluated is placed in the ‘case’ statement. This generally will evaluate to a value, which is used in the subsequent statements." }, { "code": null, "e": 3002, "s": 2851, "text": "The expression to be evaluated is placed in the ‘case’ statement. This generally will evaluate to a value, which is used in the subsequent statements." }, { "code": null, "e": 3157, "s": 3002, "text": "Each value is evaluated against that which is passed by the ‘case’ expression. Depending on which value holds true, subsequent statement will be executed." }, { "code": null, "e": 3312, "s": 3157, "text": "Each value is evaluated against that which is passed by the ‘case’ expression. Depending on which value holds true, subsequent statement will be executed." }, { "code": null, "e": 3415, "s": 3312, "text": "There is also a default statement which gets executed if none of the prior values evaluate to be true." }, { "code": null, "e": 3518, "s": 3415, "text": "There is also a default statement which gets executed if none of the prior values evaluate to be true." }, { "code": null, "e": 3574, "s": 3518, "text": "Following diagram shows the flow of the ‘if’ statement." }, { "code": null, "e": 3634, "s": 3574, "text": "Following is an example of the ‘case’ statement in Clojure." }, { "code": null, "e": 3860, "s": 3634, "text": "(ns clojure.examples.hello\n (:gen-class))\n\n;; This program displays Hello World\n(defn Example []\n (def x 5) \n (case x 5 (println \"x is 5\")\n 10 (println \"x is 10\")\n (println \"x is neither 5 nor 10\")))\n(Example)" }, { "code": null, "e": 4202, "s": 3860, "text": "In the above example, we are first initializing a variable ‘x’ to a value of 5. We then have a ‘case’ statement which evaluates the value of the variable ‘x’. Based on the value of the variable, it will execute the relevant case set of statements. The last statement is the default statement, if none of the previous statements are executed." }, { "code": null, "e": 4248, "s": 4202, "text": "The above code produces the following output." }, { "code": null, "e": 4256, "s": 4248, "text": "x is 5\n" }, { "code": null, "e": 4263, "s": 4256, "text": " Print" }, { "code": null, "e": 4274, "s": 4263, "text": " Add Notes" } ]
How to read JSON file in Python
JSON stands for JavaScript Object Notation. It is commonly used for transmitting data in web applications( such as sending data from server to client to display on the web pages). Example 1: { "fruit": "Apple", "size": "Large", "color": "Red" } Example 2: { 'name': 'Karan', 'languages': ['English', 'French'] } The json file will have .json extension Python has an in-built package called json which can be used to work with JSON data and to read JSON files. The json module has many functions among which load() and loads() are used to read the json files. load() − This function is used to parse or read a json file. loads() − This function is used to parse a json string. To use json module in python, we need to import it first. The json module is imported as follows − import json Suppose we have json file named “persons.json” with contents as shown in Example 2 above. We want to open and read it using python. This can be done in following steps − Import json module Import json module Open the file using the name of the json file witn open() function Open the file using the name of the json file witn open() function Open the file using the name of the json file witn open() function Open the file using the name of the json file witn open() function Read the json file using load() and put the json data into a variable. Read the json file using load() and put the json data into a variable. Use the data retrieved from the file or simply print it as in this case for simplicty. Use the data retrieved from the file or simply print it as in this case for simplicty. import json with open('persons.json') as f: data = json.load(f) print(data) {'name': 'Karan', 'languages': ['English', 'French']} Note: Make sure the json file is saved with .json extension on your system. Make sure the json file is saved with .json extension on your system. Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised. Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised.
[ { "code": null, "e": 1242, "s": 1062, "text": "JSON stands for JavaScript Object Notation. It is commonly used for transmitting data in web applications( such as sending data from server to client to display on the web pages)." }, { "code": null, "e": 1316, "s": 1242, "text": "Example 1:\n{\n \"fruit\": \"Apple\",\n \"size\": \"Large\",\n \"color\": \"Red\"\n}" }, { "code": null, "e": 1389, "s": 1316, "text": "Example 2:\n{\n 'name': 'Karan',\n 'languages': ['English', 'French']\n}" }, { "code": null, "e": 1429, "s": 1389, "text": "The json file will have .json extension" }, { "code": null, "e": 1636, "s": 1429, "text": "Python has an in-built package called json which can be used to work with JSON data and to read JSON files. The json module has many functions among which load() and loads() are used to read the json files." }, { "code": null, "e": 1697, "s": 1636, "text": "load() − This function is used to parse or read a json file." }, { "code": null, "e": 1753, "s": 1697, "text": "loads() − This function is used to parse a json string." }, { "code": null, "e": 1852, "s": 1753, "text": "To use json module in python, we need to import it first. The json module is imported as follows −" }, { "code": null, "e": 1864, "s": 1852, "text": "import json" }, { "code": null, "e": 2034, "s": 1864, "text": "Suppose we have json file named “persons.json” with contents as shown in Example 2 above. We want to open and read it using python. This can be done in following steps −" }, { "code": null, "e": 2053, "s": 2034, "text": "Import json module" }, { "code": null, "e": 2072, "s": 2053, "text": "Import json module" }, { "code": null, "e": 2139, "s": 2072, "text": "Open the file using the name of the json file witn open() function" }, { "code": null, "e": 2206, "s": 2139, "text": "Open the file using the name of the json file witn open() function" }, { "code": null, "e": 2273, "s": 2206, "text": "Open the file using the name of the json file witn open() function" }, { "code": null, "e": 2340, "s": 2273, "text": "Open the file using the name of the json file witn open() function" }, { "code": null, "e": 2411, "s": 2340, "text": "Read the json file using load() and put the json data into a variable." }, { "code": null, "e": 2482, "s": 2411, "text": "Read the json file using load() and put the json data into a variable." }, { "code": null, "e": 2569, "s": 2482, "text": "Use the data retrieved from the file or simply print it as in this case for simplicty." }, { "code": null, "e": 2656, "s": 2569, "text": "Use the data retrieved from the file or simply print it as in this case for simplicty." }, { "code": null, "e": 2737, "s": 2656, "text": "import json\n\nwith open('persons.json') as f:\n data = json.load(f)\n\nprint(data)" }, { "code": null, "e": 2791, "s": 2737, "text": "{'name': 'Karan', 'languages': ['English', 'French']}" }, { "code": null, "e": 2797, "s": 2791, "text": "Note:" }, { "code": null, "e": 2867, "s": 2797, "text": "Make sure the json file is saved with .json extension on your system." }, { "code": null, "e": 2937, "s": 2867, "text": "Make sure the json file is saved with .json extension on your system." }, { "code": null, "e": 3067, "s": 2937, "text": "Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised." }, { "code": null, "e": 3197, "s": 3067, "text": "Make sure the json file and the python program are saved in the same directory on your system, else an exception would be raised." } ]
How to pass an object as a parameter in JavaScript function?
To pass an object as a parameter in JavaScript, use this and prototype. You can try to run the following code to learn how to pass an object − <html> <head> <script> var func = function(param1) { this.param1 = param1; }; func.prototype.display = function() { return this.param1; }; function display(val) { document.write(val()); } var res = new func(99); display(res.display.bind(res)); </script> </head> </html>
[ { "code": null, "e": 1205, "s": 1062, "text": "To pass an object as a parameter in JavaScript, use this and prototype. You can try to run the following code to learn how to pass an object −" }, { "code": null, "e": 1602, "s": 1205, "text": "<html>\n <head>\n <script>\n var func = function(param1) {\n this.param1 = param1;\n };\n func.prototype.display = function() {\n return this.param1;\n };\n function display(val) {\n document.write(val());\n }\n var res = new func(99);\n\n display(res.display.bind(res));\n </script>\n </head>\n</html>" } ]
LMNs- Algorithms - GeeksforGeeks
28 Jun, 2021 Analyze an algorithm 1) Worst Case Analysis (Usually Done):In the worst case analysis, we calculate upper bound on running time of an algorithm by considering worst case (a situation where algorithm takes maximum time)2) Average Case Analysis (Sometimes done) :In average case analysis, we take all possible inputs and calculate computing time for all of the inputs.3) Best Case Analysis (Bogus) :In the best case analysis, we calculate lower bound on running time of an algorithm. Asymptotic Notations Θ Notation:The theta notation bounds a functions from above and below, so it defines exact asymptotic behavior. Θ((g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that 0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0} Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above. O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <= f(n) <= cg(n) for all n >= n0} Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound. Ω (g(n)) = {f(n): there exist positive constants c and n0 such that 0 <= cg(n) <= f(n) for all n >= n0}. Solving recurrences Substitution Method: We make a guess for the solution and then we use mathematical induction to prove the guess is correct or incorrect. Recurrence Tree Method: We draw a recurrence tree and calculate the time taken by every level of tree. Finally, we sum the work done at all levels. Master theorem Method: Only for following type of recurrences or for recurrences that can be transformed to following type. T(n) = aT(n/b) + f(n) where a >= 1 and b > 1 Sorting Searching Trees Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. Depth First Traversals: (a) Inorder (b) Preorder (c) Postorder Important Tree Properties and Formulas Binary Search Tree Binary Search Tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. There must be no duplicate nodes. InsertionDeletion Insertion Deletion AVL Tree AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. InsertionDeletion Insertion Deletion B-Tree B-Tree is a self-balancing search tree. In most of the other self-balancing search trees (like AVL and Red Black Trees), it is assumed that everything is in main memory. To understand use of B-Trees, we must think of huge amount of data that cannot fit in main memory. When the number of keys is high, the data is read from disk in the form of blocks. Disk access time is very high compared to main memory access time. The main idea of using B-Trees is to reduce the number of disk accesses.Properties of B-Tree B-Tree InsertionB-Tree Deletion B-Tree Insertion B-Tree Deletion Graph Graph is a data structure that consists of following two components:1. A finite set of vertices also called as nodes.2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same as (v, u) in case of directed graph(di-graph). The pair of form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost. Following two are the most commonly used representations of graph. Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph.Adjacency List : An array of linked lists is used. Size of the array is equal to number of vertices. Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Adjacency List : An array of linked lists is used. Size of the array is equal to number of vertices. Graph Algorithms Some Interesting Graph Questions Minimum Spanning Tree Minimum Spanning Tree (MST) problem: Given connected graph G with positive edge weights, find a min weight set of edges that connects all of the vertices. MST is fundamental problem with diverse applications. Network design– telephone, electrical, hydraulic, TV cable, computer, road Network design– telephone, electrical, hydraulic, TV cable, computer, road Approximation algorithms for NP-hard problems – traveling salesperson problem, Steiner tree Approximation algorithms for NP-hard problems – traveling salesperson problem, Steiner tree Cluster analysis- k clustering problem can be viewed as finding an MST and deleting the k-1 most expensive edges. Cluster analysis- k clustering problem can be viewed as finding an MST and deleting the k-1 most expensive edges. Example: Prim’s Minimum Spanning Tree Algorithm, Kruskal’s Minimum Spanning Tree Algorithm Divide and Conquer Divide:Break the given problem into subproblems of same type.Conquer: Recursively solve these subproblemsCombine: Appropriately combine the answers Divide:Break the given problem into subproblems of same type. Conquer: Recursively solve these subproblems Combine: Appropriately combine the answers Following are some standard algorithms that are Divide and Conquer algorithms.1) Binary Search is a searching algorithm. In each step, the algorithm compares the input element x with the value of the middle element in array. If the values match, return the index of middle. Otherwise, if x is less than the middle element, then the algorithm recurs for left side of middle element, else recurs for right side of middle element.2) Quicksort is a sorting algorithm. The algorithm picks a pivot element, rearranges the array elements in such a way that all elements smaller than the picked pivot element move to left side of pivot, and all greater elements move to right side. Finally, the algorithm recursively sorts the subarrays on left and right of pivot element.3) Merge Sort is also a sorting algorithm. The algorithm divides the array in two halves, recursively sorts them and finally merges the two sorted halves.4) Closest Pair of Points The problem is to find the closest pair of points in a set of points in x-y plane. The problem can be solved in O(n^2) time by calculating distances of every pair of points and comparing the distances to find the minimum. The Divide and Conquer algorithm solves the problem in O(nLogn) time. Greedy Approach Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. Following are some standard algorithms that are Greedy algorithms.1) Kruskal’s Minimum Spanning Tree (MST): In Kruskal’s algorithm, we create a MST by picking edges one by one. The Greedy Choice is to pick the smallest weight edge that doesn’t cause a cycle in the MST constructed so far.2) Prim’s Minimum Spanning Tree: In Prim’s algorithm also, we create a MST by picking edges one by one. We maintain two sets: set of the vertices already included in MST and the set of the vertices not yet included. The Greedy Choice is to pick the smallest weight edge that connects the two sets.3) Dijkstra’s Shortest Path: The Dijkstra’s algorithm is very similar to Prim’s algorithm. The shortest path tree is built up, edge by edge. We maintain two sets: set of the vertices already included in the tree and the set of the vertices not yet included. The Greedy Choice is to pick the edge that connects the two sets and is on the smallest weight path from source to the set that contains not yet included vertices.4) Huffman Coding: Huffman Coding is a loss-less compression technique. It assigns variable length bit codes to different characters. The Greedy Choice is to assign least bit length code to the most frequent character. Dynamic Programming Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. Properties: Overlapping Subproblems: Dynamic Programming is mainly used when solutions of same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these don’t have to be recomputed. Overlapping Subproblems: Dynamic Programming is mainly used when solutions of same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these don’t have to be recomputed. Uses: Fibonacci Numbers Optimal Substructure: A given problems has Optimal Substructure Property if optimal solution of the given problem can be obtained by using optimal solutions of its subproblems. Optimal Substructure: A given problems has Optimal Substructure Property if optimal solution of the given problem can be obtained by using optimal solutions of its subproblems. Uses: Longest Increasing Subsequence, Shortest Path Two Approaches: Memoization (Top Down)Tabulation (Bottom Up) Memoization (Top Down) Tabulation (Bottom Up) Examples: Floyd Warshall Algorithm, Bellman–Ford Algorithm for Shortest Paths BackTracking Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items .Meaning of item varies from problem to problem. Example: Hamiltonian Cycle Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Software Testing - Web Based Testing What are the different ways of Data Representation? Bash Script - Command Substitution SDE SHEET - A Complete Guide for SDE Preparation 7 Highest Paying Programming Languages For Freelancers in 2022 DSA Sheet by Love Babbar How to Create a Shell Script in linux How To Convert Numpy Array To Tensor? 7 Best React Project Ideas For Beginners in 2022
[ { "code": null, "e": 29577, "s": 29549, "text": "\n28 Jun, 2021" }, { "code": null, "e": 29598, "s": 29577, "text": "Analyze an algorithm" }, { "code": null, "e": 30060, "s": 29598, "text": "1) Worst Case Analysis (Usually Done):In the worst case analysis, we calculate upper bound on running time of an algorithm by considering worst case (a situation where algorithm takes maximum time)2) Average Case Analysis (Sometimes done) :In average case analysis, we take all possible inputs and calculate computing time for all of the inputs.3) Best Case Analysis (Bogus) :In the best case analysis, we calculate lower bound on running time of an algorithm." }, { "code": null, "e": 30081, "s": 30060, "text": "Asymptotic Notations" }, { "code": null, "e": 30193, "s": 30081, "text": "Θ Notation:The theta notation bounds a functions from above and below, so it defines exact asymptotic behavior." }, { "code": null, "e": 30315, "s": 30193, "text": "Θ((g(n)) = {f(n): there exist positive constants c1, c2 and n0 such that\n0 <= c1*g(n) <= f(n) <= c2*g(n) for all n >= n0}" }, { "code": null, "e": 30428, "s": 30315, "text": "Big O Notation: The Big O notation defines an upper bound of an algorithm, it bounds a function only from above." }, { "code": null, "e": 30538, "s": 30428, "text": "O(g(n)) = { f(n): there exist positive constants c and n0 such that\n 0 <= f(n) <= cg(n) for all n >= n0}" }, { "code": null, "e": 30670, "s": 30538, "text": "Ω Notation: Just as Big O notation provides an asymptotic upper bound on a function, Ω notation provides an asymptotic lower bound." }, { "code": null, "e": 30776, "s": 30670, "text": "Ω (g(n)) = {f(n): there exist positive constants c and n0 such that\n 0 <= cg(n) <= f(n) for all n >= n0}." }, { "code": null, "e": 30796, "s": 30776, "text": "Solving recurrences" }, { "code": null, "e": 30933, "s": 30796, "text": "Substitution Method: We make a guess for the solution and then we use mathematical induction to prove the guess is correct or incorrect." }, { "code": null, "e": 31081, "s": 30933, "text": "Recurrence Tree Method: We draw a recurrence tree and calculate the time taken by every level of tree. Finally, we sum the work done at all levels." }, { "code": null, "e": 31205, "s": 31081, "text": "Master theorem Method: Only for following type of recurrences or for recurrences that can be transformed to following type." }, { "code": null, "e": 31250, "s": 31205, "text": "T(n) = aT(n/b) + f(n) where a >= 1 and b > 1" }, { "code": null, "e": 31258, "s": 31250, "text": "Sorting" }, { "code": null, "e": 31269, "s": 31258, "text": " Searching" }, { "code": null, "e": 31275, "s": 31269, "text": "Trees" }, { "code": null, "e": 31505, "s": 31275, "text": "Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures. Depth First Traversals: (a) Inorder (b) Preorder (c) Postorder Important Tree Properties and Formulas" }, { "code": null, "e": 31524, "s": 31505, "text": "Binary Search Tree" }, { "code": null, "e": 31623, "s": 31524, "text": "Binary Search Tree, is a node-based binary tree data structure which has the following properties:" }, { "code": null, "e": 31706, "s": 31623, "text": "The left subtree of a node contains only nodes with keys less than the node’s key." }, { "code": null, "e": 31793, "s": 31706, "text": "The right subtree of a node contains only nodes with keys greater than the node’s key." }, { "code": null, "e": 31894, "s": 31793, "text": "The left and right subtree each must also be a binary search tree. There must be no duplicate nodes." }, { "code": null, "e": 31912, "s": 31894, "text": "InsertionDeletion" }, { "code": null, "e": 31922, "s": 31912, "text": "Insertion" }, { "code": null, "e": 31931, "s": 31922, "text": "Deletion" }, { "code": null, "e": 31940, "s": 31931, "text": "AVL Tree" }, { "code": null, "e": 32097, "s": 31940, "text": "AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes." }, { "code": null, "e": 32115, "s": 32097, "text": "InsertionDeletion" }, { "code": null, "e": 32125, "s": 32115, "text": "Insertion" }, { "code": null, "e": 32134, "s": 32125, "text": "Deletion" }, { "code": null, "e": 32141, "s": 32134, "text": "B-Tree" }, { "code": null, "e": 32654, "s": 32141, "text": " B-Tree is a self-balancing search tree. In most of the other self-balancing search trees (like AVL and Red Black Trees), it is assumed that everything is in main memory. To understand use of B-Trees, we must think of huge amount of data that cannot fit in main memory. When the number of keys is high, the data is read from disk in the form of blocks. Disk access time is very high compared to main memory access time. The main idea of using B-Trees is to reduce the number of disk accesses.Properties of B-Tree" }, { "code": null, "e": 32686, "s": 32654, "text": "B-Tree InsertionB-Tree Deletion" }, { "code": null, "e": 32703, "s": 32686, "text": "B-Tree Insertion" }, { "code": null, "e": 32719, "s": 32703, "text": "B-Tree Deletion" }, { "code": null, "e": 32725, "s": 32719, "text": "Graph" }, { "code": null, "e": 33194, "s": 32725, "text": "Graph is a data structure that consists of following two components:1. A finite set of vertices also called as nodes.2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same as (v, u) in case of directed graph(di-graph). The pair of form (u, v) indicates that there is an edge from vertex u to vertex v. The edges may contain weight/value/cost. Following two are the most commonly used representations of graph." }, { "code": null, "e": 33403, "s": 33194, "text": "Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph.Adjacency List : An array of linked lists is used. Size of the array is equal to number of vertices." }, { "code": null, "e": 33512, "s": 33403, "text": "Adjacency Matrix: Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph." }, { "code": null, "e": 33613, "s": 33512, "text": "Adjacency List : An array of linked lists is used. Size of the array is equal to number of vertices." }, { "code": null, "e": 33631, "s": 33613, "text": " Graph Algorithms" }, { "code": null, "e": 33664, "s": 33631, "text": "Some Interesting Graph Questions" }, { "code": null, "e": 33686, "s": 33664, "text": "Minimum Spanning Tree" }, { "code": null, "e": 33895, "s": 33686, "text": "Minimum Spanning Tree (MST) problem: Given connected graph G with positive edge weights, find a min weight set of edges that connects all of the vertices. MST is fundamental problem with diverse applications." }, { "code": null, "e": 33973, "s": 33895, "text": "Network design– telephone, electrical, hydraulic, TV cable, computer, road" }, { "code": null, "e": 34051, "s": 33973, "text": "Network design– telephone, electrical, hydraulic, TV cable, computer, road" }, { "code": null, "e": 34144, "s": 34051, "text": "Approximation algorithms for NP-hard problems – traveling salesperson problem, Steiner tree" }, { "code": null, "e": 34237, "s": 34144, "text": "Approximation algorithms for NP-hard problems – traveling salesperson problem, Steiner tree" }, { "code": null, "e": 34351, "s": 34237, "text": "Cluster analysis- k clustering problem can be viewed as finding an MST and deleting the k-1 most expensive edges." }, { "code": null, "e": 34465, "s": 34351, "text": "Cluster analysis- k clustering problem can be viewed as finding an MST and deleting the k-1 most expensive edges." }, { "code": null, "e": 34556, "s": 34465, "text": "Example: Prim’s Minimum Spanning Tree Algorithm, Kruskal’s Minimum Spanning Tree Algorithm" }, { "code": null, "e": 34576, "s": 34556, "text": " Divide and Conquer" }, { "code": null, "e": 34724, "s": 34576, "text": "Divide:Break the given problem into subproblems of same type.Conquer: Recursively solve these subproblemsCombine: Appropriately combine the answers" }, { "code": null, "e": 34786, "s": 34724, "text": "Divide:Break the given problem into subproblems of same type." }, { "code": null, "e": 34831, "s": 34786, "text": "Conquer: Recursively solve these subproblems" }, { "code": null, "e": 34874, "s": 34831, "text": "Combine: Appropriately combine the answers" }, { "code": null, "e": 36110, "s": 34874, "text": "Following are some standard algorithms that are Divide and Conquer algorithms.1) Binary Search is a searching algorithm. In each step, the algorithm compares the input element x with the value of the middle element in array. If the values match, return the index of middle. Otherwise, if x is less than the middle element, then the algorithm recurs for left side of middle element, else recurs for right side of middle element.2) Quicksort is a sorting algorithm. The algorithm picks a pivot element, rearranges the array elements in such a way that all elements smaller than the picked pivot element move to left side of pivot, and all greater elements move to right side. Finally, the algorithm recursively sorts the subarrays on left and right of pivot element.3) Merge Sort is also a sorting algorithm. The algorithm divides the array in two halves, recursively sorts them and finally merges the two sorted halves.4) Closest Pair of Points The problem is to find the closest pair of points in a set of points in x-y plane. The problem can be solved in O(n^2) time by calculating distances of every pair of points and comparing the distances to find the minimum. The Divide and Conquer algorithm solves the problem in O(nLogn) time." }, { "code": null, "e": 36126, "s": 36110, "text": "Greedy Approach" }, { "code": null, "e": 37782, "s": 36126, "text": "Greedy is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious and immediate benefit. Greedy algorithms are used for optimization problems. An optimization problem can be solved using Greedy if the problem has the following property: At every step, we can make a choice that looks best at the moment, and we get the optimal solution of the complete problem. Following are some standard algorithms that are Greedy algorithms.1) Kruskal’s Minimum Spanning Tree (MST): In Kruskal’s algorithm, we create a MST by picking edges one by one. The Greedy Choice is to pick the smallest weight edge that doesn’t cause a cycle in the MST constructed so far.2) Prim’s Minimum Spanning Tree: In Prim’s algorithm also, we create a MST by picking edges one by one. We maintain two sets: set of the vertices already included in MST and the set of the vertices not yet included. The Greedy Choice is to pick the smallest weight edge that connects the two sets.3) Dijkstra’s Shortest Path: The Dijkstra’s algorithm is very similar to Prim’s algorithm. The shortest path tree is built up, edge by edge. We maintain two sets: set of the vertices already included in the tree and the set of the vertices not yet included. The Greedy Choice is to pick the edge that connects the two sets and is on the smallest weight path from source to the set that contains not yet included vertices.4) Huffman Coding: Huffman Coding is a loss-less compression technique. It assigns variable length bit codes to different characters. The Greedy Choice is to assign least bit length code to the most frequent character." }, { "code": null, "e": 37802, "s": 37782, "text": "Dynamic Programming" }, { "code": null, "e": 38010, "s": 37802, "text": "Dynamic Programming is an algorithmic paradigm that solves a given complex problem by breaking it into subproblems and stores the results of subproblems to avoid computing the same results again. Properties:" }, { "code": null, "e": 38256, "s": 38010, "text": "Overlapping Subproblems: Dynamic Programming is mainly used when solutions of same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these don’t have to be recomputed." }, { "code": null, "e": 38502, "s": 38256, "text": "Overlapping Subproblems: Dynamic Programming is mainly used when solutions of same subproblems are needed again and again. In dynamic programming, computed solutions to subproblems are stored in a table so that these don’t have to be recomputed." }, { "code": null, "e": 38526, "s": 38502, "text": "Uses: Fibonacci Numbers" }, { "code": null, "e": 38703, "s": 38526, "text": "Optimal Substructure: A given problems has Optimal Substructure Property if optimal solution of the given problem can be obtained by using optimal solutions of its subproblems." }, { "code": null, "e": 38880, "s": 38703, "text": "Optimal Substructure: A given problems has Optimal Substructure Property if optimal solution of the given problem can be obtained by using optimal solutions of its subproblems." }, { "code": null, "e": 38948, "s": 38880, "text": "Uses: Longest Increasing Subsequence, Shortest Path Two Approaches:" }, { "code": null, "e": 38993, "s": 38948, "text": "Memoization (Top Down)Tabulation (Bottom Up)" }, { "code": null, "e": 39016, "s": 38993, "text": "Memoization (Top Down)" }, { "code": null, "e": 39039, "s": 39016, "text": "Tabulation (Bottom Up)" }, { "code": null, "e": 39117, "s": 39039, "text": "Examples: Floyd Warshall Algorithm, Bellman–Ford Algorithm for Shortest Paths" }, { "code": null, "e": 39131, "s": 39117, "text": " BackTracking" }, { "code": null, "e": 39451, "s": 39131, "text": "Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items .Meaning of item varies from problem to problem. Example: Hamiltonian Cycle" }, { "code": null, "e": 39549, "s": 39451, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 39623, "s": 39549, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 39660, "s": 39623, "text": "Software Testing - Web Based Testing" }, { "code": null, "e": 39712, "s": 39660, "text": "What are the different ways of Data Representation?" }, { "code": null, "e": 39747, "s": 39712, "text": "Bash Script - Command Substitution" }, { "code": null, "e": 39796, "s": 39747, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 39859, "s": 39796, "text": "7 Highest Paying Programming Languages For Freelancers in 2022" }, { "code": null, "e": 39884, "s": 39859, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 39922, "s": 39884, "text": "How to Create a Shell Script in linux" }, { "code": null, "e": 39960, "s": 39922, "text": "How To Convert Numpy Array To Tensor?" } ]
How to run Java RMI Application
02 Nov, 2018 Prerequisite: RMI RMI (Remote Method Invocation) is used for distributed object references system. A distributed object is an object which publishes its interface on other machines. A Remote Object is a distributed object whose state is encapsulated. Stub and Skeleton are two objects used to communicate with the remote object. Stub: Stub is a gateway for client program which is used to communicate with skeleton object, by establishing a connection between them. Skeleton: Resides on Server program which is used for passing the request from stub to the remote interface. Creation of classes and interfaces for the problem statement: The steps involved in this are as follows:Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind("rmi:// localhost/FactorialService", c); } catch (Exception e) { // If any error occur System.out.println("ERR: " + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup("rmi:// localhost/FactorialService"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println("\nMalformedURLException: " + murle); } catch (RemoteException re) { System.out.println("\nRemoteException: " + re); } catch (NotBoundException nbe) { System.out.println("\nNotBoundException: " + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println("\nArithmeticException: " + ae); } }}Compilation of all programUse javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files.Running the system:After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry.Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen.In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory.In the third console, run the client program. Creation of classes and interfaces for the problem statement: The steps involved in this are as follows:Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind("rmi:// localhost/FactorialService", c); } catch (Exception e) { // If any error occur System.out.println("ERR: " + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup("rmi:// localhost/FactorialService"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println("\nMalformedURLException: " + murle); } catch (RemoteException re) { System.out.println("\nRemoteException: " + re); } catch (NotBoundException nbe) { System.out.println("\nNotBoundException: " + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println("\nArithmeticException: " + ae); } }} Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;} A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface. Problem Statement: Create an RMI Application for finding the factorial of a number Interface Program import java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;} Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }} This class will implement the remote interface. Do the required calculation for the problem statement. Implementation of Interface import java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }} Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind("rmi:// localhost/FactorialService", c); } catch (Exception e) { // If any error occur System.out.println("ERR: " + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }} For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference. Server Program import java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind("rmi:// localhost/FactorialService", c); } catch (Exception e) { // If any error occur System.out.println("ERR: " + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }} Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup("rmi:// localhost/FactorialService"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println("\nMalformedURLException: " + murle); } catch (RemoteException re) { System.out.println("\nRemoteException: " + re); } catch (NotBoundException nbe) { System.out.println("\nNotBoundException: " + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println("\nArithmeticException: " + ae); } }} Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this object Client Program import java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup("rmi:// localhost/FactorialService"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println("\nMalformedURLException: " + murle); } catch (RemoteException re) { System.out.println("\nRemoteException: " + re); } catch (NotBoundException nbe) { System.out.println("\nNotBoundException: " + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println("\nArithmeticException: " + ae); } }} Compilation of all programUse javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files. Use javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files. Running the system:After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry.Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen.In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory.In the third console, run the client program. After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry. Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen. In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory. In the third console, run the client program. In this way RMI can be run in three console for localhost. RMI uses Network stack and TCP/IP Stack for communication of three different JVM’s. Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Nov, 2018" }, { "code": null, "e": 70, "s": 52, "text": "Prerequisite: RMI" }, { "code": null, "e": 381, "s": 70, "text": "RMI (Remote Method Invocation) is used for distributed object references system. A distributed object is an object which publishes its interface on other machines. A Remote Object is a distributed object whose state is encapsulated. Stub and Skeleton are two objects used to communicate with the remote object." }, { "code": null, "e": 518, "s": 381, "text": "Stub: Stub is a gateway for client program which is used to communicate with skeleton object, by establishing a connection between them." }, { "code": null, "e": 627, "s": 518, "text": "Skeleton: Resides on Server program which is used for passing the request from stub to the remote interface." }, { "code": null, "e": 5353, "s": 627, "text": "Creation of classes and interfaces for the problem statement: The steps involved in this are as follows:Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind(\"rmi:// localhost/FactorialService\", c); } catch (Exception e) { // If any error occur System.out.println(\"ERR: \" + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup(\"rmi:// localhost/FactorialService\"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println(\"\\nMalformedURLException: \" + murle); } catch (RemoteException re) { System.out.println(\"\\nRemoteException: \" + re); } catch (NotBoundException nbe) { System.out.println(\"\\nNotBoundException: \" + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println(\"\\nArithmeticException: \" + ae); } }}Compilation of all programUse javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files.Running the system:After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry.Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen.In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory.In the third console, run the client program." }, { "code": null, "e": 9375, "s": 5353, "text": "Creation of classes and interfaces for the problem statement: The steps involved in this are as follows:Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind(\"rmi:// localhost/FactorialService\", c); } catch (Exception e) { // If any error occur System.out.println(\"ERR: \" + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup(\"rmi:// localhost/FactorialService\"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println(\"\\nMalformedURLException: \" + murle); } catch (RemoteException re) { System.out.println(\"\\nRemoteException: \" + re); } catch (NotBoundException nbe) { System.out.println(\"\\nNotBoundException: \" + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println(\"\\nArithmeticException: \" + ae); } }}" }, { "code": null, "e": 9962, "s": 9375, "text": "Create a Remote Interface which extends java.rmi.Remote:A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface.Problem Statement: Create an RMI Application for finding the factorial of a numberInterface ProgramInterface Programimport java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}" }, { "code": null, "e": 10163, "s": 9962, "text": "A remote interface determines the object that can be invoked remotely by the client. This interface can be communicated with the client’s program. This Interface must extend java.rmi.Remote Interface." }, { "code": null, "e": 10246, "s": 10163, "text": "Problem Statement: Create an RMI Application for finding the factorial of a number" }, { "code": null, "e": 10264, "s": 10246, "text": "Interface Program" }, { "code": "import java.math.BigInteger; // Creating an Interfacepublic interface Factorial extends java.rmi.Remote { // Declaring the method public BigInteger fact(int num) throws java.rmi.RemoteException;}", "e": 10479, "s": 10264, "text": null }, { "code": null, "e": 11542, "s": 10479, "text": "Create a class which extends java.rmi.server.UnicastRemoteObject and implements the previous interface.This class will implement the remote interface. Do the required calculation for the problem statement.Implementation of InterfaceImplementation of Interfaceimport java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}" }, { "code": null, "e": 11645, "s": 11542, "text": "This class will implement the remote interface. Do the required calculation for the problem statement." }, { "code": null, "e": 11673, "s": 11645, "text": "Implementation of Interface" }, { "code": "import java.math.BigInteger; // Extends and Implement the class// and interface respectivelypublic class FactorialImpl extends java.rmi.server.UnicastRemoteObject implements Factorial { // Constructor Declaration public FactorialImpl() throws java.rmi.RemoteException { super(); } // Calculation for the problem statement // Implementing the method fact() // to find factorial of a number public BigInteger fact(int num) throws java.rmi.RemoteException { BigInteger factorial = BigInteger.ONE; for (int i = 1; i <= num; ++i) { factorial = factorial .multiply( BigInteger .valueOf(i)); } return factorial; }}", "e": 12477, "s": 11673, "text": null }, { "code": null, "e": 13376, "s": 12477, "text": "Create a Server Class (with localhost and service name)For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference.Server ProgramServer Programimport java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind(\"rmi:// localhost/FactorialService\", c); } catch (Exception e) { // If any error occur System.out.println(\"ERR: \" + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}" }, { "code": null, "e": 13581, "s": 13376, "text": "For hosting a service, the server program is created whereby using java.rmi.Naming.rebind() method can be called which takes two arguments i.e., an object reference (service name) and instances reference." }, { "code": null, "e": 13596, "s": 13581, "text": "Server Program" }, { "code": "import java.rmi.Naming; public class FactorialServer { // Implement the constructor of the class public FactorialServer() { try { // Create a object reference for the interface Factorial c = new FactorialImpl(); // Bind the localhost with the service Naming.rebind(\"rmi:// localhost/FactorialService\", c); } catch (Exception e) { // If any error occur System.out.println(\"ERR: \" + e); } } public static void main(String[] args) { // Create an object new FactorialServer(); }}", "e": 14208, "s": 13596, "text": null }, { "code": null, "e": 15580, "s": 14208, "text": "Create a Client Class (with localhost and service name)Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this objectClient ProgramClient Programimport java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup(\"rmi:// localhost/FactorialService\"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println(\"\\nMalformedURLException: \" + murle); } catch (RemoteException re) { System.out.println(\"\\nRemoteException: \" + re); } catch (NotBoundException nbe) { System.out.println(\"\\nNotBoundException: \" + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println(\"\\nArithmeticException: \" + ae); } }}" }, { "code": null, "e": 15745, "s": 15580, "text": "Client program will invokes java.rmi.Naming.lookup() method for RMI URL and returns an instance of object type (Factorial Interface). All RMI is done on this object" }, { "code": null, "e": 15760, "s": 15745, "text": "Client Program" }, { "code": "import java.net.MalformedURLException;import java.rmi.Naming;import java.rmi.NotBoundException;import java.rmi.RemoteException; public class FactorialClient { public static void main(String[] args) { try { // Create an remote object with the same name // Cast the lookup result to the interface Factorial c = (Factorial); Naming.lookup(\"rmi:// localhost/FactorialService\"); // Call the method for the results System.out.println(c.fact(30)); } // If any error occur catch (MalformedURLException murle) { System.out.println(\"\\nMalformedURLException: \" + murle); } catch (RemoteException re) { System.out.println(\"\\nRemoteException: \" + re); } catch (NotBoundException nbe) { System.out.println(\"\\nNotBoundException: \" + nbe); } catch (java.lang.ArithmeticException ae) { System.out.println(\"\\nArithmeticException: \" + ae); } }}", "e": 16885, "s": 15760, "text": null }, { "code": null, "e": 17017, "s": 16885, "text": "Compilation of all programUse javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files." }, { "code": null, "e": 17123, "s": 17017, "text": "Use javac to compile all four programs and rmic (RMI Compiler) to create a stub and skeleton class files." }, { "code": null, "e": 17697, "s": 17123, "text": "Running the system:After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry.Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen.In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory.In the third console, run the client program." }, { "code": null, "e": 17915, "s": 17697, "text": "After the compilation phase, the system is now ready to run. To run the system, open three console screen (move to that path where the program resides). One for the client, one for server and one for the RMI Registry." }, { "code": null, "e": 18035, "s": 17915, "text": "Start with a registry, use rmiregistry, if there is no error registry will start running and now move to second screen." }, { "code": null, "e": 18209, "s": 18035, "text": "In the second console run the server program and host the FactorialService. It will start and wait for the client connection and it will load the implementation into memory." }, { "code": null, "e": 18255, "s": 18209, "text": "In the third console, run the client program." }, { "code": null, "e": 18398, "s": 18255, "text": "In this way RMI can be run in three console for localhost. RMI uses Network stack and TCP/IP Stack for communication of three different JVM’s." }, { "code": null, "e": 18403, "s": 18398, "text": "Java" }, { "code": null, "e": 18422, "s": 18403, "text": "Technical Scripter" }, { "code": null, "e": 18427, "s": 18422, "text": "Java" }, { "code": null, "e": 18525, "s": 18427, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18540, "s": 18525, "text": "Stream In Java" }, { "code": null, "e": 18561, "s": 18540, "text": "Introduction to Java" }, { "code": null, "e": 18582, "s": 18561, "text": "Constructors in Java" }, { "code": null, "e": 18601, "s": 18582, "text": "Exceptions in Java" }, { "code": null, "e": 18618, "s": 18601, "text": "Generics in Java" }, { "code": null, "e": 18644, "s": 18618, "text": "Java Programming Examples" }, { "code": null, "e": 18674, "s": 18644, "text": "Functional Interfaces in Java" }, { "code": null, "e": 18690, "s": 18674, "text": "Strings in Java" }, { "code": null, "e": 18727, "s": 18690, "text": "Differences between JDK, JRE and JVM" } ]
How to create an outline button in Bootstrap 4 ?
12 Dec, 2021 Before performing with outline classes of bootstrap just know about a little bit of button outline. An outline on buttons means to give an outline around the buttons. This ‘.btn-outline’ class removes all background colors or styles from the button for giving the Effective, lighter, and highlighter look to the button outside. Basically, the outline button is responsible for drawn a highlighted border around the button. Outline of buttons are used for many purposes such as – To give an effective look at buttons. To Indicate an action beyond the current working mechanism. To draw highlight outlines around buttons to give different look than normal buttons. To make a button “Stand-Out”. To give different styles for actions in forms and dialogs. Approach: In Bootstrap 4 has the default contextual classes or predefined class with the “.btn-outline” class, There are some built-in colored buttons that outline classes in bootstrap 4 which is used for a different purpose. The button outline classes are: .btn-outline-primary .btn-outline-secondary .btn-outline-success .btn-outline-danger .btn-outline-warning .btn-outline-info .btn-outline-light .btn-outline-dark Include Bootstrap4 and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”><script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js” integrity=”sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN” crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script> Example 1: In this example, we can see all the types of button outline contextual classes in bootstrap and know how it is used along within a webpage. HTML <!DOCTYPE html><html> <head> <meta name="viewport" content ="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script></head> <body> <div class="container"> <h1>Bootstrap Buttons Outline Examples</h1> <h5>There are some examples of buttons:-</h5> <br> <p> This is show Simple Button Outline<span> <button type="button" class="btn btn-outline-primary"> Primary </button> </span> </p> <br> <p> This is show Secondary Button Outline<span> <button type="button" class="btn btn-outline-secondary"> Secondary </button> </span> </p> <br> <p> This is show Success Button Outline<span> <button type="button" class="btn btn-outline-success"> Success </button> </span> </p> <br> <p> This is show Danger Button Outline<span> <button type="button" class="btn btn-outline-danger"> Danger </button> </span> </p> <br> <p> This is show Warning Button Outline<span> <button type="button" class="btn btn-outline-warning"> Warning </button> </span> </p> <br> <p> This is show Information Button Outline<span> <button type="button" class="btn btn-outline-info"> Info </button> </span> </p> <br> <p> This is show Light Button Outline<span> <button type="button" class="btn btn-outline-light"> Light </button> </span> </p> <br> <p> This is show Dark Button Outline<span> <button type="button" class="btn btn-outline-dark"> Dark </button> </span> </p> <br> </div></body> </html> Output: Buttons Outline types in Bootstrap4 Example 2: In this example, we use a spinner within the outline button in which the buttons are indicating an action is currently processing or taking place. HTML <!DOCTYPE html><html> <head> <meta name="viewport" content ="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <h1> Bootstrap Spinner Button Examples in Bootstrap </h1> <p>There are some examples of Spinner Button </p> <button type="button" class="btn btn-lg btn-outline"> <div class="spinner-border"> </div> </button> <br><br> <button type="button" class="btn btn-lg btn-outline-primary"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-success"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-warning"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-danger"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-info"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-dark"> <div class="spinner-border"> </div> </button> <button type="button" class="btn btn-lg btn-outline-success"> <div class="spinner-border"> </div> </button> </div></body> </html> Bootstrap Spinner within a button Example 3: In this example, we can see button outline contextual classes with different glyphicons and sizes. HTML <!DOCTYPE html><html> <head> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"> </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></head> <body> <div class="container"> <h1> Bootstrap Buttons Outline Examples in Different size </h1> <p> There are some examples of buttons outline with different icons and different size:- </p> <button type="button" class ="btn btn-sm btn-outline-primary"> <i class="fa fa-home"></i> </button> <button type="button" class ="btn btn-md btn-outline-primary"> <i class="fa fa-home"></i> </button> <button type="button" class= "btn btn-lg btn-outline-primary"> <i class="fa fa-home"></i> </button><br><br> <button type="button" class= "btn btn-sm btn-outline-success"> Home </button> <button type="button" class= "btn btn-md btn-outline-success"> Home </button> <button type="button" class= "btn btn-lg btn-outline-success"> Home </button> <br><br> <button type="button" class= "btn btn-sm btn-outline-danger"> <i class="fa fa-home"></i> Home </button> <button type="button" class= "btn btn-md btn-outline-danger"> <i class="fa fa-home"></i> Home </button> <button type="button" class= "btn btn-lg btn-outline-danger"> <i class="fa fa-home"></i> Home </button><br><br> <button type="button" class= "btn btn-lg btn-outline-primary"> <i class="fa fa-asterisk"></i> </button> <button type="button" class= "btn btn-lg btn-outline-success"> <i class="fa fa-circle"></i> </button> <button type="button" class= "btn btn-lg btn-outline-warning"> <i class="fa fa-square"></i> </button> <button type="button" class= "btn btn-lg btn-outline-danger"> <i class="fa fa-heart"></i> </button> <button type="button" class= "btn btn-lg btn-outline-info"> <i class="fa fa-battery"></i> </button> <button type="button" class= "btn btn-lg btn-outline-dark"> <i class="fa fa-bell"></i> </button> </div></body> </html> Bootstrap outline buttons with different size and icons in Bootstrap. varshagumber28 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.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Dec, 2021" }, { "code": null, "e": 475, "s": 52, "text": "Before performing with outline classes of bootstrap just know about a little bit of button outline. An outline on buttons means to give an outline around the buttons. This ‘.btn-outline’ class removes all background colors or styles from the button for giving the Effective, lighter, and highlighter look to the button outside. Basically, the outline button is responsible for drawn a highlighted border around the button." }, { "code": null, "e": 531, "s": 475, "text": "Outline of buttons are used for many purposes such as –" }, { "code": null, "e": 569, "s": 531, "text": "To give an effective look at buttons." }, { "code": null, "e": 629, "s": 569, "text": "To Indicate an action beyond the current working mechanism." }, { "code": null, "e": 715, "s": 629, "text": "To draw highlight outlines around buttons to give different look than normal buttons." }, { "code": null, "e": 745, "s": 715, "text": "To make a button “Stand-Out”." }, { "code": null, "e": 804, "s": 745, "text": "To give different styles for actions in forms and dialogs." }, { "code": null, "e": 1031, "s": 804, "text": "Approach: In Bootstrap 4 has the default contextual classes or predefined class with the “.btn-outline” class, There are some built-in colored buttons that outline classes in bootstrap 4 which is used for a different purpose." }, { "code": null, "e": 1064, "s": 1031, "text": "The button outline classes are: " }, { "code": null, "e": 1085, "s": 1064, "text": ".btn-outline-primary" }, { "code": null, "e": 1108, "s": 1085, "text": ".btn-outline-secondary" }, { "code": null, "e": 1129, "s": 1108, "text": ".btn-outline-success" }, { "code": null, "e": 1149, "s": 1129, "text": ".btn-outline-danger" }, { "code": null, "e": 1170, "s": 1149, "text": ".btn-outline-warning" }, { "code": null, "e": 1188, "s": 1170, "text": ".btn-outline-info" }, { "code": null, "e": 1207, "s": 1188, "text": ".btn-outline-light" }, { "code": null, "e": 1225, "s": 1207, "text": ".btn-outline-dark" }, { "code": null, "e": 1325, "s": 1225, "text": "Include Bootstrap4 and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 2118, "s": 1325, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css” integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm” crossorigin=”anonymous”><script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js” integrity=”sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN” crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js” integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q” crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js” integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl” crossorigin=”anonymous”></script>" }, { "code": null, "e": 2269, "s": 2118, "text": "Example 1: In this example, we can see all the types of button outline contextual classes in bootstrap and know how it is used along within a webpage." }, { "code": null, "e": 2274, "s": 2269, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script></head> <body> <div class=\"container\"> <h1>Bootstrap Buttons Outline Examples</h1> <h5>There are some examples of buttons:-</h5> <br> <p> This is show Simple Button Outline<span> <button type=\"button\" class=\"btn btn-outline-primary\"> Primary </button> </span> </p> <br> <p> This is show Secondary Button Outline<span> <button type=\"button\" class=\"btn btn-outline-secondary\"> Secondary </button> </span> </p> <br> <p> This is show Success Button Outline<span> <button type=\"button\" class=\"btn btn-outline-success\"> Success </button> </span> </p> <br> <p> This is show Danger Button Outline<span> <button type=\"button\" class=\"btn btn-outline-danger\"> Danger </button> </span> </p> <br> <p> This is show Warning Button Outline<span> <button type=\"button\" class=\"btn btn-outline-warning\"> Warning </button> </span> </p> <br> <p> This is show Information Button Outline<span> <button type=\"button\" class=\"btn btn-outline-info\"> Info </button> </span> </p> <br> <p> This is show Light Button Outline<span> <button type=\"button\" class=\"btn btn-outline-light\"> Light </button> </span> </p> <br> <p> This is show Dark Button Outline<span> <button type=\"button\" class=\"btn btn-outline-dark\"> Dark </button> </span> </p> <br> </div></body> </html>", "e": 5445, "s": 2274, "text": null }, { "code": null, "e": 5453, "s": 5445, "text": "Output:" }, { "code": null, "e": 5490, "s": 5453, "text": "Buttons Outline types in Bootstrap4" }, { "code": null, "e": 5648, "s": 5490, "text": "Example 2: In this example, we use a spinner within the outline button in which the buttons are indicating an action is currently processing or taking place." }, { "code": null, "e": 5653, "s": 5648, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content =\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <h1> Bootstrap Spinner Button Examples in Bootstrap </h1> <p>There are some examples of Spinner Button </p> <button type=\"button\" class=\"btn btn-lg btn-outline\"> <div class=\"spinner-border\"> </div> </button> <br><br> <button type=\"button\" class=\"btn btn-lg btn-outline-primary\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-success\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-warning\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-danger\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-info\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-dark\"> <div class=\"spinner-border\"> </div> </button> <button type=\"button\" class=\"btn btn-lg btn-outline-success\"> <div class=\"spinner-border\"> </div> </button> </div></body> </html>", "e": 7547, "s": 5653, "text": null }, { "code": null, "e": 7581, "s": 7547, "text": "Bootstrap Spinner within a button" }, { "code": null, "e": 7691, "s": 7581, "text": "Example 3: In this example, we can see button outline contextual classes with different glyphicons and sizes." }, { "code": null, "e": 7696, "s": 7691, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"> </script> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"></head> <body> <div class=\"container\"> <h1> Bootstrap Buttons Outline Examples in Different size </h1> <p> There are some examples of buttons outline with different icons and different size:- </p> <button type=\"button\" class =\"btn btn-sm btn-outline-primary\"> <i class=\"fa fa-home\"></i> </button> <button type=\"button\" class =\"btn btn-md btn-outline-primary\"> <i class=\"fa fa-home\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-primary\"> <i class=\"fa fa-home\"></i> </button><br><br> <button type=\"button\" class= \"btn btn-sm btn-outline-success\"> Home </button> <button type=\"button\" class= \"btn btn-md btn-outline-success\"> Home </button> <button type=\"button\" class= \"btn btn-lg btn-outline-success\"> Home </button> <br><br> <button type=\"button\" class= \"btn btn-sm btn-outline-danger\"> <i class=\"fa fa-home\"></i> Home </button> <button type=\"button\" class= \"btn btn-md btn-outline-danger\"> <i class=\"fa fa-home\"></i> Home </button> <button type=\"button\" class= \"btn btn-lg btn-outline-danger\"> <i class=\"fa fa-home\"></i> Home </button><br><br> <button type=\"button\" class= \"btn btn-lg btn-outline-primary\"> <i class=\"fa fa-asterisk\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-success\"> <i class=\"fa fa-circle\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-warning\"> <i class=\"fa fa-square\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-danger\"> <i class=\"fa fa-heart\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-info\"> <i class=\"fa fa-battery\"></i> </button> <button type=\"button\" class= \"btn btn-lg btn-outline-dark\"> <i class=\"fa fa-bell\"></i> </button> </div></body> </html>", "e": 11066, "s": 7696, "text": null }, { "code": null, "e": 11139, "s": 11069, "text": "Bootstrap outline buttons with different size and icons in Bootstrap." }, { "code": null, "e": 11156, "s": 11141, "text": "varshagumber28" }, { "code": null, "e": 11176, "s": 11156, "text": "Bootstrap-Questions" }, { "code": null, "e": 11191, "s": 11176, "text": "HTML-Questions" }, { "code": null, "e": 11198, "s": 11191, "text": "Picked" }, { "code": null, "e": 11208, "s": 11198, "text": "Bootstrap" }, { "code": null, "e": 11213, "s": 11208, "text": "HTML" }, { "code": null, "e": 11230, "s": 11213, "text": "Web Technologies" }, { "code": null, "e": 11235, "s": 11230, "text": "HTML" } ]
Stack and Queue in C#
Stack class represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. The following is the property of Stack class − Count− Gets the number of elements in the stack. Count− Gets the number of elements in the stack. The following are the methods of Stack class − The following is an example showing how to work with Stack class and its Push() and Pop() method − Live Demo using System; using System.Collections; namespace CollectionsApplication { class Program { static void Main(string[] args) { Stack st = new Stack(); st.Push('A'); st.Push('B'); st.Push('C'); st.Push('D'); Console.WriteLine("Current stack: "); foreach (char c in st) { Console.Write(c + " "); } Console.WriteLine(); st.Push('P'); st.Push('Q'); Console.WriteLine("The next poppable value in stack: {0}", st.Peek()); Console.WriteLine("Current stack: "); foreach (char c in st) { Console.Write(c + " "); } Console.WriteLine(); Console.WriteLine("Removing values...."); st.Pop(); st.Pop(); st.Pop(); Console.WriteLine("Current stack: "); foreach (char c in st) { Console.Write(c + " "); } } } } Current stack: D C B A The next poppable value in stack: Q Current stack: Q P D C B A Removing values.... Current stack: C B A Queue collection class is a concept in C# that is included in the System.Collection namespace. The elements are stored in a QUEUE in FIFO. The first element added will be the first to go out like a queue of people outside a movie hall to buy tickets. It has two methods − Enqueue() method to add values Dequeue() method to retrieve values Add items in the queue. Queue q = new Queue(); q.Enqueue(“Two”); q.Enqueue(“One”); Return items from the queue. Queue q = new Queue(); q.Enqueue(“Two”); q.Enqueue(“One”); // remove elements while (q.Count > 0) Console.WriteLine(q.Dequeue());
[ { "code": null, "e": 1191, "s": 1062, "text": "Stack class represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items." }, { "code": null, "e": 1238, "s": 1191, "text": "The following is the property of Stack class −" }, { "code": null, "e": 1287, "s": 1238, "text": "Count− Gets the number of elements in the stack." }, { "code": null, "e": 1336, "s": 1287, "text": "Count− Gets the number of elements in the stack." }, { "code": null, "e": 1383, "s": 1336, "text": "The following are the methods of Stack class −" }, { "code": null, "e": 1482, "s": 1383, "text": "The following is an example showing how to work with Stack class and its Push() and Pop() method −" }, { "code": null, "e": 1493, "s": 1482, "text": " Live Demo" }, { "code": null, "e": 2453, "s": 1493, "text": "using System;\nusing System.Collections;\n\nnamespace CollectionsApplication {\n class Program {\n static void Main(string[] args) {\n Stack st = new Stack();\n\n st.Push('A');\n st.Push('B');\n st.Push('C');\n st.Push('D');\n\n Console.WriteLine(\"Current stack: \");\n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n\n Console.WriteLine();\n\n st.Push('P');\n st.Push('Q');\n Console.WriteLine(\"The next poppable value in stack: {0}\", st.Peek());\n Console.WriteLine(\"Current stack: \");\n\n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n Console.WriteLine();\n\n Console.WriteLine(\"Removing values....\");\n st.Pop();\n st.Pop();\n st.Pop();\n\n Console.WriteLine(\"Current stack: \");\n foreach (char c in st) {\n Console.Write(c + \" \");\n }\n }\n }\n}" }, { "code": null, "e": 2580, "s": 2453, "text": "Current stack:\nD C B A\nThe next poppable value in stack: Q\nCurrent stack:\nQ P D C B A\nRemoving values....\nCurrent stack:\nC B A" }, { "code": null, "e": 2831, "s": 2580, "text": "Queue collection class is a concept in C# that is included in the System.Collection namespace. The elements are stored in a QUEUE in FIFO. The first element added will be the first to go out like a queue of people outside a movie hall to buy tickets." }, { "code": null, "e": 2852, "s": 2831, "text": "It has two methods −" }, { "code": null, "e": 2883, "s": 2852, "text": "Enqueue() method to add values" }, { "code": null, "e": 2919, "s": 2883, "text": "Dequeue() method to retrieve values" }, { "code": null, "e": 2943, "s": 2919, "text": "Add items in the queue." }, { "code": null, "e": 3002, "s": 2943, "text": "Queue q = new Queue();\nq.Enqueue(“Two”);\nq.Enqueue(“One”);" }, { "code": null, "e": 3031, "s": 3002, "text": "Return items from the queue." }, { "code": null, "e": 3162, "s": 3031, "text": "Queue q = new Queue();\nq.Enqueue(“Two”);\nq.Enqueue(“One”);\n\n// remove elements\nwhile (q.Count > 0)\nConsole.WriteLine(q.Dequeue());" } ]
How to Link Multiple Container in Docker ? - GeeksforGeeks
17 Jan, 2021 Docker is a free software created by Docker Inc. and it enables clients to create free and confined environments where the users can deploy their applications. A container is a standard unit of software that packages up code and all its dependencies from one computing environment and runs it quickly and reliably into another computing environment. Container linking allows multiple containers to link with each other. Linking the containers, provide a secure channel through which Docker containers can communicate with each other. This article describes the step-by-step process of container linking. Installed docker software in your respective operating system. Follow the below steps to link your c Step 1:The first step is to download the Jenkins image from the docker hub repository using the below command: sudo docker Jenkins pull Step 2: Once you have downloaded the image, the next step is to run the container. Here you can also specify a name to the container using the name option. To do so follow the below command. sudo docker run –name=jenkinsa -d jenkins Step 3: Now after creating the source container, it’s time to launch the destination container. Along with launching the destination container, we will also link it with the source container. For our destination container, we will be using the standard Ubuntu image, you can also use any other image according to your convenience. Use the below command to launch and link the containers: sudo docker run –name=jenkinsc –link=jenkinsa:alias-src -it ubuntu:latest /bin/bash Step 4: You can use the below command to check which two containers are running. sudo docker ps Step 5: Now in this step we will attach to the receiving container using the below command. sudo docker attach Jenkins Step 6: After attaching to the receiving container you can run the below command and you will notice new variables for linking with the source container. env docker How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install FFmpeg on Windows? How to Set Git Username and Password in GitBash? How to Install Jupyter Notebook on MacOS? How to Add External JAR File to an IntelliJ IDEA Project? How to Create and Setup Spring Boot Project in Eclipse IDE? How to Install Flutter on Visual Studio Code? How to Check the OS Version in Linux? How to Set Java Path in Windows and Linux? How To Pass and Parse Linux Bash Script Arguments and Parameters How to Install a local module using npm?
[ { "code": null, "e": 24561, "s": 24533, "text": "\n17 Jan, 2021" }, { "code": null, "e": 24722, "s": 24561, "text": "Docker is a free software created by Docker Inc. and it enables clients to create free and confined environments where the users can deploy their applications. " }, { "code": null, "e": 24913, "s": 24722, "text": "A container is a standard unit of software that packages up code and all its dependencies from one computing environment and runs it quickly and reliably into another computing environment. " }, { "code": null, "e": 25167, "s": 24913, "text": "Container linking allows multiple containers to link with each other. Linking the containers, provide a secure channel through which Docker containers can communicate with each other. This article describes the step-by-step process of container linking." }, { "code": null, "e": 25230, "s": 25167, "text": "Installed docker software in your respective operating system." }, { "code": null, "e": 25268, "s": 25230, "text": "Follow the below steps to link your c" }, { "code": null, "e": 25379, "s": 25268, "text": "Step 1:The first step is to download the Jenkins image from the docker hub repository using the below command:" }, { "code": null, "e": 25404, "s": 25379, "text": "sudo docker Jenkins pull" }, { "code": null, "e": 25595, "s": 25404, "text": "Step 2: Once you have downloaded the image, the next step is to run the container. Here you can also specify a name to the container using the name option. To do so follow the below command." }, { "code": null, "e": 25637, "s": 25595, "text": "sudo docker run –name=jenkinsa -d jenkins" }, { "code": null, "e": 26025, "s": 25637, "text": "Step 3: Now after creating the source container, it’s time to launch the destination container. Along with launching the destination container, we will also link it with the source container. For our destination container, we will be using the standard Ubuntu image, you can also use any other image according to your convenience. Use the below command to launch and link the containers:" }, { "code": null, "e": 26109, "s": 26025, "text": "sudo docker run –name=jenkinsc –link=jenkinsa:alias-src -it ubuntu:latest /bin/bash" }, { "code": null, "e": 26190, "s": 26109, "text": "Step 4: You can use the below command to check which two containers are running." }, { "code": null, "e": 26205, "s": 26190, "text": "sudo docker ps" }, { "code": null, "e": 26297, "s": 26205, "text": "Step 5: Now in this step we will attach to the receiving container using the below command." }, { "code": null, "e": 26324, "s": 26297, "text": "sudo docker attach Jenkins" }, { "code": null, "e": 26478, "s": 26324, "text": "Step 6: After attaching to the receiving container you can run the below command and you will notice new variables for linking with the source container." }, { "code": null, "e": 26482, "s": 26478, "text": "env" }, { "code": null, "e": 26489, "s": 26482, "text": "docker" }, { "code": null, "e": 26496, "s": 26489, "text": "How To" }, { "code": null, "e": 26594, "s": 26496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26603, "s": 26594, "text": "Comments" }, { "code": null, "e": 26616, "s": 26603, "text": "Old Comments" }, { "code": null, "e": 26650, "s": 26616, "text": "How to Install FFmpeg on Windows?" }, { "code": null, "e": 26699, "s": 26650, "text": "How to Set Git Username and Password in GitBash?" }, { "code": null, "e": 26741, "s": 26699, "text": "How to Install Jupyter Notebook on MacOS?" }, { "code": null, "e": 26799, "s": 26741, "text": "How to Add External JAR File to an IntelliJ IDEA Project?" }, { "code": null, "e": 26859, "s": 26799, "text": "How to Create and Setup Spring Boot Project in Eclipse IDE?" }, { "code": null, "e": 26905, "s": 26859, "text": "How to Install Flutter on Visual Studio Code?" }, { "code": null, "e": 26943, "s": 26905, "text": "How to Check the OS Version in Linux?" }, { "code": null, "e": 26986, "s": 26943, "text": "How to Set Java Path in Windows and Linux?" }, { "code": null, "e": 27051, "s": 26986, "text": "How To Pass and Parse Linux Bash Script Arguments and Parameters" } ]
Android | AdMob Interstitial Ads for Android Studio - GeeksforGeeks
05 Nov, 2019 Interstitial ads are full-screen ads that cover the whole UI of the app. This article shows you how to integrate Interstitial ads from AdMob into an Android app. Example – First Create a new Project in Android Studio and add the following codes to import the google Mobile Ads SDK. In the project-level build.gradle file, add the highlighted code to the allprojects section. allprojects{ repositories { google() jcenter() maven { url "https://maven.google.com" } }} In the app-level build.gradle file, add the highlighted code to dependencies section. dependencies{implementation fileTree (dir : 'libs', include : [ '*.jar' ])implementation 'com.android.support:appcompat-v7:26.1.0' compile 'com.google.android.gms:play-services-ads:15.0.0' Add the following code to Main Activity to initialize Mobile Ads SDK (this only needs to be done once in app lifecycle). You can find the app’s App ID in AdMob console. package org.geeksforgeeks.geeksforgeeks; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.google.android.gms.ads.MobileAds; public class MainActivity extends AppCompatActivity { protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); // Initialize the Mobile Ads SDK MobileAds.initialize (this, getString (R.string.admob_app_id)); }} Add the highlighted code to Main Activity to show Interstitial Ad: MainActivity.class – package org.geeksforgeeks.geeksforgeeks; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.google.android.gms.ads.MobileAds;import com.google.android.gms.ads.AdListener;import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.InterstitialAd; public class MainActivity extends AppCompatActivity { private InterstitialAd interstitial; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the Mobile Ads SDK MobileAds.initialize(this, getString(R.string.admob_app_id)); AdRequest adIRequest = new AdRequest.Builder().build(); // Prepare the Interstitial Ad Activity interstitial = new InterstitialAd(MainActivity.this); // Insert the Ad Unit ID interstitial.setAdUnitId(getString(R.string.admob_interstitial_id)); // Interstitial Ad load Request interstitial.loadAd(adIRequest); // Prepare an Interstitial Ad Listener interstitial.setAdListener(new AdListener() { public void onAdLoaded() { // Call displayInterstitial() function when the Ad loads displayInterstitial(); } }); } public void displayInterstitial() { // If Interstitial Ads are loaded then show else show nothing. if (interstitial.isLoaded()) { interstitial.show(); } }} Add the Admob App Id and Interstitial Ad Id to string.xml strings.xml – <?xml version="1.0" encoding="utf-8"?><resources> <string name="admob_app_id"> ca-app-pub-3940256099942544~3347511713</string> <string name="admob_interstitial_id"> ca-app-pub-3940256099942544/1033173712</string> <!-- ca-app-pub-3940256099942544~3347511713 this is your admob app id --> <!-- ca-app-pub-3940256099942544/1033173712 this is your admob Interstitial ad id --></resources> Akanksha_Rai android Technical Scripter TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Find the Wi-Fi Password Using CMD in Windows? Docker - COPY Instruction How to Run a Python Script using Docker? Top Programming Languages for Android App Development Running Python script on GPU. Setting up the environment in Java 'dd' command in Linux How to setup cron jobs in Ubuntu How to set up Command Prompt for Python in Windows10 ? How to Add External JAR File to an IntelliJ IDEA Project?
[ { "code": null, "e": 24177, "s": 24149, "text": "\n05 Nov, 2019" }, { "code": null, "e": 24339, "s": 24177, "text": "Interstitial ads are full-screen ads that cover the whole UI of the app. This article shows you how to integrate Interstitial ads from AdMob into an Android app." }, { "code": null, "e": 24349, "s": 24339, "text": "Example –" }, { "code": null, "e": 24552, "s": 24349, "text": "First Create a new Project in Android Studio and add the following codes to import the google Mobile Ads SDK. In the project-level build.gradle file, add the highlighted code to the allprojects section." }, { "code": "allprojects{ repositories { google() jcenter() maven { url \"https://maven.google.com\" } }}", "e": 24710, "s": 24552, "text": null }, { "code": null, "e": 24796, "s": 24710, "text": "In the app-level build.gradle file, add the highlighted code to dependencies section." }, { "code": "dependencies{implementation fileTree (dir : 'libs', include : [ '*.jar' ])implementation 'com.android.support:appcompat-v7:26.1.0' compile 'com.google.android.gms:play-services-ads:15.0.0'", "e": 24985, "s": 24796, "text": null }, { "code": null, "e": 25154, "s": 24985, "text": "Add the following code to Main Activity to initialize Mobile Ads SDK (this only needs to be done once in app lifecycle). You can find the app’s App ID in AdMob console." }, { "code": "package org.geeksforgeeks.geeksforgeeks; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.google.android.gms.ads.MobileAds; public class MainActivity extends AppCompatActivity { protected void onCreate (Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); // Initialize the Mobile Ads SDK MobileAds.initialize (this, getString (R.string.admob_app_id)); }}", "e": 25640, "s": 25154, "text": null }, { "code": null, "e": 25707, "s": 25640, "text": "Add the highlighted code to Main Activity to show Interstitial Ad:" }, { "code": null, "e": 25728, "s": 25707, "text": "MainActivity.class –" }, { "code": "package org.geeksforgeeks.geeksforgeeks; import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import com.google.android.gms.ads.MobileAds;import com.google.android.gms.ads.AdListener;import com.google.android.gms.ads.AdRequest;import com.google.android.gms.ads.InterstitialAd; public class MainActivity extends AppCompatActivity { private InterstitialAd interstitial; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the Mobile Ads SDK MobileAds.initialize(this, getString(R.string.admob_app_id)); AdRequest adIRequest = new AdRequest.Builder().build(); // Prepare the Interstitial Ad Activity interstitial = new InterstitialAd(MainActivity.this); // Insert the Ad Unit ID interstitial.setAdUnitId(getString(R.string.admob_interstitial_id)); // Interstitial Ad load Request interstitial.loadAd(adIRequest); // Prepare an Interstitial Ad Listener interstitial.setAdListener(new AdListener() { public void onAdLoaded() { // Call displayInterstitial() function when the Ad loads displayInterstitial(); } }); } public void displayInterstitial() { // If Interstitial Ads are loaded then show else show nothing. if (interstitial.isLoaded()) { interstitial.show(); } }}", "e": 27248, "s": 25728, "text": null }, { "code": null, "e": 27306, "s": 27248, "text": "Add the Admob App Id and Interstitial Ad Id to string.xml" }, { "code": null, "e": 27320, "s": 27306, "text": "strings.xml –" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <string name=\"admob_app_id\"> ca-app-pub-3940256099942544~3347511713</string> <string name=\"admob_interstitial_id\"> ca-app-pub-3940256099942544/1033173712</string> <!-- ca-app-pub-3940256099942544~3347511713 this is your admob app id --> <!-- ca-app-pub-3940256099942544/1033173712 this is your admob Interstitial ad id --></resources>", "e": 27771, "s": 27320, "text": null }, { "code": null, "e": 27784, "s": 27771, "text": "Akanksha_Rai" }, { "code": null, "e": 27792, "s": 27784, "text": "android" }, { "code": null, "e": 27811, "s": 27792, "text": "Technical Scripter" }, { "code": null, "e": 27820, "s": 27811, "text": "TechTips" }, { "code": null, "e": 27918, "s": 27820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27927, "s": 27918, "text": "Comments" }, { "code": null, "e": 27940, "s": 27927, "text": "Old Comments" }, { "code": null, "e": 27993, "s": 27940, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 28019, "s": 27993, "text": "Docker - COPY Instruction" }, { "code": null, "e": 28060, "s": 28019, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 28114, "s": 28060, "text": "Top Programming Languages for Android App Development" }, { "code": null, "e": 28144, "s": 28114, "text": "Running Python script on GPU." }, { "code": null, "e": 28179, "s": 28144, "text": "Setting up the environment in Java" }, { "code": null, "e": 28201, "s": 28179, "text": "'dd' command in Linux" }, { "code": null, "e": 28234, "s": 28201, "text": "How to setup cron jobs in Ubuntu" }, { "code": null, "e": 28289, "s": 28234, "text": "How to set up Command Prompt for Python in Windows10 ?" } ]
Advanced Excel Financial - XIRR Function
The XIRR function returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. To calculate the internal rate of return for a series of periodic cash flows, use the IRR function. XIRR (values, dates, [guess]) A series of cash flows that corresponds to a schedule of payments in dates. See Notes below. A schedule of payment dates that corresponds to the cash flow payments. Dates may occur in any order. See Notes below. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment If the first value is a cost or payment, it must be a negative value All succeeding payments are discounted based on a 365-day year The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment If the first value is a cost or payment, it must be a negative value If the first value is a cost or payment, it must be a negative value All succeeding payments are discounted based on a 365-day year All succeeding payments are discounted based on a 365-day year The series of values must contain at least one positive and one negative value. Dates should be entered by using the DATE Function, or as results of other formulas or functions. Problems can occur if dates are entered as text. The series of values must contain at least one positive and one negative value. Dates should be entered by using the DATE Function, or as results of other formulas or functions. Problems can occur if dates are entered as text. Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900. Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900. Numbers in dates are truncated to integers. Numbers in dates are truncated to integers. XIRR expects at least one positive cash flow and one negative cash flow. Otherwise, XIRR returns the #NUM! error value. XIRR expects at least one positive cash flow and one negative cash flow. Otherwise, XIRR returns the #NUM! error value. If any number in dates is not a valid Excel date, XIRR returns the #VALUE! error value. If any number in dates is not a valid Excel date, XIRR returns the #VALUE! error value. If any number in dates precedes the starting date, XIRR returns the #NUM! error value. If any number in dates precedes the starting date, XIRR returns the #NUM! error value. If values and dates contain a different number of values, XIRR returns the #NUM! error value. If values and dates contain a different number of values, XIRR returns the #NUM! error value. In most cases you do not need to provide guess for the XIRR calculation. If omitted, guess is assumed to be 0.1 (10 percent) In most cases you do not need to provide guess for the XIRR calculation. If omitted, guess is assumed to be 0.1 (10 percent) XIRR is closely related to XNPV, the net present value function. The rate of return calculated by XIRR is the interest rate corresponding to XNPV = 0. XIRR is closely related to XNPV, the net present value function. The rate of return calculated by XIRR is the interest rate corresponding to XNPV = 0. Excel uses an iterative technique for calculating XIRR. Using a changing rate (starting with guess), XIRR cycles through the calculation until the result is accurate within 0.000001 percent. If XIRR can't find a result that works after 100 tries, the #NUM! error value is returned. The rate is changed until − $$0 = \sum_{i=1}^{N} \frac{P_i}{\left ( 1 + rate \right )^{\frac{\left ( d_i - d_1 \right )}{365}}}$$ Where, di = the ith, or last, payment date. d1 = the 0th payment date. Pi = the ith, or last, payment. Excel uses an iterative technique for calculating XIRR. Using a changing rate (starting with guess), XIRR cycles through the calculation until the result is accurate within 0.000001 percent. If XIRR can't find a result that works after 100 tries, the #NUM! error value is returned. The rate is changed until − $$0 = \sum_{i=1}^{N} \frac{P_i}{\left ( 1 + rate \right )^{\frac{\left ( d_i - d_1 \right )}{365}}}$$ Where, di = the ith, or last, payment date. d1 = the 0th payment date. Pi = the ith, or last, payment. Excel 2007, Excel 2010, Excel 2013, Excel 2016 296 Lectures 146 hours Arun Motoori 56 Lectures 5.5 hours Pavan Lalwani 120 Lectures 6.5 hours Inf Sid 134 Lectures 8.5 hours Yoda Learning 46 Lectures 7.5 hours William Fiset 25 Lectures 1.5 hours Sasha Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2071, "s": 1854, "text": "The XIRR function returns the internal rate of return for a schedule of cash flows that is not necessarily periodic. To calculate the internal rate of return for a series of periodic cash flows, use the IRR function." }, { "code": null, "e": 2102, "s": 2071, "text": "XIRR (values, dates, [guess])\n" }, { "code": null, "e": 2178, "s": 2102, "text": "A series of cash flows that corresponds to a schedule of payments in dates." }, { "code": null, "e": 2195, "s": 2178, "text": "See Notes below." }, { "code": null, "e": 2267, "s": 2195, "text": "A schedule of payment dates that corresponds to the cash flow payments." }, { "code": null, "e": 2297, "s": 2267, "text": "Dates may occur in any order." }, { "code": null, "e": 2314, "s": 2297, "text": "See Notes below." }, { "code": null, "e": 2563, "s": 2314, "text": "The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment\n\nIf the first value is a cost or payment, it must be a negative value\nAll succeeding payments are discounted based on a 365-day year\n\n" }, { "code": null, "e": 2677, "s": 2563, "text": "The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment" }, { "code": null, "e": 2746, "s": 2677, "text": "If the first value is a cost or payment, it must be a negative value" }, { "code": null, "e": 2815, "s": 2746, "text": "If the first value is a cost or payment, it must be a negative value" }, { "code": null, "e": 2878, "s": 2815, "text": "All succeeding payments are discounted based on a 365-day year" }, { "code": null, "e": 2941, "s": 2878, "text": "All succeeding payments are discounted based on a 365-day year" }, { "code": null, "e": 3168, "s": 2941, "text": "The series of values must contain at least one positive and one negative value. Dates should be entered by using the DATE Function, or as results of other formulas or functions. Problems can occur if dates are entered as text." }, { "code": null, "e": 3395, "s": 3168, "text": "The series of values must contain at least one positive and one negative value. Dates should be entered by using the DATE Function, or as results of other formulas or functions. Problems can occur if dates are entered as text." }, { "code": null, "e": 3630, "s": 3395, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900." }, { "code": null, "e": 3865, "s": 3630, "text": "Microsoft Excel stores dates as sequential serial numbers so they can be used in calculations. By default, January 1, 1900 is serial number 1, and January 1, 2008 is serial number 39448 because it is 39,448 days after January 1, 1900." }, { "code": null, "e": 3909, "s": 3865, "text": "Numbers in dates are truncated to integers." }, { "code": null, "e": 3953, "s": 3909, "text": "Numbers in dates are truncated to integers." }, { "code": null, "e": 4073, "s": 3953, "text": "XIRR expects at least one positive cash flow and one negative cash flow. Otherwise, XIRR returns the #NUM! error value." }, { "code": null, "e": 4193, "s": 4073, "text": "XIRR expects at least one positive cash flow and one negative cash flow. Otherwise, XIRR returns the #NUM! error value." }, { "code": null, "e": 4281, "s": 4193, "text": "If any number in dates is not a valid Excel date, XIRR returns the #VALUE! error value." }, { "code": null, "e": 4369, "s": 4281, "text": "If any number in dates is not a valid Excel date, XIRR returns the #VALUE! error value." }, { "code": null, "e": 4456, "s": 4369, "text": "If any number in dates precedes the starting date, XIRR returns the #NUM! error value." }, { "code": null, "e": 4543, "s": 4456, "text": "If any number in dates precedes the starting date, XIRR returns the #NUM! error value." }, { "code": null, "e": 4637, "s": 4543, "text": "If values and dates contain a different number of values, XIRR returns the #NUM! error value." }, { "code": null, "e": 4731, "s": 4637, "text": "If values and dates contain a different number of values, XIRR returns the #NUM! error value." }, { "code": null, "e": 4856, "s": 4731, "text": "In most cases you do not need to provide guess for the XIRR calculation. If omitted, guess is assumed to be 0.1 (10 percent)" }, { "code": null, "e": 4981, "s": 4856, "text": "In most cases you do not need to provide guess for the XIRR calculation. If omitted, guess is assumed to be 0.1 (10 percent)" }, { "code": null, "e": 5132, "s": 4981, "text": "XIRR is closely related to XNPV, the net present value function. The rate of return calculated by XIRR is the interest rate corresponding to XNPV = 0." }, { "code": null, "e": 5283, "s": 5132, "text": "XIRR is closely related to XNPV, the net present value function. The rate of return calculated by XIRR is the interest rate corresponding to XNPV = 0." }, { "code": null, "e": 5799, "s": 5283, "text": "Excel uses an iterative technique for calculating XIRR. Using a changing rate (starting with guess), XIRR cycles through the calculation until the result is accurate within 0.000001 percent. If XIRR can't find a result that works after 100 tries, the #NUM! error value is returned. The rate is changed until −\n$$0 = \\sum_{i=1}^{N} \\frac{P_i}{\\left ( 1\n+ rate \\right )^{\\frac{\\left ( d_i - d_1 \\right )}{365}}}$$\nWhere,\ndi = the ith, or last, payment date.\nd1 = the 0th payment date.\nPi = the ith, or last, payment.\n" }, { "code": null, "e": 6109, "s": 5799, "text": "Excel uses an iterative technique for calculating XIRR. Using a changing rate (starting with guess), XIRR cycles through the calculation until the result is accurate within 0.000001 percent. If XIRR can't find a result that works after 100 tries, the #NUM! error value is returned. The rate is changed until −" }, { "code": null, "e": 6211, "s": 6109, "text": "$$0 = \\sum_{i=1}^{N} \\frac{P_i}{\\left ( 1\n+ rate \\right )^{\\frac{\\left ( d_i - d_1 \\right )}{365}}}$$" }, { "code": null, "e": 6218, "s": 6211, "text": "Where," }, { "code": null, "e": 6255, "s": 6218, "text": "di = the ith, or last, payment date." }, { "code": null, "e": 6282, "s": 6255, "text": "d1 = the 0th payment date." }, { "code": null, "e": 6314, "s": 6282, "text": "Pi = the ith, or last, payment." }, { "code": null, "e": 6361, "s": 6314, "text": "Excel 2007, Excel 2010, Excel 2013, Excel 2016" }, { "code": null, "e": 6397, "s": 6361, "text": "\n 296 Lectures \n 146 hours \n" }, { "code": null, "e": 6411, "s": 6397, "text": " Arun Motoori" }, { "code": null, "e": 6446, "s": 6411, "text": "\n 56 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6461, "s": 6446, "text": " Pavan Lalwani" }, { "code": null, "e": 6497, "s": 6461, "text": "\n 120 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6506, "s": 6497, "text": " Inf Sid" }, { "code": null, "e": 6542, "s": 6506, "text": "\n 134 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6557, "s": 6542, "text": " Yoda Learning" }, { "code": null, "e": 6592, "s": 6557, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6607, "s": 6592, "text": " William Fiset" }, { "code": null, "e": 6642, "s": 6607, "text": "\n 25 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6656, "s": 6642, "text": " Sasha Miller" }, { "code": null, "e": 6663, "s": 6656, "text": " Print" }, { "code": null, "e": 6674, "s": 6663, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: The transition property
[]
Objective-C Structures
Objective-C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds. Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book − Title Author Subject Book ID To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is shown below − struct [structure tag] { member definition; member definition; ... member definition; } [one or more structure variables]; The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure − struct Books { NSString *title; NSString *author; NSString *subject; int book_id; } book; To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure − #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @"Objective-C Programming"; Book1.author = @"Nuha Ali"; Book1.subject = @"Objective-C Programming Tutorial"; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @"Telecom Billing"; Book2.author = @"Zara Ali"; Book2.subject = @"Telecom Billing Tutorial"; Book2.book_id = 6495700; /* print Book1 info */ NSLog(@"Book 1 title : %@\n", Book1.title); NSLog(@"Book 1 author : %@\n", Book1.author); NSLog(@"Book 1 subject : %@\n", Book1.subject); NSLog(@"Book 1 book_id : %d\n", Book1.book_id); /* print Book2 info */ NSLog(@"Book 2 title : %@\n", Book2.title); NSLog(@"Book 2 author : %@\n", Book2.author); NSLog(@"Book 2 subject : %@\n", Book2.subject); NSLog(@"Book 2 book_id : %d\n", Book2.book_id); return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 04:20:07.947 demo[20591] Book 1 title : Objective-C Programming 2013-09-14 04:20:07.947 demo[20591] Book 1 author : Nuha Ali 2013-09-14 04:20:07.947 demo[20591] Book 1 subject : Objective-C Programming Tutorial 2013-09-14 04:20:07.947 demo[20591] Book 1 book_id : 6495407 2013-09-14 04:20:07.947 demo[20591] Book 2 title : Telecom Billing 2013-09-14 04:20:07.947 demo[20591] Book 2 author : Zara Ali 2013-09-14 04:20:07.947 demo[20591] Book 2 subject : Telecom Billing Tutorial 2013-09-14 04:20:07.947 demo[20591] Book 2 book_id : 6495700 You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example − #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; @interface SampleClass:NSObject /* function declaration */ - (void) printBook:( struct Books) book ; @end @implementation SampleClass - (void) printBook:( struct Books) book { NSLog(@"Book title : %@\n", book.title); NSLog(@"Book author : %@\n", book.author); NSLog(@"Book subject : %@\n", book.subject); NSLog(@"Book book_id : %d\n", book.book_id); } @end int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @"Objective-C Programming"; Book1.author = @"Nuha Ali"; Book1.subject = @"Objective-C Programming Tutorial"; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @"Telecom Billing"; Book2.author = @"Zara Ali"; Book2.subject = @"Telecom Billing Tutorial"; Book2.book_id = 6495700; SampleClass *sampleClass = [[SampleClass alloc]init]; /* print Book1 info */ [sampleClass printBook: Book1]; /* Print Book2 info */ [sampleClass printBook: Book2]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 04:34:45.725 demo[8060] Book title : Objective-C Programming 2013-09-14 04:34:45.725 demo[8060] Book author : Nuha Ali 2013-09-14 04:34:45.725 demo[8060] Book subject : Objective-C Programming Tutorial 2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495407 2013-09-14 04:34:45.725 demo[8060] Book title : Telecom Billing 2013-09-14 04:34:45.725 demo[8060] Book author : Zara Ali 2013-09-14 04:34:45.725 demo[8060] Book subject : Telecom Billing Tutorial 2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495700 You can define pointers to structures in very similar way as you define pointer to any other variable as follows − struct Books *struct_pointer; Now, you can store the address of a structure variable in the above-defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows − struct_pointer = &Book1; To access the members of a structure using a pointer to that structure, you must use the -> operator as follows − struct_pointer->title; Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept − #import <Foundation/Foundation.h> struct Books { NSString *title; NSString *author; NSString *subject; int book_id; }; @interface SampleClass:NSObject /* function declaration */ - (void) printBook:( struct Books *) book ; @end @implementation SampleClass - (void) printBook:( struct Books *) book { NSLog(@"Book title : %@\n", book->title); NSLog(@"Book author : %@\n", book->author); NSLog(@"Book subject : %@\n", book->subject); NSLog(@"Book book_id : %d\n", book->book_id); } @end int main() { struct Books Book1; /* Declare Book1 of type Book */ struct Books Book2; /* Declare Book2 of type Book */ /* book 1 specification */ Book1.title = @"Objective-C Programming"; Book1.author = @"Nuha Ali"; Book1.subject = @"Objective-C Programming Tutorial"; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = @"Telecom Billing"; Book2.author = @"Zara Ali"; Book2.subject = @"Telecom Billing Tutorial"; Book2.book_id = 6495700; SampleClass *sampleClass = [[SampleClass alloc]init]; /* print Book1 info by passing address of Book1 */ [sampleClass printBook:&Book1]; /* print Book2 info by passing address of Book2 */ [sampleClass printBook:&Book2]; return 0; } When the above code is compiled and executed, it produces the following result − 2013-09-14 04:38:13.942 demo[20745] Book title : Objective-C Programming 2013-09-14 04:38:13.942 demo[20745] Book author : Nuha Ali 2013-09-14 04:38:13.942 demo[20745] Book subject : Objective-C Programming Tutorial 2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495407 2013-09-14 04:38:13.942 demo[20745] Book title : Telecom Billing 2013-09-14 04:38:13.942 demo[20745] Book author : Zara Ali 2013-09-14 04:38:13.942 demo[20745] Book subject : Telecom Billing Tutorial 2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495700 Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples − Packing several objects into a machine word. e.g. 1 bit flags can be compacted. Packing several objects into a machine word. e.g. 1 bit flags can be compacted. Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers. Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers. Objective-C allows us do this in a structure definition by putting :bit length after the variable. For example − struct packed_struct { unsigned int f1:1; unsigned int f2:1; unsigned int f3:1; unsigned int f4:1; unsigned int type:4; unsigned int my_int:9; } pack; Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit my_int. Objective-C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word. 18 Lectures 1 hours PARTHA MAJUMDAR 6 Lectures 25 mins Ken Burke Print Add Notes Bookmark this page
[ { "code": null, "e": 2811, "s": 2560, "text": "Objective-C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds." }, { "code": null, "e": 2980, "s": 2811, "text": "Structures are used to represent a record, Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −" }, { "code": null, "e": 2986, "s": 2980, "text": "Title" }, { "code": null, "e": 2993, "s": 2986, "text": "Author" }, { "code": null, "e": 3001, "s": 2993, "text": "Subject" }, { "code": null, "e": 3009, "s": 3001, "text": "Book ID" }, { "code": null, "e": 3209, "s": 3009, "text": "To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is shown below −" }, { "code": null, "e": 3346, "s": 3209, "text": "struct [structure tag] {\n member definition;\n member definition;\n ...\n member definition;\n} [one or more structure variables]; " }, { "code": null, "e": 3696, "s": 3346, "text": "The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −" }, { "code": null, "e": 3802, "s": 3696, "text": "struct Books {\n NSString *title;\n NSString *author;\n NSString *subject;\n int book_id;\n} book; " }, { "code": null, "e": 4136, "s": 3802, "text": "To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −" }, { "code": null, "e": 5246, "s": 4136, "text": "#import <Foundation/Foundation.h>\n\nstruct Books {\n NSString *title;\n NSString *author;\n NSString *subject;\n int book_id;\n};\n \nint main() {\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = @\"Objective-C Programming\";\n Book1.author = @\"Nuha Ali\"; \n Book1.subject = @\"Objective-C Programming Tutorial\";\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n Book2.title = @\"Telecom Billing\";\n Book2.author = @\"Zara Ali\";\n Book2.subject = @\"Telecom Billing Tutorial\";\n Book2.book_id = 6495700;\n \n /* print Book1 info */\n NSLog(@\"Book 1 title : %@\\n\", Book1.title);\n NSLog(@\"Book 1 author : %@\\n\", Book1.author);\n NSLog(@\"Book 1 subject : %@\\n\", Book1.subject);\n NSLog(@\"Book 1 book_id : %d\\n\", Book1.book_id);\n\n /* print Book2 info */\n NSLog(@\"Book 2 title : %@\\n\", Book2.title);\n NSLog(@\"Book 2 author : %@\\n\", Book2.author);\n NSLog(@\"Book 2 subject : %@\\n\", Book2.subject);\n NSLog(@\"Book 2 book_id : %d\\n\", Book2.book_id);\n\n return 0;\n}" }, { "code": null, "e": 5327, "s": 5246, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 5878, "s": 5327, "text": "2013-09-14 04:20:07.947 demo[20591] Book 1 title : Objective-C Programming\n2013-09-14 04:20:07.947 demo[20591] Book 1 author : Nuha Ali\n2013-09-14 04:20:07.947 demo[20591] Book 1 subject : Objective-C Programming Tutorial\n2013-09-14 04:20:07.947 demo[20591] Book 1 book_id : 6495407\n2013-09-14 04:20:07.947 demo[20591] Book 2 title : Telecom Billing\n2013-09-14 04:20:07.947 demo[20591] Book 2 author : Zara Ali\n2013-09-14 04:20:07.947 demo[20591] Book 2 subject : Telecom Billing Tutorial\n2013-09-14 04:20:07.947 demo[20591] Book 2 book_id : 6495700\n" }, { "code": null, "e": 6089, "s": 5878, "text": "You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −" }, { "code": null, "e": 7304, "s": 6089, "text": "#import <Foundation/Foundation.h>\n\nstruct Books {\n NSString *title;\n NSString *author;\n NSString *subject;\n int book_id;\n};\n\n@interface SampleClass:NSObject\n/* function declaration */\n- (void) printBook:( struct Books) book ;\n@end\n\n@implementation SampleClass \n\n- (void) printBook:( struct Books) book {\n NSLog(@\"Book title : %@\\n\", book.title);\n NSLog(@\"Book author : %@\\n\", book.author);\n NSLog(@\"Book subject : %@\\n\", book.subject);\n NSLog(@\"Book book_id : %d\\n\", book.book_id);\n}\n\n@end\n\nint main() {\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = @\"Objective-C Programming\";\n Book1.author = @\"Nuha Ali\"; \n Book1.subject = @\"Objective-C Programming Tutorial\";\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n Book2.title = @\"Telecom Billing\";\n Book2.author = @\"Zara Ali\";\n Book2.subject = @\"Telecom Billing Tutorial\";\n Book2.book_id = 6495700;\n \n SampleClass *sampleClass = [[SampleClass alloc]init];\n /* print Book1 info */\n [sampleClass printBook: Book1];\n\n /* Print Book2 info */\n [sampleClass printBook: Book2];\n\n return 0;\n}\n" }, { "code": null, "e": 7385, "s": 7304, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 7912, "s": 7385, "text": "2013-09-14 04:34:45.725 demo[8060] Book title : Objective-C Programming\n2013-09-14 04:34:45.725 demo[8060] Book author : Nuha Ali\n2013-09-14 04:34:45.725 demo[8060] Book subject : Objective-C Programming Tutorial\n2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495407\n2013-09-14 04:34:45.725 demo[8060] Book title : Telecom Billing\n2013-09-14 04:34:45.725 demo[8060] Book author : Zara Ali\n2013-09-14 04:34:45.725 demo[8060] Book subject : Telecom Billing Tutorial\n2013-09-14 04:34:45.725 demo[8060] Book book_id : 6495700\n" }, { "code": null, "e": 8027, "s": 7912, "text": "You can define pointers to structures in very similar way as you define pointer to any other variable as follows −" }, { "code": null, "e": 8057, "s": 8027, "text": "struct Books *struct_pointer;" }, { "code": null, "e": 8258, "s": 8057, "text": "Now, you can store the address of a structure variable in the above-defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −" }, { "code": null, "e": 8283, "s": 8258, "text": "struct_pointer = &Book1;" }, { "code": null, "e": 8397, "s": 8283, "text": "To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −" }, { "code": null, "e": 8420, "s": 8397, "text": "struct_pointer->title;" }, { "code": null, "e": 8534, "s": 8420, "text": "Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −" }, { "code": null, "e": 9811, "s": 8534, "text": "#import <Foundation/Foundation.h>\n\nstruct Books {\n NSString *title;\n NSString *author;\n NSString *subject;\n int book_id;\n};\n\n@interface SampleClass:NSObject\n/* function declaration */\n- (void) printBook:( struct Books *) book ;\n@end\n\n@implementation SampleClass \n- (void) printBook:( struct Books *) book {\n NSLog(@\"Book title : %@\\n\", book->title);\n NSLog(@\"Book author : %@\\n\", book->author);\n NSLog(@\"Book subject : %@\\n\", book->subject);\n NSLog(@\"Book book_id : %d\\n\", book->book_id);\n}\n\n@end\n\nint main() {\n struct Books Book1; /* Declare Book1 of type Book */\n struct Books Book2; /* Declare Book2 of type Book */\n \n /* book 1 specification */\n Book1.title = @\"Objective-C Programming\";\n Book1.author = @\"Nuha Ali\"; \n Book1.subject = @\"Objective-C Programming Tutorial\";\n Book1.book_id = 6495407;\n\n /* book 2 specification */\n Book2.title = @\"Telecom Billing\";\n Book2.author = @\"Zara Ali\";\n Book2.subject = @\"Telecom Billing Tutorial\";\n Book2.book_id = 6495700;\n \n SampleClass *sampleClass = [[SampleClass alloc]init];\n /* print Book1 info by passing address of Book1 */\n [sampleClass printBook:&Book1];\n\n /* print Book2 info by passing address of Book2 */\n [sampleClass printBook:&Book2];\n\n return 0;\n}" }, { "code": null, "e": 9892, "s": 9811, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 10427, "s": 9892, "text": "2013-09-14 04:38:13.942 demo[20745] Book title : Objective-C Programming\n2013-09-14 04:38:13.942 demo[20745] Book author : Nuha Ali\n2013-09-14 04:38:13.942 demo[20745] Book subject : Objective-C Programming Tutorial\n2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495407\n2013-09-14 04:38:13.942 demo[20745] Book title : Telecom Billing\n2013-09-14 04:38:13.942 demo[20745] Book author : Zara Ali\n2013-09-14 04:38:13.942 demo[20745] Book subject : Telecom Billing Tutorial\n2013-09-14 04:38:13.942 demo[20745] Book book_id : 6495700\n" }, { "code": null, "e": 10570, "s": 10427, "text": "Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples −" }, { "code": null, "e": 10650, "s": 10570, "text": "Packing several objects into a machine word. e.g. 1 bit flags can be compacted." }, { "code": null, "e": 10730, "s": 10650, "text": "Packing several objects into a machine word. e.g. 1 bit flags can be compacted." }, { "code": null, "e": 10828, "s": 10730, "text": "Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers." }, { "code": null, "e": 10926, "s": 10828, "text": "Reading external file formats -- non-standard file formats could be read in. E.g. 9 bit integers." }, { "code": null, "e": 11039, "s": 10926, "text": "Objective-C allows us do this in a structure definition by putting :bit length after the variable. For example −" }, { "code": null, "e": 11208, "s": 11039, "text": "struct packed_struct {\n unsigned int f1:1;\n unsigned int f2:1;\n unsigned int f3:1;\n unsigned int f4:1;\n unsigned int type:4;\n unsigned int my_int:9;\n} pack;" }, { "code": null, "e": 11310, "s": 11208, "text": "Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4 bit type and a 9 bit my_int." }, { "code": null, "e": 11644, "s": 11310, "text": "Objective-C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields whilst other would store the next field in the next word." }, { "code": null, "e": 11677, "s": 11644, "text": "\n 18 Lectures \n 1 hours \n" }, { "code": null, "e": 11694, "s": 11677, "text": " PARTHA MAJUMDAR" }, { "code": null, "e": 11725, "s": 11694, "text": "\n 6 Lectures \n 25 mins\n" }, { "code": null, "e": 11736, "s": 11725, "text": " Ken Burke" }, { "code": null, "e": 11743, "s": 11736, "text": " Print" }, { "code": null, "e": 11754, "s": 11743, "text": " Add Notes" } ]
All About Python List Comprehension | by Baijayanta Roy | Towards Data Science
Python is a language of expressiveness in concise code, which is very elegant and easy to comprehend. List Comprehension provides a concise way to create lists. List Comprehension is the proper “pythonic” way of building an accessible, concise, and fast way to build lists. It allows one to perform complex operations on lists using a single line. List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists. In the core of list comprehension, it is the loop (‘for’ loop). Any list comprehension we can represent as a for loop, but when we represent it with equivalent list comprehension in a single line, it looks genuinely unique. List comprehension has these essential parts : An iterable input sequence (this could be a list, a range, or any sequence) that we iterate using a variable name.An output expressionAn optional condition for the variable to filter or map or do some logical action An iterable input sequence (this could be a list, a range, or any sequence) that we iterate using a variable name. An output expression An optional condition for the variable to filter or map or do some logical action For example, if we want to create a square list from a list of variables from 1 to 5, we can do so as below using the standard for loop, but when we use a list comprehension, it becomes concise and lightweight. If we break-down the list comprehension parts, it looks as below. Thus here iterable is range(1,6), and x is the variable representing each value in the range. For each x (1,2,3,4,5) , output expression x*x calculates a corresponding output (1,4,9,16,25) which ultimately becomes the final output list (refer to above diagram). Few Ways of Usage other than the basic construct: List comprehensions provide a way to check for conditions and filter out the elements we don’t need from the input list for output. This filtering happens before the output expression takes place. Refer to the below example where we calculate square for only those variables which are divisible by 2. List Comprehension can be used to check nested conditions. Refer to the below code, where we want to find which all variables in the input list are divisible by 2,4 & 5. We can use an “if-else” in a list comprehension in Python. Refer to the code block below, which finds odd and even for a list of numbers. We need to specify what the output is first, following “if” condition and then “else” followed by what is the output under “else.” Note, we can not print input value directly without using a comma and parenthesis. Suppose we have to flatten a 2D list. We can easily do it using List Comprehension using a sublist. How can we flatten a 3D list? It becomes a bit complex where first we flatten 3D to 2D and then 2D to 1D. In the below example blue underlined portion is the step that makes 2D flatten from a 3D list, and then the outer part does flattening to 1D. We can use list comprehension for multiple nested “for” loops. We have to careful in terms of the order of execution when we use nested list comprehension. Suppose we have a 3x3 square matrix, and we want to create a matrix using this matrix where all diagonal values need to be square while other values need to be zeros. Here the output is 1 dimensional, and we need additional logic to convert to 2D matrix form. Here I used “column” and “row” for explanation purposes but can be used directly in the “for loop” without the intermediate variables (as used in below List Comprehension). matrix = [[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]]row = len(matrix)column = len(matrix[0])output = []for i in range(row): for j in range(column): if i == j: output.append(matrix[i][j] * matrix[i][j]) else: output.append(0) output[1, 0, 0, 0, 25, 0, 0, 0, 81] Now we see equivalent nested list comprehension (single line only, but for easy understanding, I have made it in 3 lines). [[matrix[i][j]*matrix[i][j] if i == j else 0 for i in range(len(matrix))] for j in range(len(matrix[0]))] Now let’s understand this with a picture of how each loop is working. Loop execution order is top to bottom (bold green arrow). Inner loops (dark green ) we complete first, and then control comes back to the outer loop (blue). Here List Comprehension is one line in comparison to 5 lines of ordinary “for loop,” as shown above code. We can also get the matrix form of output directly by putting brackets after first for loop. One of the significant advantages of list comprehension is that developer need to write less codeList comprehension often becomes easier to understandThe speed of list comprehensions is notably better than for-loops when appending items to the listList comprehensions are an excellent alternative to the built-in map and filter functions One of the significant advantages of list comprehension is that developer need to write less code List comprehension often becomes easier to understand The speed of list comprehensions is notably better than for-loops when appending items to the list List comprehensions are an excellent alternative to the built-in map and filter functions In Python, we have also “dictionary comprehensions” and “set comprehensions” that are similar in operation but meant for dictionary and set. Python also has “generator expression” which uses a “round” bracket. When I started my journey with Python, I used to find it challenging to understand how the list comprehension works. Once I understood its elegance and power, I never looked back. Even though it feels intimidating at first, with a bit of practice, every python lover can fall in love with List Comprehension. I look forward to your comment and share if you have any unique experience with the list comprehension. Thanks for reading. You can connect me @LinkedIn.
[ { "code": null, "e": 520, "s": 172, "text": "Python is a language of expressiveness in concise code, which is very elegant and easy to comprehend. List Comprehension provides a concise way to create lists. List Comprehension is the proper “pythonic” way of building an accessible, concise, and fast way to build lists. It allows one to perform complex operations on lists using a single line." }, { "code": null, "e": 1055, "s": 520, "text": "List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists. In the core of list comprehension, it is the loop (‘for’ loop). Any list comprehension we can represent as a for loop, but when we represent it with equivalent list comprehension in a single line, it looks genuinely unique." }, { "code": null, "e": 1102, "s": 1055, "text": "List comprehension has these essential parts :" }, { "code": null, "e": 1318, "s": 1102, "text": "An iterable input sequence (this could be a list, a range, or any sequence) that we iterate using a variable name.An output expressionAn optional condition for the variable to filter or map or do some logical action" }, { "code": null, "e": 1433, "s": 1318, "text": "An iterable input sequence (this could be a list, a range, or any sequence) that we iterate using a variable name." }, { "code": null, "e": 1454, "s": 1433, "text": "An output expression" }, { "code": null, "e": 1536, "s": 1454, "text": "An optional condition for the variable to filter or map or do some logical action" }, { "code": null, "e": 1747, "s": 1536, "text": "For example, if we want to create a square list from a list of variables from 1 to 5, we can do so as below using the standard for loop, but when we use a list comprehension, it becomes concise and lightweight." }, { "code": null, "e": 1813, "s": 1747, "text": "If we break-down the list comprehension parts, it looks as below." }, { "code": null, "e": 2075, "s": 1813, "text": "Thus here iterable is range(1,6), and x is the variable representing each value in the range. For each x (1,2,3,4,5) , output expression x*x calculates a corresponding output (1,4,9,16,25) which ultimately becomes the final output list (refer to above diagram)." }, { "code": null, "e": 2125, "s": 2075, "text": "Few Ways of Usage other than the basic construct:" }, { "code": null, "e": 2426, "s": 2125, "text": "List comprehensions provide a way to check for conditions and filter out the elements we don’t need from the input list for output. This filtering happens before the output expression takes place. Refer to the below example where we calculate square for only those variables which are divisible by 2." }, { "code": null, "e": 2596, "s": 2426, "text": "List Comprehension can be used to check nested conditions. Refer to the below code, where we want to find which all variables in the input list are divisible by 2,4 & 5." }, { "code": null, "e": 2865, "s": 2596, "text": "We can use an “if-else” in a list comprehension in Python. Refer to the code block below, which finds odd and even for a list of numbers. We need to specify what the output is first, following “if” condition and then “else” followed by what is the output under “else.”" }, { "code": null, "e": 2948, "s": 2865, "text": "Note, we can not print input value directly without using a comma and parenthesis." }, { "code": null, "e": 3048, "s": 2948, "text": "Suppose we have to flatten a 2D list. We can easily do it using List Comprehension using a sublist." }, { "code": null, "e": 3296, "s": 3048, "text": "How can we flatten a 3D list? It becomes a bit complex where first we flatten 3D to 2D and then 2D to 1D. In the below example blue underlined portion is the step that makes 2D flatten from a 3D list, and then the outer part does flattening to 1D." }, { "code": null, "e": 3885, "s": 3296, "text": "We can use list comprehension for multiple nested “for” loops. We have to careful in terms of the order of execution when we use nested list comprehension. Suppose we have a 3x3 square matrix, and we want to create a matrix using this matrix where all diagonal values need to be square while other values need to be zeros. Here the output is 1 dimensional, and we need additional logic to convert to 2D matrix form. Here I used “column” and “row” for explanation purposes but can be used directly in the “for loop” without the intermediate variables (as used in below List Comprehension)." }, { "code": null, "e": 4207, "s": 3885, "text": "matrix = [[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]]row = len(matrix)column = len(matrix[0])output = []for i in range(row): for j in range(column): if i == j: output.append(matrix[i][j] * matrix[i][j]) else: output.append(0) output[1, 0, 0, 0, 25, 0, 0, 0, 81]" }, { "code": null, "e": 4330, "s": 4207, "text": "Now we see equivalent nested list comprehension (single line only, but for easy understanding, I have made it in 3 lines)." }, { "code": null, "e": 4468, "s": 4330, "text": "[[matrix[i][j]*matrix[i][j] if i == j else 0 for i in range(len(matrix))] for j in range(len(matrix[0]))]" }, { "code": null, "e": 4894, "s": 4468, "text": "Now let’s understand this with a picture of how each loop is working. Loop execution order is top to bottom (bold green arrow). Inner loops (dark green ) we complete first, and then control comes back to the outer loop (blue). Here List Comprehension is one line in comparison to 5 lines of ordinary “for loop,” as shown above code. We can also get the matrix form of output directly by putting brackets after first for loop." }, { "code": null, "e": 5232, "s": 4894, "text": "One of the significant advantages of list comprehension is that developer need to write less codeList comprehension often becomes easier to understandThe speed of list comprehensions is notably better than for-loops when appending items to the listList comprehensions are an excellent alternative to the built-in map and filter functions" }, { "code": null, "e": 5330, "s": 5232, "text": "One of the significant advantages of list comprehension is that developer need to write less code" }, { "code": null, "e": 5384, "s": 5330, "text": "List comprehension often becomes easier to understand" }, { "code": null, "e": 5483, "s": 5384, "text": "The speed of list comprehensions is notably better than for-loops when appending items to the list" }, { "code": null, "e": 5573, "s": 5483, "text": "List comprehensions are an excellent alternative to the built-in map and filter functions" }, { "code": null, "e": 5783, "s": 5573, "text": "In Python, we have also “dictionary comprehensions” and “set comprehensions” that are similar in operation but meant for dictionary and set. Python also has “generator expression” which uses a “round” bracket." }, { "code": null, "e": 6092, "s": 5783, "text": "When I started my journey with Python, I used to find it challenging to understand how the list comprehension works. Once I understood its elegance and power, I never looked back. Even though it feels intimidating at first, with a bit of practice, every python lover can fall in love with List Comprehension." } ]
How to Web Scrape with Python in 4 Minutes | by Julia Kho | Towards Data Science
Web scraping is a technique to automatically access and extract large amounts of information from a website, which can save a huge amount of time and effort. In this article, we will go through an easy example of how to automate downloading hundreds of files from the New York MTA. This is a great exercise for web scraping beginners who are looking to understand how to web scrape. Web scraping can be slightly intimidating, so this tutorial will break down the process of how to go about the process. We will be downloading turnstile data from this site: http://web.mta.info/developers/turnstile.html Turnstile data is compiled every week from May 2010 to present, so hundreds of .txt files exist on the site. Below is a snippet of what some of the data looks like. Each date is a link to the .txt file that you can download. It would be torturous to manually right click on each link and save to your desktop. Luckily, there’s web-scraping! Read through the website’s Terms and Conditions to understand how you can legally use the data. Most sites prohibit you from using the data for commercial purposes.Make sure you are not downloading data at too rapid a rate because this may break the website. You may potentially be blocked from the site as well. Read through the website’s Terms and Conditions to understand how you can legally use the data. Most sites prohibit you from using the data for commercial purposes. Make sure you are not downloading data at too rapid a rate because this may break the website. You may potentially be blocked from the site as well. The first thing that we need to do is to figure out where we can locate the links to the files we want to download inside the multiple levels of HTML tags. Simply put, there is a lot of code on a website page and we want to find the relevant pieces of code that contains our data. If you are not familiar with HTML tags, refer to W3Schools Tutorials. It is important to understand the basics of HTML in order to successfully web scrape. On the website, right click and click on “Inspect”. This allows you to see the raw code behind the site. Once you’ve clicked on “Inspect”, you should see this console pop up. Notice that on the top left of the console, there is an arrow symbol. If you click on this arrow and then click on an area of the site itself, the code for that particular item will be highlighted in the console. I’ve clicked on the very first data file, Saturday, September 22, 2018 and the console has highlighted in blue the link to that particular file. <a href=”data/nyct/turnstile/turnstile_180922.txt”>Saturday, September 22, 2018</a> Notice that all the .txt files are inside the <a> tag following the line above. As you do more web scraping, you will find that the <a> is used for hyperlinks. Now that we’ve identified the location of the links, let’s get started on coding! We start by importing the following libraries. import requestsimport urllib.requestimport timefrom bs4 import BeautifulSoup Next, we set the url to the website and access the site with our requests library. url = 'http://web.mta.info/developers/turnstile.html'response = requests.get(url) If the access was successful, you should see the following output: Next we parse the html with BeautifulSoup so that we can work with a nicer, nested BeautifulSoup data structure. If you are interested in learning more about this library, check out the BeatifulSoup documentation. soup = BeautifulSoup(response.text, “html.parser”) We use the method .findAll to locate all of our <a> tags. soup.findAll('a') This code gives us every line of code that has an <a> tag. The information that we are interested in starts on line 38 as seen below. That is, the very first text file is located in line 38, so we want to grab the rest of the text files located below. Next, let’s extract the actual link that we want. Let’s test out the first link. one_a_tag = soup.findAll(‘a’)[38]link = one_a_tag[‘href’] This code saves the first text file, ‘data/nyct/turnstile/turnstile_180922.txt’ to our variable link. The full url to download the data is actually ‘http://web.mta.info/developers/data/nyct/turnstile/turnstile_180922.txt’ which I discovered by clicking on the first data file on the website as a test. We can use our urllib.request library to download this file path to our computer. We provide request.urlretrieve with two parameters: file url and the filename. For my files, I named them “turnstile_180922.txt”, “turnstile_180901”, etc. download_url = 'http://web.mta.info/developers/'+ linkurllib.request.urlretrieve(download_url,'./'+link[link.find('/turnstile_')+1:]) Last but not least, we should include this line of code so that we can pause our code for a second so that we are not spamming the website with requests. This helps us avoid getting flagged as a spammer. time.sleep(1) Now that we understand how to download a file, let’s try downloading the entire set of data files with a for loop. The code below contains the entire set of code for web scraping the NY MTA turnstile data. You can find my Jupyter Notebook for this on my Github. Thanks for reading and happy web scraping everyone!
[ { "code": null, "e": 675, "s": 172, "text": "Web scraping is a technique to automatically access and extract large amounts of information from a website, which can save a huge amount of time and effort. In this article, we will go through an easy example of how to automate downloading hundreds of files from the New York MTA. This is a great exercise for web scraping beginners who are looking to understand how to web scrape. Web scraping can be slightly intimidating, so this tutorial will break down the process of how to go about the process." }, { "code": null, "e": 729, "s": 675, "text": "We will be downloading turnstile data from this site:" }, { "code": null, "e": 775, "s": 729, "text": "http://web.mta.info/developers/turnstile.html" }, { "code": null, "e": 1000, "s": 775, "text": "Turnstile data is compiled every week from May 2010 to present, so hundreds of .txt files exist on the site. Below is a snippet of what some of the data looks like. Each date is a link to the .txt file that you can download." }, { "code": null, "e": 1116, "s": 1000, "text": "It would be torturous to manually right click on each link and save to your desktop. Luckily, there’s web-scraping!" }, { "code": null, "e": 1429, "s": 1116, "text": "Read through the website’s Terms and Conditions to understand how you can legally use the data. Most sites prohibit you from using the data for commercial purposes.Make sure you are not downloading data at too rapid a rate because this may break the website. You may potentially be blocked from the site as well." }, { "code": null, "e": 1594, "s": 1429, "text": "Read through the website’s Terms and Conditions to understand how you can legally use the data. Most sites prohibit you from using the data for commercial purposes." }, { "code": null, "e": 1743, "s": 1594, "text": "Make sure you are not downloading data at too rapid a rate because this may break the website. You may potentially be blocked from the site as well." }, { "code": null, "e": 2180, "s": 1743, "text": "The first thing that we need to do is to figure out where we can locate the links to the files we want to download inside the multiple levels of HTML tags. Simply put, there is a lot of code on a website page and we want to find the relevant pieces of code that contains our data. If you are not familiar with HTML tags, refer to W3Schools Tutorials. It is important to understand the basics of HTML in order to successfully web scrape." }, { "code": null, "e": 2285, "s": 2180, "text": "On the website, right click and click on “Inspect”. This allows you to see the raw code behind the site." }, { "code": null, "e": 2355, "s": 2285, "text": "Once you’ve clicked on “Inspect”, you should see this console pop up." }, { "code": null, "e": 2425, "s": 2355, "text": "Notice that on the top left of the console, there is an arrow symbol." }, { "code": null, "e": 2713, "s": 2425, "text": "If you click on this arrow and then click on an area of the site itself, the code for that particular item will be highlighted in the console. I’ve clicked on the very first data file, Saturday, September 22, 2018 and the console has highlighted in blue the link to that particular file." }, { "code": null, "e": 2797, "s": 2713, "text": "<a href=”data/nyct/turnstile/turnstile_180922.txt”>Saturday, September 22, 2018</a>" }, { "code": null, "e": 2957, "s": 2797, "text": "Notice that all the .txt files are inside the <a> tag following the line above. As you do more web scraping, you will find that the <a> is used for hyperlinks." }, { "code": null, "e": 3039, "s": 2957, "text": "Now that we’ve identified the location of the links, let’s get started on coding!" }, { "code": null, "e": 3086, "s": 3039, "text": "We start by importing the following libraries." }, { "code": null, "e": 3163, "s": 3086, "text": "import requestsimport urllib.requestimport timefrom bs4 import BeautifulSoup" }, { "code": null, "e": 3246, "s": 3163, "text": "Next, we set the url to the website and access the site with our requests library." }, { "code": null, "e": 3328, "s": 3246, "text": "url = 'http://web.mta.info/developers/turnstile.html'response = requests.get(url)" }, { "code": null, "e": 3395, "s": 3328, "text": "If the access was successful, you should see the following output:" }, { "code": null, "e": 3609, "s": 3395, "text": "Next we parse the html with BeautifulSoup so that we can work with a nicer, nested BeautifulSoup data structure. If you are interested in learning more about this library, check out the BeatifulSoup documentation." }, { "code": null, "e": 3660, "s": 3609, "text": "soup = BeautifulSoup(response.text, “html.parser”)" }, { "code": null, "e": 3718, "s": 3660, "text": "We use the method .findAll to locate all of our <a> tags." }, { "code": null, "e": 3736, "s": 3718, "text": "soup.findAll('a')" }, { "code": null, "e": 3988, "s": 3736, "text": "This code gives us every line of code that has an <a> tag. The information that we are interested in starts on line 38 as seen below. That is, the very first text file is located in line 38, so we want to grab the rest of the text files located below." }, { "code": null, "e": 4069, "s": 3988, "text": "Next, let’s extract the actual link that we want. Let’s test out the first link." }, { "code": null, "e": 4127, "s": 4069, "text": "one_a_tag = soup.findAll(‘a’)[38]link = one_a_tag[‘href’]" }, { "code": null, "e": 4666, "s": 4127, "text": "This code saves the first text file, ‘data/nyct/turnstile/turnstile_180922.txt’ to our variable link. The full url to download the data is actually ‘http://web.mta.info/developers/data/nyct/turnstile/turnstile_180922.txt’ which I discovered by clicking on the first data file on the website as a test. We can use our urllib.request library to download this file path to our computer. We provide request.urlretrieve with two parameters: file url and the filename. For my files, I named them “turnstile_180922.txt”, “turnstile_180901”, etc." }, { "code": null, "e": 4800, "s": 4666, "text": "download_url = 'http://web.mta.info/developers/'+ linkurllib.request.urlretrieve(download_url,'./'+link[link.find('/turnstile_')+1:])" }, { "code": null, "e": 5004, "s": 4800, "text": "Last but not least, we should include this line of code so that we can pause our code for a second so that we are not spamming the website with requests. This helps us avoid getting flagged as a spammer." }, { "code": null, "e": 5018, "s": 5004, "text": "time.sleep(1)" }, { "code": null, "e": 5224, "s": 5018, "text": "Now that we understand how to download a file, let’s try downloading the entire set of data files with a for loop. The code below contains the entire set of code for web scraping the NY MTA turnstile data." }, { "code": null, "e": 5280, "s": 5224, "text": "You can find my Jupyter Notebook for this on my Github." } ]
Sort list of dictionaries by values in C#
Firstly, let us create a dictionary − var d = new Dictionary<string, int>(5); Now add the key and value − // add key and value d.Add("car", 25); d.Add("bus", 28); d.Add("motorbike", 17); Use orderby to order by values − var val = from ele in d orderby ele.Value ascending select ele; We have set ascending above to sort the dictionary in ascending order. You can also use descending. Display the values in ascending order − foreach (KeyValuePair ele in val) { Console.WriteLine("{0} = {1}", ele.Key, ele.Value); }
[ { "code": null, "e": 1100, "s": 1062, "text": "Firstly, let us create a dictionary −" }, { "code": null, "e": 1140, "s": 1100, "text": "var d = new Dictionary<string, int>(5);" }, { "code": null, "e": 1168, "s": 1140, "text": "Now add the key and value −" }, { "code": null, "e": 1249, "s": 1168, "text": "// add key and value\nd.Add(\"car\", 25);\nd.Add(\"bus\", 28);\nd.Add(\"motorbike\", 17);" }, { "code": null, "e": 1282, "s": 1249, "text": "Use orderby to order by values −" }, { "code": null, "e": 1346, "s": 1282, "text": "var val = from ele in d\norderby ele.Value ascending\nselect ele;" }, { "code": null, "e": 1446, "s": 1346, "text": "We have set ascending above to sort the dictionary in ascending order. You can also use descending." }, { "code": null, "e": 1486, "s": 1446, "text": "Display the values in ascending order −" }, { "code": null, "e": 1579, "s": 1486, "text": "foreach (KeyValuePair ele in val) {\n Console.WriteLine(\"{0} = {1}\", ele.Key, ele.Value);\n}" } ]
Delete one row and reorder the others with the correct ID in MySQL?
To understand the concept, let us first create a table. The query to create a table is as follows mysql> create table ReorderSortDemo -> ( -> UserId int -> ); Query OK, 0 rows affected (0.57 sec) Insert some records in the table using insert command. The query is as follows − mysql> insert into ReorderSortDemo values(14); Query OK, 1 row affected (0.13 sec) mysql> insert into ReorderSortDemo values(4); Query OK, 1 row affected (0.10 sec) mysql> insert into ReorderSortDemo values(6); Query OK, 1 row affected (0.11 sec) mysql> insert into ReorderSortDemo values(3); Query OK, 1 row affected (0.09 sec) mysql> insert into ReorderSortDemo values(8); Query OK, 1 row affected (0.11 sec) mysql> insert into ReorderSortDemo values(18); Query OK, 1 row affected (0.08 sec) mysql> insert into ReorderSortDemo values(1); Query OK, 1 row affected (0.12 sec) mysql> insert into ReorderSortDemo values(11); Query OK, 1 row affected (0.08 sec) mysql> insert into ReorderSortDemo values(16); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from ReorderSortDemo; The following is the output +--------+ | UserId | +--------+ | 14 | | 4 | | 6 | | 3 | | 8 | | 18 | | 1 | | 11 | | 16 | +--------+ 9 rows in set (0.00 sec) First delete one row from the table then use update command to reorder the others. The query is as follows − mysql> delete from ReorderSortDemo where UserId=8; Query OK, 1 row affected (0.20 sec) After deleting, let us check the table records once again. The query is as follows − mysql> select *from ReorderSortDemo; The output is as follows +--------+ | UserId | +--------+ | 14 | | 4 | | 6 | | 3 | | 18 | | 1 | | 11 | | 16 | +--------+ 8 rows in set (0.00 sec) Here is the query to reorder the other columns mysql> update ReorderSortDemo -> set UserId=UserId-1 -> where UserId > 8; Query OK, 4 rows affected (0.22 sec) Rows matched: 4 Changed: 4 Warnings: 0 Let us check the table records once again. The query is as follows − mysql> select *from ReorderSortDemo; The output is as follows +--------+ | UserId | +--------+ | 13 | | 4 | | 6 | | 3 | | 17 | | 1 | | 10 | | 15 | +--------+ 8 rows in set (0.00 sec)
[ { "code": null, "e": 1160, "s": 1062, "text": "To understand the concept, let us first create a table. The query to create a table is as follows" }, { "code": null, "e": 1267, "s": 1160, "text": "mysql> create table ReorderSortDemo\n -> (\n -> UserId int\n -> );\nQuery OK, 0 rows affected (0.57 sec)" }, { "code": null, "e": 1348, "s": 1267, "text": "Insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2090, "s": 1348, "text": "mysql> insert into ReorderSortDemo values(14);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into ReorderSortDemo values(4);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into ReorderSortDemo values(6);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into ReorderSortDemo values(3);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into ReorderSortDemo values(8);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into ReorderSortDemo values(18);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into ReorderSortDemo values(1);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into ReorderSortDemo values(11);\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into ReorderSortDemo values(16);\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 2175, "s": 2090, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2212, "s": 2175, "text": "mysql> select *from ReorderSortDemo;" }, { "code": null, "e": 2240, "s": 2212, "text": "The following is the output" }, { "code": null, "e": 2408, "s": 2240, "text": "+--------+\n| UserId |\n+--------+\n| 14 |\n| 4 |\n| 6 |\n| 3 |\n| 8 |\n| 18 |\n| 1 |\n| 11 |\n| 16 |\n+--------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2517, "s": 2408, "text": "First delete one row from the table then use update command to reorder the others. The query is as follows −" }, { "code": null, "e": 2604, "s": 2517, "text": "mysql> delete from ReorderSortDemo where UserId=8;\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 2689, "s": 2604, "text": "After deleting, let us check the table records once again. The query is as follows −" }, { "code": null, "e": 2726, "s": 2689, "text": "mysql> select *from ReorderSortDemo;" }, { "code": null, "e": 2751, "s": 2726, "text": "The output is as follows" }, { "code": null, "e": 2908, "s": 2751, "text": "+--------+\n| UserId |\n+--------+\n| 14 |\n| 4 |\n| 6 |\n| 3 |\n| 18 |\n| 1 |\n| 11 |\n| 16 |\n+--------+\n8 rows in set (0.00 sec)" }, { "code": null, "e": 2955, "s": 2908, "text": "Here is the query to reorder the other columns" }, { "code": null, "e": 3111, "s": 2955, "text": "mysql> update ReorderSortDemo\n -> set UserId=UserId-1\n -> where UserId > 8;\nQuery OK, 4 rows affected (0.22 sec)\nRows matched: 4 Changed: 4 Warnings: 0" }, { "code": null, "e": 3180, "s": 3111, "text": "Let us check the table records once again. The query is as follows −" }, { "code": null, "e": 3217, "s": 3180, "text": "mysql> select *from ReorderSortDemo;" }, { "code": null, "e": 3242, "s": 3217, "text": "The output is as follows" }, { "code": null, "e": 3399, "s": 3242, "text": "+--------+\n| UserId |\n+--------+\n| 13 |\n| 4 |\n| 6 |\n| 3 |\n| 17 |\n| 1 |\n| 10 |\n| 15 |\n+--------+\n8 rows in set (0.00 sec)" } ]
Preorder Traversal | Practice | GeeksforGeeks
Given a binary tree, find its preorder traversal. Example 1: Input: 1 / 4 / \ 4 2 Output: 1 4 4 2 Example 2: Input: 6 / \ 3 2 \ / 1 2 Output: 6 3 1 2 2 Your Task: You just have to complete the function preorder() which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= Number of nodes <= 104 0 <= Data of a node <= 105 0 superrhitik4582 days ago vector<int> vi;void pre(Node* root){ if(root!=NULL){ vi.push_back(root->data); pre(root->left); pre(root->right);} return;}vector <int> preorder(Node* root){ // Your code herepre(root); vector<int> res=vi;//v=vi; vi.clear();// for(int i=0;i<v.size();i++)//cout<<v[i]<<" ";return res;} 0 itachinamikaze2211 week ago JAVA static ArrayList<Integer> preorder(Node root) { ArrayList<Integer> res= new ArrayList<>(); if(root==null) return res; Stack<Node> st= new Stack<Node>(); st.push(root); while(st.isEmpty()==false) { root=st.pop(); res.add(root.data); if(root.right!=null) st.push(root.right); if(root.left!=null) st.push(root.left); } return res;} +1 singh.shobhit0071 week ago If someone is wondering why there solution is not working when they are declaring a global vector, it cause there are multiple entries for being made in the vector for different testcases and the array is not being cleared, use array.clear to clean your array before using that assign the value of array to a temp vector and return the temp, it should work for reference vector<int> arr;void preOrder(Node *root){ if(root == nullptr) return; arr.push_back(root->data);; preOrder(root->left); preOrder(root->right); return;} vector <int> preorder(Node* root){ // Your code here preOrder(root); vector<int> res = arr; arr.clear(); return res;} 0 harshscode2 weeks ago void findpre(Node *root,vector<int> &v){ if(!root) return; v.push_back(root->data); findpre(root->left,v); findpre(root->right,v); }//Function to return a list containing the preorder traversal of the tree.vector <int> preorder(Node* root){ vector<int> v; findpre(root,v); return v; } 0 hharshit81182 weeks ago vector<int> preorder(Node* root){vector<int> v;stack<Node*> st;st.push(root);while(st.empty() == false){ Node* curr = st.top(); st.pop(); v.push_back(curr->data); if(curr->right){ st.push(curr->right); } if(curr->left){ st.push(curr->left); }}return v;} 0 mangy007 This comment was deleted. 0 meanm0nst3r2 weeks ago What's the error?someone please commentCode:vector <int> preorder(Node* root){ // Your code here Node* curr=root; vector<int> v; if(!curr) return v; v.push_back(curr->data); preorder(curr->left); preorder(curr->right); return v;} 0 sagrikasoni3 weeks ago JAVA Solution static ArrayList<Integer> preorder(Node root) { ArrayList<Integer> arr = new ArrayList<Integer>(); if(root==null) return arr; Stack<Node> q = new Stack<Node>(); q.push(root); while(!q.isEmpty()){ Node curr = q.pop(); arr.add(curr.data); if(curr.right!=null) q.push(curr.right); if(curr.left!=null) q.push(curr.left); } return arr; } 0 talmeezahmed7864 weeks ago #Iterative python solution, for more performance #replace the queue with deque def preorder(root): # code here result = [] # initialize our process queue queue = [] size = 0 # push the root node to our queue queue.append(root) size = size + 1 while (size > 0): # process the node at front of queue currentNode = queue[0] queue = queue[1:] size = size - 1 # process the root first if (currentNode.data != None): result.append(currentNode.data) # process the right node if (currentNode.right and currentNode.right.data != None): queue.insert(0, currentNode.right) size = size + 1 # process the left node if (currentNode.left and currentNode.left.data != None): queue.insert(0, currentNode.left) size = size + 1 return result 0 bsbh20is1 month ago int arr[10000]; void pre(struct Node*node,int *i){ if(node==NULL) return; arr[(*i)]=node->data; (*i)=(*i)+1; pre(node->left,i); pre(node->right,i); } int* preorder(struct Node* root){ //code here int ind=0; pre(root,&ind); return arr; //do not change the default values(i.e -1) in the unused array indices.} 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": 278, "text": "Given a binary tree, find its preorder traversal." }, { "code": null, "e": 339, "s": 328, "text": "Example 1:" }, { "code": null, "e": 430, "s": 339, "text": "Input:\n 1 \n / \n 4 \n / \\ \n4 2\nOutput: 1 4 4 2 \n" }, { "code": null, "e": 441, "s": 430, "text": "Example 2:" }, { "code": null, "e": 523, "s": 441, "text": "Input:\n 6\n / \\\n 3 2\n \\ / \n 1 2\nOutput: 6 3 1 2 2 \n\n" }, { "code": null, "e": 699, "s": 523, "text": "Your Task:\nYou just have to complete the function preorder() which takes the root node of the tree as input and returns an array containing the preorder traversal of the tree." }, { "code": null, "e": 763, "s": 699, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 831, "s": 763, "text": "Constraints:\n1 <= Number of nodes <= 104\n0 <= Data of a node <= 105" }, { "code": null, "e": 833, "s": 831, "text": "0" }, { "code": null, "e": 858, "s": 833, "text": "superrhitik4582 days ago" }, { "code": null, "e": 1082, "s": 858, "text": "vector<int> vi;void pre(Node* root){ if(root!=NULL){ vi.push_back(root->data); pre(root->left); pre(root->right);} return;}vector <int> preorder(Node* root){ // Your code herepre(root); vector<int> res=vi;//v=vi;" }, { "code": null, "e": 1154, "s": 1082, "text": "vi.clear();// for(int i=0;i<v.size();i++)//cout<<v[i]<<\" \";return res;}" }, { "code": null, "e": 1156, "s": 1154, "text": "0" }, { "code": null, "e": 1184, "s": 1156, "text": "itachinamikaze2211 week ago" }, { "code": null, "e": 1189, "s": 1184, "text": "JAVA" }, { "code": null, "e": 1649, "s": 1189, "text": "static ArrayList<Integer> preorder(Node root) { ArrayList<Integer> res= new ArrayList<>(); if(root==null) return res; Stack<Node> st= new Stack<Node>(); st.push(root); while(st.isEmpty()==false) { root=st.pop(); res.add(root.data); if(root.right!=null) st.push(root.right); if(root.left!=null) st.push(root.left); } return res;}" }, { "code": null, "e": 1652, "s": 1649, "text": "+1" }, { "code": null, "e": 1679, "s": 1652, "text": "singh.shobhit0071 week ago" }, { "code": null, "e": 2037, "s": 1679, "text": "If someone is wondering why there solution is not working when they are declaring a global vector, it cause there are multiple entries for being made in the vector for different testcases and the array is not being cleared, use array.clear to clean your array before using that assign the value of array to a temp vector and return the temp, it should work " }, { "code": null, "e": 2053, "s": 2039, "text": "for reference" }, { "code": null, "e": 2222, "s": 2053, "text": "vector<int> arr;void preOrder(Node *root){ if(root == nullptr) return; arr.push_back(root->data);; preOrder(root->left); preOrder(root->right); return;}" }, { "code": null, "e": 2340, "s": 2222, "text": "vector <int> preorder(Node* root){ // Your code here preOrder(root); vector<int> res = arr; arr.clear(); return res;}" }, { "code": null, "e": 2342, "s": 2340, "text": "0" }, { "code": null, "e": 2364, "s": 2342, "text": "harshscode2 weeks ago" }, { "code": null, "e": 2678, "s": 2364, "text": "void findpre(Node *root,vector<int> &v){ if(!root) return; v.push_back(root->data); findpre(root->left,v); findpre(root->right,v); }//Function to return a list containing the preorder traversal of the tree.vector <int> preorder(Node* root){ vector<int> v; findpre(root,v); return v; }" }, { "code": null, "e": 2680, "s": 2678, "text": "0" }, { "code": null, "e": 2704, "s": 2680, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 2984, "s": 2704, "text": "vector<int> preorder(Node* root){vector<int> v;stack<Node*> st;st.push(root);while(st.empty() == false){ Node* curr = st.top(); st.pop(); v.push_back(curr->data); if(curr->right){ st.push(curr->right); } if(curr->left){ st.push(curr->left); }}return v;}" }, { "code": null, "e": 2986, "s": 2984, "text": "0" }, { "code": null, "e": 2995, "s": 2986, "text": "mangy007" }, { "code": null, "e": 3021, "s": 2995, "text": "This comment was deleted." }, { "code": null, "e": 3023, "s": 3021, "text": "0" }, { "code": null, "e": 3046, "s": 3023, "text": "meanm0nst3r2 weeks ago" }, { "code": null, "e": 3277, "s": 3046, "text": "What's the error?someone please commentCode:vector <int> preorder(Node* root){ // Your code here Node* curr=root; vector<int> v; if(!curr) return v; v.push_back(curr->data); preorder(curr->left); preorder(curr->right); return v;}" }, { "code": null, "e": 3279, "s": 3277, "text": "0" }, { "code": null, "e": 3302, "s": 3279, "text": "sagrikasoni3 weeks ago" }, { "code": null, "e": 3316, "s": 3302, "text": "JAVA Solution" }, { "code": null, "e": 3791, "s": 3316, "text": " static ArrayList<Integer> preorder(Node root)\n {\n ArrayList<Integer> arr = new ArrayList<Integer>();\n if(root==null) return arr;\n Stack<Node> q = new Stack<Node>();\n q.push(root);\n while(!q.isEmpty()){\n Node curr = q.pop();\n arr.add(curr.data);\n if(curr.right!=null)\n q.push(curr.right);\n if(curr.left!=null)\n q.push(curr.left);\n \n }\n \n return arr;\n }" }, { "code": null, "e": 3793, "s": 3791, "text": "0" }, { "code": null, "e": 3820, "s": 3793, "text": "talmeezahmed7864 weeks ago" }, { "code": null, "e": 4772, "s": 3820, "text": "#Iterative python solution, for more performance \n#replace the queue with deque\n\ndef preorder(root):\n \n # code here\n result = []\n\n # initialize our process queue\n queue = []\n size = 0\n\n # push the root node to our queue\n queue.append(root)\n size = size + 1\n\n while (size > 0):\n\n # process the node at front of queue\n currentNode = queue[0]\n queue = queue[1:]\n size = size - 1\n\n # process the root first\n if (currentNode.data != None):\n result.append(currentNode.data)\n \n # process the right node\n if (currentNode.right and currentNode.right.data != None):\n queue.insert(0, currentNode.right)\n size = size + 1\n \n # process the left node\n if (currentNode.left and currentNode.left.data != None):\n queue.insert(0, currentNode.left)\n size = size + 1\n\n \n\n return result\n" }, { "code": null, "e": 4774, "s": 4772, "text": "0" }, { "code": null, "e": 4794, "s": 4774, "text": "bsbh20is1 month ago" }, { "code": null, "e": 4810, "s": 4794, "text": "int arr[10000];" }, { "code": null, "e": 4963, "s": 4810, "text": "void pre(struct Node*node,int *i){ if(node==NULL) return; arr[(*i)]=node->data; (*i)=(*i)+1; pre(node->left,i); pre(node->right,i); }" }, { "code": null, "e": 5133, "s": 4963, "text": "int* preorder(struct Node* root){ //code here int ind=0; pre(root,&ind); return arr; //do not change the default values(i.e -1) in the unused array indices.}" }, { "code": null, "e": 5279, "s": 5133, "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": 5315, "s": 5279, "text": " Login to access your submissions. " }, { "code": null, "e": 5325, "s": 5315, "text": "\nProblem\n" }, { "code": null, "e": 5335, "s": 5325, "text": "\nContest\n" }, { "code": null, "e": 5398, "s": 5335, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5546, "s": 5398, "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": 5754, "s": 5546, "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": 5860, "s": 5754, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to check if a string is alphanumeric in Python?
Python String class has a method called isalnum() which can be called on a string and tells us if the string consists only of alphanumerics or not. You can call it in the following way: >>> '123abc'.isalnum() True >>> '123#$%abc'.isalnum() False You can also use regexes for the same result. For matching alpha numerics, we can call the re.match(regex, string) using the regex: "^[a-zA-Z0-9]+$". For example, >>> bool(re.match('^[a-zA-Z0-9]+$', '123abc')) True >>> bool(re.match('^[a-zA-Z0-9]+$', '123#$%abc')) False re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
[ { "code": null, "e": 1248, "s": 1062, "text": "Python String class has a method called isalnum() which can be called on a string and tells us if the string consists only of alphanumerics or not. You can call it in the following way:" }, { "code": null, "e": 1308, "s": 1248, "text": ">>> '123abc'.isalnum()\nTrue\n>>> '123#$%abc'.isalnum()\nFalse" }, { "code": null, "e": 1471, "s": 1308, "text": "You can also use regexes for the same result. For matching alpha numerics, we can call the re.match(regex, string) using the regex: \"^[a-zA-Z0-9]+$\". For example," }, { "code": null, "e": 1579, "s": 1471, "text": ">>> bool(re.match('^[a-zA-Z0-9]+$', '123abc'))\nTrue\n>>> bool(re.match('^[a-zA-Z0-9]+$', '123#$%abc'))\nFalse" }, { "code": null, "e": 1686, "s": 1579, "text": "re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool()." } ]
Enhance Your Plotly Express Scatter Plot With Marginal Plots | by Andy McDonald | Towards Data Science
Scatter plots are a commonly used data visualisation tool within data science. They allow us to plot two numerical variables, as points, on a two dimensional graph. From these plots, we can understand if there is a relationship between the two variables, and what the strength of that relationship is. Within this short tutorial, we are going to use the excellent Plotly library to visualise a data set, and we are going to see how to add marginal plots to the edges of the y, and x-axis to enhance our visualisation and understanding of the data. I have covered creating scatter plots in plotly and matplotlib, which you can find below: Creating Scatter Plots of Well Log Data Using matplotlib in Python Using Plotly Express to Create Interactive Scatter Plots Part of this tutorial is covered in my Plotly Scatter Plots video Plotly is a web-based toolkit that is used to generate powerful and interactive data visualisations. It is very efficient and plots can be generated with very few lines of code. It is a popular library that contains a wide range of charts, including statistical, financial, maps, machine learning, and much more. The Plotly library can be used in two main ways: Plotly Graph Objects, which is a low-level interface for creating figures, traces, and layouts Plotly Express, which is a high level wrapper around Plotly Graph Objects. Plotly Express allows users to type much simpler syntax to generate the same plot. Loading Libraries & Data The first step is to load in pandas, which will be used to for loading our data, and plotly.express for viewing the data. import pandas as pdimport plotly.express as px Once the libraries have been imported, we can import our data. The dataset we will be using for this article comes from a Machine Learning competition for lithology prediction that was run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements. To download the file, navigate to the Data section of the link above. The original data source can be downloaded at: https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition df = pd.read_csv('xeek_subset_example.csv') We can then call upon df to view the first five and last five rows of the dataframe. What we get back is the above dataframe. Our dataset contains two well log measurements (RHOB- Bulk Density and NPHI- Neutron Porosity), a Depth curve and a geologically interpreted lithology. Creating Scatter Plots with Plotly Express is a very simple, we specify the dataframe and the columns we want to plot. px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH') This returns the following scatter plot. At the moment it looks a little messy as many of the lithologies have overlapping values. This occurs as the interpreted lithology would have been created based on a number of different logging measurements and cuttings descriptions. Individual LITH groups can be hidden by clicking on the name of the LITH in the legend. Marginal plots are mini plots that can be attached to the margins of the y and x axes. There are four different types of marginal plots available within Plotly Express. A boxplot is a graphical and standardised way to display the distribution of data based on five key numbers: The “minimum”, 1st Quartile (25th percentile), median (2nd Quartile./ 50th Percentile), the 3rd Quartile (75th percentile), and the “maximum”. The minimum and maximum values are defined as Q1–1.5 * IQR and Q3 + 1.5 * IQR respectively. Any points that fall outside of these limits are referred to as outliers. Marginal boxplots can be added to a single axes like so px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='box') Or to both axes by specifying values for marginal_y and marginal_x keyword arguments. px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='box', marginal_x='box') Rug plots are used to visualise the distribution of data and can be added as follows: px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='rug', marginal_x='rug') Histograms are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume end points from a gamma ray. To change the marginal plots to histograms, we do so as follows: px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='histogram', marginal_x='histogram') Violin plots are similar to boxplots, but they also combine the power of kernel density estimation plots. In addition to illustrating the key statistical points that a boxplot shows, it also allows us to gain an insight into the distribution of the data. px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='violin', marginal_x='violin') You don’t have to have the same plot on both axes, you can use a histogram on the x-axis and a violin plot on the y-axis. px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='violin', marginal_x='histogram') In this short tutorial we have seen how to display a variety of marginal plots on a plotly express scatter plot using well log data. These plots can enhance our data visualisations and provide us with further information about the data distribution. Thanks for reading! If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub. If you want to get in touch you can find me on LinkedIn or at my website. Interested in learning more about python and well log data or petrophysics? Follow me on Medium. If you enjoy reading these tutorials and want to support me as a writer and creator, then please consider signing up to become a Medium member. It’s $5 a month and you get unlimited access to many thousands of articles on a wide range of topics. If you sign up using my link, I will earn a small commission with no extra cost to you!
[ { "code": null, "e": 474, "s": 172, "text": "Scatter plots are a commonly used data visualisation tool within data science. They allow us to plot two numerical variables, as points, on a two dimensional graph. From these plots, we can understand if there is a relationship between the two variables, and what the strength of that relationship is." }, { "code": null, "e": 720, "s": 474, "text": "Within this short tutorial, we are going to use the excellent Plotly library to visualise a data set, and we are going to see how to add marginal plots to the edges of the y, and x-axis to enhance our visualisation and understanding of the data." }, { "code": null, "e": 810, "s": 720, "text": "I have covered creating scatter plots in plotly and matplotlib, which you can find below:" }, { "code": null, "e": 877, "s": 810, "text": "Creating Scatter Plots of Well Log Data Using matplotlib in Python" }, { "code": null, "e": 934, "s": 877, "text": "Using Plotly Express to Create Interactive Scatter Plots" }, { "code": null, "e": 1000, "s": 934, "text": "Part of this tutorial is covered in my Plotly Scatter Plots video" }, { "code": null, "e": 1313, "s": 1000, "text": "Plotly is a web-based toolkit that is used to generate powerful and interactive data visualisations. It is very efficient and plots can be generated with very few lines of code. It is a popular library that contains a wide range of charts, including statistical, financial, maps, machine learning, and much more." }, { "code": null, "e": 1362, "s": 1313, "text": "The Plotly library can be used in two main ways:" }, { "code": null, "e": 1457, "s": 1362, "text": "Plotly Graph Objects, which is a low-level interface for creating figures, traces, and layouts" }, { "code": null, "e": 1615, "s": 1457, "text": "Plotly Express, which is a high level wrapper around Plotly Graph Objects. Plotly Express allows users to type much simpler syntax to generate the same plot." }, { "code": null, "e": 1640, "s": 1615, "text": "Loading Libraries & Data" }, { "code": null, "e": 1762, "s": 1640, "text": "The first step is to load in pandas, which will be used to for loading our data, and plotly.express for viewing the data." }, { "code": null, "e": 1809, "s": 1762, "text": "import pandas as pdimport plotly.express as px" }, { "code": null, "e": 1872, "s": 1809, "text": "Once the libraries have been imported, we can import our data." }, { "code": null, "e": 2479, "s": 1872, "text": "The dataset we will be using for this article comes from a Machine Learning competition for lithology prediction that was run by Xeek and FORCE (https://xeek.ai/challenges/force-well-logs/overview). The objective of the competition was to predict lithology from a dataset consisting 98 training wells each with varying degrees of log completeness. The objective was to predict lithofacies based on the log measurements. To download the file, navigate to the Data section of the link above. The original data source can be downloaded at: https://github.com/bolgebrygg/Force-2020-Machine-Learning-competition" }, { "code": null, "e": 2523, "s": 2479, "text": "df = pd.read_csv('xeek_subset_example.csv')" }, { "code": null, "e": 2608, "s": 2523, "text": "We can then call upon df to view the first five and last five rows of the dataframe." }, { "code": null, "e": 2801, "s": 2608, "text": "What we get back is the above dataframe. Our dataset contains two well log measurements (RHOB- Bulk Density and NPHI- Neutron Porosity), a Depth curve and a geologically interpreted lithology." }, { "code": null, "e": 2920, "s": 2801, "text": "Creating Scatter Plots with Plotly Express is a very simple, we specify the dataframe and the columns we want to plot." }, { "code": null, "e": 3011, "s": 2920, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH')" }, { "code": null, "e": 3286, "s": 3011, "text": "This returns the following scatter plot. At the moment it looks a little messy as many of the lithologies have overlapping values. This occurs as the interpreted lithology would have been created based on a number of different logging measurements and cuttings descriptions." }, { "code": null, "e": 3374, "s": 3286, "text": "Individual LITH groups can be hidden by clicking on the name of the LITH in the legend." }, { "code": null, "e": 3543, "s": 3374, "text": "Marginal plots are mini plots that can be attached to the margins of the y and x axes. There are four different types of marginal plots available within Plotly Express." }, { "code": null, "e": 3961, "s": 3543, "text": "A boxplot is a graphical and standardised way to display the distribution of data based on five key numbers: The “minimum”, 1st Quartile (25th percentile), median (2nd Quartile./ 50th Percentile), the 3rd Quartile (75th percentile), and the “maximum”. The minimum and maximum values are defined as Q1–1.5 * IQR and Q3 + 1.5 * IQR respectively. Any points that fall outside of these limits are referred to as outliers." }, { "code": null, "e": 4017, "s": 3961, "text": "Marginal boxplots can be added to a single axes like so" }, { "code": null, "e": 4136, "s": 4017, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='box')" }, { "code": null, "e": 4222, "s": 4136, "text": "Or to both axes by specifying values for marginal_y and marginal_x keyword arguments." }, { "code": null, "e": 4359, "s": 4222, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='box', marginal_x='box')" }, { "code": null, "e": 4445, "s": 4359, "text": "Rug plots are used to visualise the distribution of data and can be added as follows:" }, { "code": null, "e": 4582, "s": 4445, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='rug', marginal_x='rug')" }, { "code": null, "e": 5043, "s": 4582, "text": "Histograms are an excellent data visualisation tool and appear similar to bar charts. However, histograms allow us to gain insights about the distribution of the values within a set of data and allow us to display a large range of data in a concise plot. Within the petrophysics and geoscience domains, we can use histograms to identify outliers and also pick key interpretation parameters. For example, clay volume or shale volume end points from a gamma ray." }, { "code": null, "e": 5108, "s": 5043, "text": "To change the marginal plots to histograms, we do so as follows:" }, { "code": null, "e": 5257, "s": 5108, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='histogram', marginal_x='histogram')" }, { "code": null, "e": 5512, "s": 5257, "text": "Violin plots are similar to boxplots, but they also combine the power of kernel density estimation plots. In addition to illustrating the key statistical points that a boxplot shows, it also allows us to gain an insight into the distribution of the data." }, { "code": null, "e": 5655, "s": 5512, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='violin', marginal_x='violin')" }, { "code": null, "e": 5777, "s": 5655, "text": "You don’t have to have the same plot on both axes, you can use a histogram on the x-axis and a violin plot on the y-axis." }, { "code": null, "e": 5923, "s": 5777, "text": "px.scatter(data_frame=df, x='NPHI', y='RHOB', range_x=[0, 1],range_y=[3, 1], color='LITH', marginal_y='violin', marginal_x='histogram')" }, { "code": null, "e": 6173, "s": 5923, "text": "In this short tutorial we have seen how to display a variety of marginal plots on a plotly express scatter plot using well log data. These plots can enhance our data visualisations and provide us with further information about the data distribution." }, { "code": null, "e": 6193, "s": 6173, "text": "Thanks for reading!" }, { "code": null, "e": 6405, "s": 6193, "text": "If you have found this article useful, please feel free to check out my other articles looking at various aspects of Python and well log data. You can also find my code used in this article and others at GitHub." }, { "code": null, "e": 6479, "s": 6405, "text": "If you want to get in touch you can find me on LinkedIn or at my website." }, { "code": null, "e": 6576, "s": 6479, "text": "Interested in learning more about python and well log data or petrophysics? Follow me on Medium." } ]
How to Serve Static Content using Node.js ? - GeeksforGeeks
27 Apr, 2020 Accessing static files are very useful when you want to put your static content accessible to the server for usage. To serve static files such as images, CSS files, and JavaScript files, etc we use the built-in middleware in node.js i.e. express.static. Setting up static middleware: You need to create a folder and add a file. For example, app.js, To run this file you need to run the following command.node app.jsNow create a folder whose content you want to serve as static, For example, you can create a folder named public.Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder.To serve this folder as static, you need the write this middleware in your index.js as follow:app.use(express.static(path.join(__dirname, 'public')))where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.Now create a EJS file like Demo.ejs and put this file in views folder. You need to create a folder and add a file. For example, app.js, To run this file you need to run the following command.node app.js node app.js Now create a folder whose content you want to serve as static, For example, you can create a folder named public. Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder. To serve this folder as static, you need the write this middleware in your index.js as follow:app.use(express.static(path.join(__dirname, 'public')))where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept. Now create a EJS file like Demo.ejs and put this file in views folder. Filename: Demo.ejs <!DOCTYPE html><html><head> <title>Static Middleware Demo</title></head><body> <img src="/GeeksLogo.png" width="600" height="600" /></body></html> Filename: app.js const express = require('express')const path = require('path')const app = express() // Static Middlewareapp.use(express.static(path.join(__dirname, 'public'))) // View Engine Setupapp.set('views', path.join(__dirname, 'views'))app.set('view engine', 'ejs') app.get('/', function(req, res){ res.render('Demo')}) app.listen(8080, function(error){ if(error) throw error console.log("Server created Successfully")}) Steps to run the program: The project structure will look like this:Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejsnpm install expressRun app.js file using below command:node app.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Demo.ejs page as shown below: The project structure will look like this: Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejsnpm install express npm install ejs npm install express Run app.js file using below command:node app.js node app.js Open browser and type this URL:http://localhost:8080/ http://localhost:8080/ Then you will see the Demo.ejs page as shown below: So this is how you can serve static content to our server which is very helpful in serving images, CSS, js file, etc in your project. Node.js-Misc Node.js Web Technologies Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.sendFile() Function Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25255, "s": 25227, "text": "\n27 Apr, 2020" }, { "code": null, "e": 25509, "s": 25255, "text": "Accessing static files are very useful when you want to put your static content accessible to the server for usage. To serve static files such as images, CSS files, and JavaScript files, etc we use the built-in middleware in node.js i.e. express.static." }, { "code": null, "e": 25539, "s": 25509, "text": "Setting up static middleware:" }, { "code": null, "e": 26252, "s": 25539, "text": "You need to create a folder and add a file. For example, app.js, To run this file you need to run the following command.node app.jsNow create a folder whose content you want to serve as static, For example, you can create a folder named public.Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder.To serve this folder as static, you need the write this middleware in your index.js as follow:app.use(express.static(path.join(__dirname, 'public')))where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.Now create a EJS file like Demo.ejs and put this file in views folder." }, { "code": null, "e": 26384, "s": 26252, "text": "You need to create a folder and add a file. For example, app.js, To run this file you need to run the following command.node app.js" }, { "code": null, "e": 26396, "s": 26384, "text": "node app.js" }, { "code": null, "e": 26510, "s": 26396, "text": "Now create a folder whose content you want to serve as static, For example, you can create a folder named public." }, { "code": null, "e": 26624, "s": 26510, "text": "Now add some static content to this public folder. In this case, there is a GeeksLogo.png image in public folder." }, { "code": null, "e": 26910, "s": 26624, "text": "To serve this folder as static, you need the write this middleware in your index.js as follow:app.use(express.static(path.join(__dirname, 'public')))where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept." }, { "code": null, "e": 26981, "s": 26910, "text": "Now create a EJS file like Demo.ejs and put this file in views folder." }, { "code": null, "e": 27000, "s": 26981, "text": "Filename: Demo.ejs" }, { "code": "<!DOCTYPE html><html><head> <title>Static Middleware Demo</title></head><body> <img src=\"/GeeksLogo.png\" width=\"600\" height=\"600\" /></body></html>", "e": 27151, "s": 27000, "text": null }, { "code": null, "e": 27168, "s": 27151, "text": "Filename: app.js" }, { "code": "const express = require('express')const path = require('path')const app = express() // Static Middlewareapp.use(express.static(path.join(__dirname, 'public'))) // View Engine Setupapp.set('views', path.join(__dirname, 'views'))app.set('view engine', 'ejs') app.get('/', function(req, res){ res.render('Demo')}) app.listen(8080, function(error){ if(error) throw error console.log(\"Server created Successfully\")})", "e": 27593, "s": 27168, "text": null }, { "code": null, "e": 27619, "s": 27593, "text": "Steps to run the program:" }, { "code": null, "e": 27957, "s": 27619, "text": "The project structure will look like this:Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejsnpm install expressRun app.js file using below command:node app.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Demo.ejs page as shown below:" }, { "code": null, "e": 28000, "s": 27957, "text": "The project structure will look like this:" }, { "code": null, "e": 28145, "s": 28000, "text": "Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejsnpm install express" }, { "code": null, "e": 28161, "s": 28145, "text": "npm install ejs" }, { "code": null, "e": 28181, "s": 28161, "text": "npm install express" }, { "code": null, "e": 28229, "s": 28181, "text": "Run app.js file using below command:node app.js" }, { "code": null, "e": 28241, "s": 28229, "text": "node app.js" }, { "code": null, "e": 28295, "s": 28241, "text": "Open browser and type this URL:http://localhost:8080/" }, { "code": null, "e": 28318, "s": 28295, "text": "http://localhost:8080/" }, { "code": null, "e": 28370, "s": 28318, "text": "Then you will see the Demo.ejs page as shown below:" }, { "code": null, "e": 28504, "s": 28370, "text": "So this is how you can serve static content to our server which is very helpful in serving images, CSS, js file, etc in your project." }, { "code": null, "e": 28517, "s": 28504, "text": "Node.js-Misc" }, { "code": null, "e": 28525, "s": 28517, "text": "Node.js" }, { "code": null, "e": 28542, "s": 28525, "text": "Web Technologies" }, { "code": null, "e": 28558, "s": 28542, "text": "Write From Home" }, { "code": null, "e": 28656, "s": 28558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28665, "s": 28656, "text": "Comments" }, { "code": null, "e": 28678, "s": 28665, "text": "Old Comments" }, { "code": null, "e": 28708, "s": 28678, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28765, "s": 28708, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28819, "s": 28765, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28856, "s": 28819, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28891, "s": 28856, "text": "Express.js res.sendFile() Function" }, { "code": null, "e": 28947, "s": 28891, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29009, "s": 28947, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29052, "s": 29009, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29102, "s": 29052, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
PyTorch – How to resize an image to a given size?
The Resize() transform resizes the input image to a given size. It's one of the transforms provided by the torchvision.transforms module. Resize() accepts both PIL and tensor images. A tensor image is a torch tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width. This transform also accepts a batch of tensor images, which is a tensor with [B, C, H, W] where B is the number of images in the batch. If the image is neither a PIL image nor a tensor image, then we first convert it to a tensor image and then apply the Resize()transform. torchvision.transforms.Resize(size)(img) Size – Size to which the input image is to be resized. size is a sequence like (h, w), where h and w are the height and width of the output image. If size is an int, then the resized image will be a square image. Size – Size to which the input image is to be resized. size is a sequence like (h, w), where h and w are the height and width of the output image. If size is an int, then the resized image will be a square image. It returns a resized image of given size. We could use the following steps to resize an input image to a given size. Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them. import torch import torchvision import torchvision.transforms as T from PIL import Image import matplotlib.pyplot as plt Read the input image. The input image is a PIL image or a torch tensor or a batch of torch tensors. Read the input image. The input image is a PIL image or a torch tensor or a batch of torch tensors. img = Image.open('lounge.jpg') Define a transform to resize the image to a given size. For example, the given size is (300,350) for rectangular crop and 250 for square crop. Change the crop size according your need. Define a transform to resize the image to a given size. For example, the given size is (300,350) for rectangular crop and 250 for square crop. Change the crop size according your need. # transform for rectangular resize transform = T.Resize((300,350)) # transform for square resize transform = T.Resize(250) Apply the above-defined transform on the input image to resize the input image. Apply the above-defined transform on the input image to resize the input image. resized_img = transform(img) Show the resized image. Show the resized image. plt.imshow(resized_img) This image is used as the input file in all the following examples. The input image is resized to (300, 350). The original image is of size (700,700) # import the required libraries import torch import torchvision.transforms as T from PIL import Image import matplotlib.pyplot as plt # read the input image img = Image.open('lounge.jpg') # compute the size(width, height) of image size = img.size print("Size of the Original image:", size) # define transformt o resize the image with given size transform = T.Resize(size = (250,450)) # apply the transform on the input image img = transform(img) print("Size after resize:", img.size) plt.imshow(img) plt.show() It will return the resized image and also print the size of the original image and the output image on the console. Size of the Original image: (640, 427) Size after resize: (450, 250) Let's take another example − import torch import torchvision.transforms as T from PIL import Image import matplotlib.pyplot as plt img = Image.open('lounge.jpg') size = img.size print("Size of Original image:", size) transform = T.Resize(size = (400,200)) img = transform(img) plt.imshow(img) print("Size after resize:", img.size) plt.show() It will produce the following output − Size of the Original image: (640, 427) Size after resize: (200, 400)
[ { "code": null, "e": 1384, "s": 1062, "text": "The Resize() transform resizes the input image to a given size. It's one of the transforms provided by the torchvision.transforms module. Resize() accepts both PIL and tensor images. A tensor image is a torch tensor with shape [C, H, W], where C is the number of channels, H is the image height, and W is the image width." }, { "code": null, "e": 1657, "s": 1384, "text": "This transform also accepts a batch of tensor images, which is a tensor with [B, C, H, W] where B is the number of images in the batch. If the image is neither a PIL image nor a tensor image, then we first convert it to a tensor image and then apply the Resize()transform." }, { "code": null, "e": 1698, "s": 1657, "text": "torchvision.transforms.Resize(size)(img)" }, { "code": null, "e": 1911, "s": 1698, "text": "Size – Size to which the input image is to be resized. size is a sequence like (h, w), where h and w are the height and width of the output image. If size is an int, then the resized image will be a square image." }, { "code": null, "e": 2124, "s": 1911, "text": "Size – Size to which the input image is to be resized. size is a sequence like (h, w), where h and w are the height and width of the output image. If size is an int, then the resized image will be a square image." }, { "code": null, "e": 2166, "s": 2124, "text": "It returns a resized image of given size." }, { "code": null, "e": 2241, "s": 2166, "text": "We could use the following steps to resize an input image to a given size." }, { "code": null, "e": 2412, "s": 2241, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2583, "s": 2412, "text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them." }, { "code": null, "e": 2704, "s": 2583, "text": "import torch\nimport torchvision\nimport torchvision.transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt" }, { "code": null, "e": 2804, "s": 2704, "text": "Read the input image. The input image is a PIL image or a torch tensor or a batch of torch tensors." }, { "code": null, "e": 2904, "s": 2804, "text": "Read the input image. The input image is a PIL image or a torch tensor or a batch of torch tensors." }, { "code": null, "e": 2936, "s": 2904, "text": "img = Image.open('lounge.jpg')\n" }, { "code": null, "e": 3121, "s": 2936, "text": "Define a transform to resize the image to a given size. For example, the given size is (300,350) for rectangular crop and 250 for square crop. Change the crop size according your need." }, { "code": null, "e": 3306, "s": 3121, "text": "Define a transform to resize the image to a given size. For example, the given size is (300,350) for rectangular crop and 250 for square crop. Change the crop size according your need." }, { "code": null, "e": 3430, "s": 3306, "text": "# transform for rectangular resize\ntransform = T.Resize((300,350))\n\n# transform for square resize\ntransform = T.Resize(250)" }, { "code": null, "e": 3510, "s": 3430, "text": "Apply the above-defined transform on the input image to resize the input image." }, { "code": null, "e": 3590, "s": 3510, "text": "Apply the above-defined transform on the input image to resize the input image." }, { "code": null, "e": 3620, "s": 3590, "text": "resized_img = transform(img)\n" }, { "code": null, "e": 3644, "s": 3620, "text": "Show the resized image." }, { "code": null, "e": 3668, "s": 3644, "text": "Show the resized image." }, { "code": null, "e": 3692, "s": 3668, "text": "plt.imshow(resized_img)" }, { "code": null, "e": 3760, "s": 3692, "text": "This image is used as the input file in all the following examples." }, { "code": null, "e": 3842, "s": 3760, "text": "The input image is resized to (300, 350). The original image is of size (700,700)" }, { "code": null, "e": 4357, "s": 3842, "text": "# import the required libraries\nimport torch\nimport torchvision.transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# read the input image\nimg = Image.open('lounge.jpg')\n\n# compute the size(width, height) of image\nsize = img.size\nprint(\"Size of the Original image:\", size)\n\n# define transformt o resize the image with given size\ntransform = T.Resize(size = (250,450))\n\n# apply the transform on the input image\nimg = transform(img)\nprint(\"Size after resize:\", img.size)\nplt.imshow(img)\nplt.show()" }, { "code": null, "e": 4473, "s": 4357, "text": "It will return the resized image and also print the size of the original image and the output image on the console." }, { "code": null, "e": 4542, "s": 4473, "text": "Size of the Original image: (640, 427)\nSize after resize: (450, 250)" }, { "code": null, "e": 4571, "s": 4542, "text": "Let's take another example −" }, { "code": null, "e": 4887, "s": 4571, "text": "import torch\nimport torchvision.transforms as T\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimg = Image.open('lounge.jpg')\nsize = img.size\nprint(\"Size of Original image:\", size)\n\ntransform = T.Resize(size = (400,200))\nimg = transform(img)\n\nplt.imshow(img)\nprint(\"Size after resize:\", img.size)\nplt.show()" }, { "code": null, "e": 4926, "s": 4887, "text": "It will produce the following output −" }, { "code": null, "e": 4995, "s": 4926, "text": "Size of the Original image: (640, 427)\nSize after resize: (200, 400)" } ]
C++ Variables
Variables are containers for storing data values. In C++, there are different types of variables (defined with different keywords), for example: int - stores integers (whole numbers), without decimals, such as 123 or -123 double - stores floating point numbers, with decimals, such as 19.99 or -19.99 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes string - stores text, such as "Hello World". String values are surrounded by double quotes bool - stores values with two states: true or false To create a variable, specify the type and assign it a value: Where type is one of C++ types (such as int), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable. To create a variable that should store a number, look at the following example: Create a variable called myNum of type int and assign it the value 15: You can also declare a variable without assigning the value, and assign the value later: Note that if you assign a new value to an existing variable, it will overwrite the previous value: A demonstration of other data types: You will learn more about the individual types in the Data Types chapter. The cout object is used together with the << operator to display variables. To combine both text and a variable, separate them with the << operator: To add a variable to another variable, you can use the + operator: Create a variable named myNum and assign the value 50 to it. = 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": "Variables are containers for storing data values. " }, { "code": null, "e": 146, "s": 51, "text": "In C++, there are different types of variables (defined with different keywords), for example:" }, { "code": null, "e": 223, "s": 146, "text": "int - stores integers (whole numbers), without decimals, such as 123 or -123" }, { "code": null, "e": 302, "s": 223, "text": "double - stores floating point numbers, with decimals, such as 19.99 or -19.99" }, { "code": null, "e": 401, "s": 302, "text": "char - stores single characters, such as 'a' or 'B'. \n Char values are surrounded by single quotes" }, { "code": null, "e": 494, "s": 401, "text": "string - stores text, such as \"Hello World\". \n String values are surrounded by double quotes" }, { "code": null, "e": 548, "s": 494, "text": "bool - stores values with two states: \n true or false" }, { "code": null, "e": 610, "s": 548, "text": "To create a variable, specify the type and assign it a value:" }, { "code": null, "e": 782, "s": 610, "text": "Where type is one of C++ types (such as int), and \nvariableName is the name of the variable (such as x or\nmyName). The equal sign is used to assign values to the variable." }, { "code": null, "e": 862, "s": 782, "text": "To create a variable that should store a number, look at the following example:" }, { "code": null, "e": 933, "s": 862, "text": "Create a variable called myNum of type int and assign it the value 15:" }, { "code": null, "e": 1022, "s": 933, "text": "You can also declare a variable without assigning the value, and assign the value later:" }, { "code": null, "e": 1121, "s": 1022, "text": "Note that if you assign a new value to an existing variable, it will overwrite the previous value:" }, { "code": null, "e": 1158, "s": 1121, "text": "A demonstration of other data types:" }, { "code": null, "e": 1232, "s": 1158, "text": "You will learn more about the individual types in the Data Types chapter." }, { "code": null, "e": 1309, "s": 1232, "text": "The cout object is used together with the << \noperator to display variables." }, { "code": null, "e": 1383, "s": 1309, "text": "To combine both text and a variable, separate them with the << \noperator:" }, { "code": null, "e": 1451, "s": 1383, "text": "To add a variable to another variable, you can use the + \noperator:" }, { "code": null, "e": 1512, "s": 1451, "text": "Create a variable named myNum and assign the value 50 to it." }, { "code": null, "e": 1518, "s": 1512, "text": " = \n" }, { "code": null, "e": 1537, "s": 1518, "text": "Start the Exercise" }, { "code": null, "e": 1570, "s": 1537, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1612, "s": 1570, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1719, "s": 1612, "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": 1738, "s": 1719, "text": "help@w3schools.com" } ]
Unsupervised Learning For Anomaly Detection | by Vardaan Bajaj | Towards Data Science
In this post, we’ll be going through: The Need for Anomaly DetectionBaseline Algorithm for Anomaly Detection with underlying MathematicsEvaluating an Anomaly Detection AlgorithmExtending Baseline Algorithm for a Multivariate Gaussian Distribution and the use of Mahalanobis DistanceDetection of Fraudulent Transactions on a Credit Card Dataset available on Kaggle The Need for Anomaly Detection Baseline Algorithm for Anomaly Detection with underlying Mathematics Evaluating an Anomaly Detection Algorithm Extending Baseline Algorithm for a Multivariate Gaussian Distribution and the use of Mahalanobis Distance Detection of Fraudulent Transactions on a Credit Card Dataset available on Kaggle In the previous post, we had an in-depth look at Principal Component Analysis (PCA) and the problem it tries to solve. To consolidate our concepts, we also visualized the results of PCA on the MNIST digit dataset on Kaggle. In each post so far, we discussed either a supervised learning algorithm or an unsupervised learning algorithm but in this post, we’ll be discussing Anomaly Detection algorithms, which can be solved using both, supervised and unsupervised learning methods. Here though, we’ll discuss how unsupervised learning is used to solve this problem and also understand why anomaly detection using unsupervised learning is beneficial in most cases. Anomaly is a synonym for the word ‘outlier’. Anomaly detection (or outlier detection) is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data. Anomalous activities can be linked to some kind of problems or rare events such as bank fraud, medical problems, structural defects, malfunctioning equipment etc. According to a research by Domo published in June 2018, over 2.5 quintillion bytes of data were created every single day, and it was estimated that by 2020, close to 1.7MB of data would be created every second for every person on earth. And in times of CoViD-19, when the world economy has been stabilized by online businesses and online education systems, the number of users using the internet have increased with increased online activity and consequently, it’s safe to assume that data generated per person has increased manifold. In simple words, the digital footprint for a person as well as for an organization has sky-rocketed. The servers are flooded with user activity and this poses a huge challenge for all businesses. Fraudulent activities in banking systems, fake ids and spammers on social media and DDoS attacks on small businesses have the potential to collapse the respective organizations and this can only be prevented if there are ways to detect such malicious (anomalous) activity. Since there are tonnes of ways to induce a particular cyber-attack, it is very difficult to have information about all these attacks beforehand in a dataset. But, since the majority of the user activity online is normal, we can capture almost all the ways which indicate normal behaviour. And from the inclusion-exclusion principle, if an activity under scrutiny does not give indications of normal activity, we can predict with high confidence that the given activity is anomalous. Let us understand the above with an analogy. In the world of human diseases, normal activity can be compared with diseases such as malaria, dengue, swine-flu, etc. for which we have a cure. SarS-CoV-2 (CoViD-19), on the other hand, is an anomaly that has crept into our world of diseases, which has characteristics of a normal disease with the exception of delayed symptoms. Had the SarS-CoV-2 anomaly been detected in its very early stage, its spread could have been contained significantly and we wouldn’t have been facing a pandemic today. Since SarS-CoV-2 is an entirely new anomaly that has never been seen before, even a supervised learning procedure to detect this as an anomaly would have failed since a supervised learning model just learns patterns from the features and labels in the given dataset whereas by providing normal data of pre-existing diseases to an unsupervised learning algorithm, we could have detected this virus as an anomaly with high probability since it would not have fallen into the category (cluster) of normal diseases. I hope this gives enough intuition to realize the importance of Anomaly Detection and why unsupervised learning methods are preferred over supervised learning methods in most cases for such tasks. There are different types of anomaly detection algorithms but the one we’ll be discussing today will start from feature-by-feature probability distribution and how it leads us to using Mahalanobis Distance for the anomaly detection algorithm. One of the most important assumptions for an unsupervised anomaly detection algorithm is that the dataset used for the learning purpose is assumed to have all non-anomalous training examples (or very very small fraction of anomalous examples). This might seem a very bold assumption but we just discussed in the previous section how less probable (but highly dangerous) an anomalous activity is. Also, the goal of the anomaly detection algorithm through the data fed to it is to learn the patterns of a normal activity so that when an anomalous activity occurs, we can flag it through the inclusion-exclusion principle. With this thing in mind, let’s discuss the anomaly detection algorithm in detail. Data points in a dataset usually have a certain type of distribution like the Gaussian (Normal) Distribution. Not all datasets follow a normal distribution but we can always apply certain transformation to features (which we’ll discuss in a later section) that convert the data’s distribution into a Normal Distribution, without any kind of loss in feature variance. Set of data points with Gaussian Distribution look as follows: From the histogram above, we see that data points follow a Gaussian Probability Distribution and most of the data points are spread around a central (mean) location. When the frequency values on y-axis are mentioned as probabilities, the area under the bell curve is always equal to 1. Before we continue our discussion, have a look at the following normal distributions. What do we observe? All the line graphs above represent Normal Probability Distributions and still, they are different. This is because each distribution above has 2 parameters that make each plot unique: the mean (μ) and variance (σ2) of data. The red, blue and yellow distributions are all centered at 0 mean, but they are all different because they have different spreads about their mean values. On the other hand, the green distribution does not have 0 mean but still represents a Normal Distribution. From this, it’s clear that to describe a Normal Distribution, the 2 parameters, μ and σ2 control how the distribution will look like. As a matter of fact, 68% of data lies around the first standard deviation (σ) from the mean (34% on each side), 26.2 % data lies between the first and second standard deviation (σ) (13.1% on each side) and so on. This means that roughly 95% of the data in a Gaussian distribution lies within 2 standard deviations from the mean. We can use this to verify whether real world datasets have a (near perfect) Gaussian Distribution or not. Real world data has a lot of features. If each feature has its data distributed in a Normal fashion, then we can proceed further, otherwise, it is recommended to convert the given distribution into a normal one. The following figure shows what transformations we can apply to a given probability distribution to convert it to a Normal Distribution. The resultant transformation may not result in a perfect probability distribution, but it results in a good enough approximation that makes the algorithm work well. Remember the assumption we made that all the data used for training is assumed to be non-anomalous (or should have a very very small fraction of anomalies). We’ll put that to use here. We saw earlier that almost 95% of data in a normal distribution lies within two standard-deviations from the mean. Since the likelihood of anomalies in general is very low, we can say with high confidence that data points spread near the mean are non-anomalous. And since the probability distribution values between mean and two standard-deviations are large enough, we can set a value in this range as a threshold (a parameter that can be tuned), where feature values with probability larger than this threshold indicate that the given feature’s values are non-anomalous, otherwise it’s anomalous. Consider that there are a total of n features in the data. For a feature x(i) with a threshold value of ε(i), all data points’ probability that are above this threshold are non-anomalous data points i.e. non-anomalous data points w.r.t. a particular feature are represented as: Where P(X(i): μ(i), σ(i)) represents the probability of a given training example for feature X(i) which is characterized by the mean of μ(i) and variance of σ(i). The above case flags a data point as anomalous/non-anomalous on the basis of a particular feature. In reality, we cannot flag a data point as an anomaly based on a single feature. Only when a combination of all the probability values for all features for a given data point is calculated can we say with high confidence whether a data point is an anomaly or not. This scenario can be extended from the previous scenario and can be represented by the following equation. A data point is deemed non-anomalous when Now that we know how to flag an anomaly using all n-features of the data, let us quickly see how we can calculate P(X(i)) for a given normal probability distribution. For that, we also need to calculate μ(i) and σ2(i), which is done as follows. where m is the number of training examples and n is the number of features. We now have everything we need to know to calculate the probabilities of data points in a normal distribution. Let’s go through an example and see how this process works. Consider data consisting of 2 features x1 and x2 with Normal Probability Distribution as follows: If we consider a data point in the training set, then we’ll have to calculate it’s probability values wrt x1 and x2 separately and then multiply them in order to get the final result, which then we’ll compare with the threshold value to decide whether it’s an anomaly or not. To better visualize things, let us plot x1 and x2 in a 2-D graph as follows: The combined probability distribution for both the features will be represented in 3-D as follows: The resultant probability distribution is a Gaussian Distribution. Now, if we consider a training example around the central value, we can see that it will have a higher probability value rather than data points far away since it lies pretty high on the probability distribution curve. We saw earlier that approximately 95% of the training data lies within 2 standard deviations from the mean which led us to choose the value of ε around the border probability value of second standard deviation, which however, can be tuned depending from task to task. This indicates that data points lying outside the 2nd standard deviation from mean have a higher probability of being anomalous, which is evident from the purple shaded part of the probability distribution in the above figure. Any anomaly detection algorithm, whether supervised or unsupervised needs to be evaluated in order to see how effective the algorithm is. Since the number of occurrence of anomalies is relatively very small as compared to normal data points, we can’t use accuracy as an evaluation metric because for a model that predicts everything as non-anomalous, the accuracy will be greater than 99.9% and we wouldn’t have captured any anomaly. This is completely undesirable. Our requirement is to evaluate how many anomalies did we detect and how many did we miss. Predicting a non-anomalous example as anomalous will do almost no harm to any system but predicting an anomalous example as non-anomalous can cause significant damage. One metric that helps us in such an evaluation criteria is by computing the confusion matrix of the predicted values. A confusion matrix is a summary of prediction results on a classification problem. The number of correct and incorrect predictions are summarized with count values and broken down by each class. This is the key to the confusion matrix. The confusion matrix shows the ways in which your classification model is confused when it makes predictions. It gives us insight not only into the errors being made by a classifier but more importantly the types of errors that are being made. A true positive is an outcome where the model correctly predicts the positive class (non-anomalous data as non-anomalous). Similarly, a true negative is an outcome where the model correctly predicts the negative class (anomalous data as anomalous). A false positive is an outcome where the model incorrectly predicts the positive class (non-anomalous data as anomalous) and a false negative is an outcome where the model incorrectly predicts the negative class (anomalous data as non-anomalous). In the case of our anomaly detection algorithm, our goal is to reduce as many false negatives as we can. Lower the number of false negatives, better is the performance of the anomaly detection algorithm. We have missed a very important detail here. The anomaly detection algorithm we discussed above is an unsupervised learning algorithm, then how do we evaluate its performance? While collecting data, we definitely know which data is anomalous and which is not. The reason for not using supervised learning was that it cannot capture all the anomalies from such a limited number of anomalies. That is why we use unsupervised learning with inclusion-exclusion principle. Suppose we have 10,040 training examples, 10,000 of which are non-anomalous and 40 are anomalous. This data will be divided into training, cross-validation and test set as follows: Training set: 8,000 non-anomalous examples Cross-Validation set: 1,000 non-anomalous and 20 anomalous examples Test set: 1,000 non-anomalous and 20 anomalous examples This distribution will enable us to capture as many patterns that occur in non-anomalous data points and then we can compare and contrast them with 20 anomalies, each in cross-validation and test set. The point of creating a cross validation set here is to tune the value of the threshold point ε. We need to know how the anomaly detection algorithm analyses the patterns for non-anomalous data points in order to know whether there is a further scope of improvement. Let’s consider a data distribution in which the plotted points do not assume a circular shape, like the following. All the red points in the image above are non-anomalous examples. If we consider the point marked in green, using our intelligence we will flag this point as an anomaly. But, the way we the anomaly detection algorithm we discussed works, this point will lie in the region where it can be detected as a normal data point. The anomaly detection algorithm discussed so far works in circles. The inner circle is representative of the probability values of the normal distribution close to the mean. The second circle, where the green point lies is representative of the probability values that are close the first standard deviation from the mean and so on. This is undesirable because every time we won’t have data whose scatter plot results in a circular distribution in 2-dimensions, spherical distribution in 3-dimensions and so on. We need an anomaly detection algorithm that adapts according to the distribution of the data points and gives good results. Turns out that for this problem, we can use the Mahalanobis Distance (MD) property of a Multi-variate Gaussian Distribution (we’ve been dealing with multivariate gaussian distributions so far). The Mahalanobis distance (MD) is the distance between two points in multivariate space. In a regular Euclidean space, variables (e.g. x, y, z) are represented by axes drawn at right angles to each other. The distance between any two points can be measured with a ruler. For uncorrelated variables, the Euclidean distance equals the MD. However, if two or more variables are correlated, the axes are no longer at right angles, and the measurements become impossible with a ruler. In addition, if you have more than three variables, you can’t plot them in regular 3D space at all. The MD solves this measurement problem, as it measures distances between points, even correlated points for multiple variables. The Mahalanobis distance measures distance relative to the centroid — a base or central point which can be thought of as an overall mean for multivariate data. The centroid is a point in multivariate space where all means from all variables intersect. The larger the MD, the further away from the centroid the data point is. To use Mahalanobis Distance for anomaly detection, we don’t need to compute the individual probability values for each feature. Instead, we can directly calculate the final probability of each data point that considers all the features of the data and above all, due to the non-zero off-diagonal values of Covariance Matrix Σ while calculating Mahalanobis Distance, the resultant anomaly detection curve is no more circular, rather, it fits the shape of the data distribution. Mahalanobis Distance is calculated using the formula given below. Once the Mahalanobis Distance is calculated, we can calculate P(X), the probability of the occurrence of a training example, given all n features as follows: Where |Σ| represents the determinant of the covariance matrix Σ. The values μ and Σ are calculated as follows: Finally, we can set a threshold value ε, where all values of P(X) < ε flag an anomaly in the data. However, this value is a parameter and can be tuned using the cross-validation set with the same data distribution we discussed for the previous anomaly detection algorithm. Before concluding the theoretical section of this post, it must be noted that although using Mahalanobis Distance for anomaly detection is a more generalized approach for anomaly detection, this very reason makes it computationally more expensive than the baseline algorithm. Also, we must have the number training examples m greater than the number of features n (m > n), otherwise the covariance matrix Σ will be non-invertible (i.e. Σ^-1 would become undefined). Finally we’ve reached the concluding part of the theoretical section of the post. We understood the need of anomaly detection algorithm before we dove deep into the mathematics involved behind the anomaly detection algorithm. I recommend reading the theoretical part more than once if things are a bit cluttered in your head at this point, which is completely normal though. Now, let’s take a look back at the fraudulent credit card transaction dataset from Kaggle, which we solved using Support Vector Machines in this post and solve it using the anomaly detection algorithm. In this section, we’ll be using Anomaly Detection algorithm to determine fraudulent credit card transactions. Dataset for this problem can be found here. One thing to note here is that the features of this dataset are already computed as a result of PCA. This helps us in 2 ways: (i) The confidentiality of the user data is maintained. (ii) The features in the dataset are independent of each other due to PCA transformation. Let’s start by loading the data in memory in a pandas data frame. import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn import preprocessingfrom sklearn.neighbors import LocalOutlierFactorfrom sklearn.metrics import confusion_matrix, classification_report,accuracy_scoreimport osfor dirname, _, filenames in os.walk(‘/kaggle/input’): for filename in filenames print(os.path.join(dirname, filename)) df = pd.read_csv("/kaggle/input/creditcardfraud/creditcard.csv")df.head() We proceed with the data pre-processing step. Let’s have a look at how the values are distributed across various features of the dataset. df.describe() The original dataset has over 284k+ data points, out of which only 492 are anomalies. Training the model on the entire dataset led to timeout on Kaggle, so I used 20% of the data ( > 56k data points ). print(df.shape)data= df.sample(frac = 0.2,random_state=1)print(data.shape) The data has no null values, which can be checked by the following piece of code. df.isnull().values.any() Let us plot normal transaction v/s anomalous transactions on a bar graph in order to realize the fraction of fraudulent transactions in the dataset. Additionally, also let us separate normal and fraudulent transactions in datasets of their own. num_classes = pd.value_counts(df['Class'], sort = True)num_classes.plot(kind = 'bar')plt.title("Transaction Class Distribution")plt.xticks(range(2), ["Normal", "Fraud"])plt.xlabel("Class")plt.ylabel("Frequency")fraud = df[df['Class'] == 1]normal = df[df['Class'] == 0]print(fraud.shape, normal.shape) In the dataset, we can only interpret the ‘Time’ and ‘Amount’ values against the output ‘Class’. Let us see, if we can find something observations that enable us to visibly differentiate between normal and fraudulent transactions. f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Time of transaction v/s Amount by Class type')ax1.scatter(fraud.Time, fraud.Amount)ax1.set_title('Fraud')ax2.scatter(normal.Time, normal.Amount)ax2.set_title('Normal')plt.xlabel('Time (in secs)')plt.ylabel('Amount')plt.xlim((0, 20000))plt.show() f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Amount per transaction by class')bins = 10ax1.hist(fraud.Amount, bins = bins)ax1.set_title('Fraud')ax2.hist(normal.Amount, bins = bins)ax2.set_title('Normal')plt.xlabel('Amount ($)')plt.ylabel('Number of Transactions')plt.xlim((0, 20000))plt.yscale('log') From the first plot, we can observe that fraudulent transactions occur at the same time as normal transaction, making time an irrelevant factor. From the second plot, we can see that most of the fraudulent transactions are small amount transactions. This is however not a huge differentiating feature since majority of normal transactions are also small amount transactions. Before proceeding further, let us have a look at how many fraudulent and non-fraudulent transactions do we have in the reduced dataset (20% of the features) that we’ll use for training the machine learning model to identify anomalies. fraud = data[data['Class']==1]normal = data[data['Class']==0]anomaly_fraction = len(fraud)/float(len(normal))print(anomaly_fraction)print("Fraud Cases: " + str(len(fraud)))print("Normal Cases: " + str(len(normal))) We have just 0.1% fraudulent transactions in the dataset. This means that a random guess by the model should yield 0.1% accuracy for fraudulent transactions. We’ll, however, construct a model that will have much better accuracy than this one. You might be thinking why I’ve mentioned this here. I’ll refer these lines while evaluating the final model’s performance. Recall that we learnt that each feature should be normally distributed in order to apply the unsupervised anomaly detection algorithm. Let us plot histograms for each feature and see which features don’t represent Gaussian distribution at all. data.hist(figsize=(15,15), bins = 64)plt.show() From the above histograms, we can see that ‘Time’, ‘V1’ and ‘V24’ are the ones that don’t even approximate a Gaussian distribution. Let’s drop these features from the model training process. We were going to omit the ‘Time’ feature anyways. columns = data.columns.tolist()target=columns[-1]columns = columns[:-1]X_train = data.iloc[:45000, :-1]y_train = data.iloc[:45000, -1]X_test = data.iloc[45000:, :-1]y_test = data.iloc[45000:, -1]print(X_train.shape, X_test.shape)print(y_train.shape, y_test.shape) Let us use the LocalOutlierFactor function from the scikit-learn library in order to use unsupervised learning method discussed above to train the model. model = LocalOutlierFactor(contamination=anomaly_fraction)y_train_pred = model.fit_predict(X_train)y_train_pred[y_train_pred == 1] = 0y_train_pred[y_train_pred == -1] = 1y_test_pred = model.fit_predict(X_test)y_test_pred[y_test_pred == 1] = 0y_test_pred[y_test_pred == -1] = 1 Now that we have trained the model, let us evaluate the model’s performance by having a look at the confusion matrix for the same as we discussed earlier that accuracy is not a good metric to evaluate any anomaly detection algorithm, especially the one which has such a skewed input data as this one. import itertoolsclasses = np.array(['0','1'])def plot_confusion_matrix(cm, classes,title='Confusion matrix', cmap=plt.cm.Blues):plt.imshow(cm, interpolation='nearest', cmap=cmap)plt.title(title)plt.colorbar()tick_marks = np.arange(len(classes))plt.xticks(tick_marks, classes, rotation=45)plt.yticks(tick_marks, classes)fmt = 'd'thresh = cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, format(cm[i, j], fmt),horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")plt.tight_layout()plt.ylabel('True label')plt.xlabel('Predicted label') The above function is a helper function that enables us to construct a confusion matrix. We’ll plot confusion matrices to evaluate both training and test set performances. cm_train = confusion_matrix(y_train, y_train_pred)plot_confusion_matrix(cm_train,["Normal", "Fraud"]) cm_test = confusion_matrix(y_test_pred, y_test)plot_confusion_matrix(cm_test,["Normal", "Fraud"]) We see that on the training set, the model detects 44,870 normal transactions correctly and only 55 normal transactions are labelled as fraud. This is quite good, but this is not something we are concerned about. We can see that out of the 75 fraudulent transactions in the training set, only 14 have been captured correctly whereas 61 are misclassified, which is a problem. When we compare this performance to the random guess probability of 0.1%, it is a significant improvement form that but not convincing enough. Even in the test set, we see that 11,936/11,942 normal transactions are correctly predicted, but only 6/19 fraudulent transactions are correctly captured. When I was solving this dataset, even I was surprised for a moment, but then I analysed the dataset critically and came to the conclusion that for this problem, this is the best unsupervised learning can do. One reason why unsupervised learning did not perform well enough is because most of the fraudulent transactions did not have much unusual characteristics regarding them which can be well separated from normal transactions. This is supported by the ‘Time’ and ‘Amount’ graphs that we plotted against the ‘Class’ feature. And I feel that this is the main reason that labels are provided with the dataset which flag transactions as fraudulent and non-fraudulent, since there aren’t any visibly distinguishing features for fraudulent transactions. The accuracy of detecting anomalies on the test set is 25%, which is way better than a random guess (the fraction of anomalies in the dataset is < 0.1%) despite having the accuracy of 99.84% accuracy on the test set. print('Total fraudulent transactions detected in training set: ' + str(cm_train[1][1]) + ' / ' + str(cm_train[1][1]+cm_train[1][0]))print('Total non-fraudulent transactions detected in training set: ' + str(cm_train[0][0]) + ' / ' + str(cm_train[0][1]+cm_train[0][0]))print('Probability to detect a fraudulent transaction in the training set: ' + str(cm_train[1][1]/(cm_train[1][1]+cm_train[1][0])))print('Probability to detect a non-fraudulent transaction in the training set: ' + str(cm_train[0][0]/(cm_train[0][1]+cm_train[0][0])))print("Accuracy of unsupervised anomaly detection model on the training set: "+str(100*(cm_train[0][0]+cm_train[1][1]) / (sum(cm_train[0]) + sum(cm_train[1]))) + "%") print('Total fraudulent transactions detected in test set: ' + str(cm_test[1][1]) + ' / ' + str(cm_test[1][1]+cm_test[1][0]))print('Total non-fraudulent transactions detected in test set: ' + str(cm_test[0][0]) + ' / ' + str(cm_test[0][1]+cm_test[0][0]))print('Probability to detect a fraudulent transaction in the test set: ' + str(cm_test[1][1]/(cm_test[1][1]+cm_test[1][0])))print('Probability to detect a non-fraudulent transaction in the test set: ' + str(cm_test[0][0]/(cm_test[0][1]+cm_test[0][0])))print("Accuracy of unsupervised anomaly detection model on the test set: "+str(100*(cm_test[0][0]+cm_test[1][1]) / (sum(cm_test[0]) + sum(cm_test[1]))) + "%") The entire code for this post can be found here. That’s it for this post. This post also marks the end of a series of posts on Machine Learning. It was a pleasure writing these posts and I learnt a lot too in this process. I believe that we understand things only as good as we teach them and in these posts, I tried my best to simplify things as much as I could. Mathematics got a bit complicated in the last few posts, but that’s how these topics were. Thanks for reading these posts.
[ { "code": null, "e": 209, "s": 171, "text": "In this post, we’ll be going through:" }, { "code": null, "e": 535, "s": 209, "text": "The Need for Anomaly DetectionBaseline Algorithm for Anomaly Detection with underlying MathematicsEvaluating an Anomaly Detection AlgorithmExtending Baseline Algorithm for a Multivariate Gaussian Distribution and the use of Mahalanobis DistanceDetection of Fraudulent Transactions on a Credit Card Dataset available on Kaggle" }, { "code": null, "e": 566, "s": 535, "text": "The Need for Anomaly Detection" }, { "code": null, "e": 635, "s": 566, "text": "Baseline Algorithm for Anomaly Detection with underlying Mathematics" }, { "code": null, "e": 677, "s": 635, "text": "Evaluating an Anomaly Detection Algorithm" }, { "code": null, "e": 783, "s": 677, "text": "Extending Baseline Algorithm for a Multivariate Gaussian Distribution and the use of Mahalanobis Distance" }, { "code": null, "e": 865, "s": 783, "text": "Detection of Fraudulent Transactions on a Credit Card Dataset available on Kaggle" }, { "code": null, "e": 1528, "s": 865, "text": "In the previous post, we had an in-depth look at Principal Component Analysis (PCA) and the problem it tries to solve. To consolidate our concepts, we also visualized the results of PCA on the MNIST digit dataset on Kaggle. In each post so far, we discussed either a supervised learning algorithm or an unsupervised learning algorithm but in this post, we’ll be discussing Anomaly Detection algorithms, which can be solved using both, supervised and unsupervised learning methods. Here though, we’ll discuss how unsupervised learning is used to solve this problem and also understand why anomaly detection using unsupervised learning is beneficial in most cases." }, { "code": null, "e": 1918, "s": 1528, "text": "Anomaly is a synonym for the word ‘outlier’. Anomaly detection (or outlier detection) is the identification of rare items, events or observations which raise suspicions by differing significantly from the majority of the data. Anomalous activities can be linked to some kind of problems or rare events such as bank fraud, medical problems, structural defects, malfunctioning equipment etc." }, { "code": null, "e": 3405, "s": 1918, "text": "According to a research by Domo published in June 2018, over 2.5 quintillion bytes of data were created every single day, and it was estimated that by 2020, close to 1.7MB of data would be created every second for every person on earth. And in times of CoViD-19, when the world economy has been stabilized by online businesses and online education systems, the number of users using the internet have increased with increased online activity and consequently, it’s safe to assume that data generated per person has increased manifold. In simple words, the digital footprint for a person as well as for an organization has sky-rocketed. The servers are flooded with user activity and this poses a huge challenge for all businesses. Fraudulent activities in banking systems, fake ids and spammers on social media and DDoS attacks on small businesses have the potential to collapse the respective organizations and this can only be prevented if there are ways to detect such malicious (anomalous) activity. Since there are tonnes of ways to induce a particular cyber-attack, it is very difficult to have information about all these attacks beforehand in a dataset. But, since the majority of the user activity online is normal, we can capture almost all the ways which indicate normal behaviour. And from the inclusion-exclusion principle, if an activity under scrutiny does not give indications of normal activity, we can predict with high confidence that the given activity is anomalous." }, { "code": null, "e": 4657, "s": 3405, "text": "Let us understand the above with an analogy. In the world of human diseases, normal activity can be compared with diseases such as malaria, dengue, swine-flu, etc. for which we have a cure. SarS-CoV-2 (CoViD-19), on the other hand, is an anomaly that has crept into our world of diseases, which has characteristics of a normal disease with the exception of delayed symptoms. Had the SarS-CoV-2 anomaly been detected in its very early stage, its spread could have been contained significantly and we wouldn’t have been facing a pandemic today. Since SarS-CoV-2 is an entirely new anomaly that has never been seen before, even a supervised learning procedure to detect this as an anomaly would have failed since a supervised learning model just learns patterns from the features and labels in the given dataset whereas by providing normal data of pre-existing diseases to an unsupervised learning algorithm, we could have detected this virus as an anomaly with high probability since it would not have fallen into the category (cluster) of normal diseases. I hope this gives enough intuition to realize the importance of Anomaly Detection and why unsupervised learning methods are preferred over supervised learning methods in most cases for such tasks." }, { "code": null, "e": 4900, "s": 4657, "text": "There are different types of anomaly detection algorithms but the one we’ll be discussing today will start from feature-by-feature probability distribution and how it leads us to using Mahalanobis Distance for the anomaly detection algorithm." }, { "code": null, "e": 5602, "s": 4900, "text": "One of the most important assumptions for an unsupervised anomaly detection algorithm is that the dataset used for the learning purpose is assumed to have all non-anomalous training examples (or very very small fraction of anomalous examples). This might seem a very bold assumption but we just discussed in the previous section how less probable (but highly dangerous) an anomalous activity is. Also, the goal of the anomaly detection algorithm through the data fed to it is to learn the patterns of a normal activity so that when an anomalous activity occurs, we can flag it through the inclusion-exclusion principle. With this thing in mind, let’s discuss the anomaly detection algorithm in detail." }, { "code": null, "e": 6032, "s": 5602, "text": "Data points in a dataset usually have a certain type of distribution like the Gaussian (Normal) Distribution. Not all datasets follow a normal distribution but we can always apply certain transformation to features (which we’ll discuss in a later section) that convert the data’s distribution into a Normal Distribution, without any kind of loss in feature variance. Set of data points with Gaussian Distribution look as follows:" }, { "code": null, "e": 6404, "s": 6032, "text": "From the histogram above, we see that data points follow a Gaussian Probability Distribution and most of the data points are spread around a central (mean) location. When the frequency values on y-axis are mentioned as probabilities, the area under the bell curve is always equal to 1. Before we continue our discussion, have a look at the following normal distributions." }, { "code": null, "e": 7480, "s": 6404, "text": "What do we observe? All the line graphs above represent Normal Probability Distributions and still, they are different. This is because each distribution above has 2 parameters that make each plot unique: the mean (μ) and variance (σ2) of data. The red, blue and yellow distributions are all centered at 0 mean, but they are all different because they have different spreads about their mean values. On the other hand, the green distribution does not have 0 mean but still represents a Normal Distribution. From this, it’s clear that to describe a Normal Distribution, the 2 parameters, μ and σ2 control how the distribution will look like. As a matter of fact, 68% of data lies around the first standard deviation (σ) from the mean (34% on each side), 26.2 % data lies between the first and second standard deviation (σ) (13.1% on each side) and so on. This means that roughly 95% of the data in a Gaussian distribution lies within 2 standard deviations from the mean. We can use this to verify whether real world datasets have a (near perfect) Gaussian Distribution or not." }, { "code": null, "e": 7994, "s": 7480, "text": "Real world data has a lot of features. If each feature has its data distributed in a Normal fashion, then we can proceed further, otherwise, it is recommended to convert the given distribution into a normal one. The following figure shows what transformations we can apply to a given probability distribution to convert it to a Normal Distribution. The resultant transformation may not result in a perfect probability distribution, but it results in a good enough approximation that makes the algorithm work well." }, { "code": null, "e": 9056, "s": 7994, "text": "Remember the assumption we made that all the data used for training is assumed to be non-anomalous (or should have a very very small fraction of anomalies). We’ll put that to use here. We saw earlier that almost 95% of data in a normal distribution lies within two standard-deviations from the mean. Since the likelihood of anomalies in general is very low, we can say with high confidence that data points spread near the mean are non-anomalous. And since the probability distribution values between mean and two standard-deviations are large enough, we can set a value in this range as a threshold (a parameter that can be tuned), where feature values with probability larger than this threshold indicate that the given feature’s values are non-anomalous, otherwise it’s anomalous. Consider that there are a total of n features in the data. For a feature x(i) with a threshold value of ε(i), all data points’ probability that are above this threshold are non-anomalous data points i.e. non-anomalous data points w.r.t. a particular feature are represented as:" }, { "code": null, "e": 9219, "s": 9056, "text": "Where P(X(i): μ(i), σ(i)) represents the probability of a given training example for feature X(i) which is characterized by the mean of μ(i) and variance of σ(i)." }, { "code": null, "e": 9689, "s": 9219, "text": "The above case flags a data point as anomalous/non-anomalous on the basis of a particular feature. In reality, we cannot flag a data point as an anomaly based on a single feature. Only when a combination of all the probability values for all features for a given data point is calculated can we say with high confidence whether a data point is an anomaly or not. This scenario can be extended from the previous scenario and can be represented by the following equation." }, { "code": null, "e": 9731, "s": 9689, "text": "A data point is deemed non-anomalous when" }, { "code": null, "e": 9976, "s": 9731, "text": "Now that we know how to flag an anomaly using all n-features of the data, let us quickly see how we can calculate P(X(i)) for a given normal probability distribution. For that, we also need to calculate μ(i) and σ2(i), which is done as follows." }, { "code": null, "e": 10052, "s": 9976, "text": "where m is the number of training examples and n is the number of features." }, { "code": null, "e": 10321, "s": 10052, "text": "We now have everything we need to know to calculate the probabilities of data points in a normal distribution. Let’s go through an example and see how this process works. Consider data consisting of 2 features x1 and x2 with Normal Probability Distribution as follows:" }, { "code": null, "e": 10674, "s": 10321, "text": "If we consider a data point in the training set, then we’ll have to calculate it’s probability values wrt x1 and x2 separately and then multiply them in order to get the final result, which then we’ll compare with the threshold value to decide whether it’s an anomaly or not. To better visualize things, let us plot x1 and x2 in a 2-D graph as follows:" }, { "code": null, "e": 10773, "s": 10674, "text": "The combined probability distribution for both the features will be represented in 3-D as follows:" }, { "code": null, "e": 11554, "s": 10773, "text": "The resultant probability distribution is a Gaussian Distribution. Now, if we consider a training example around the central value, we can see that it will have a higher probability value rather than data points far away since it lies pretty high on the probability distribution curve. We saw earlier that approximately 95% of the training data lies within 2 standard deviations from the mean which led us to choose the value of ε around the border probability value of second standard deviation, which however, can be tuned depending from task to task. This indicates that data points lying outside the 2nd standard deviation from mean have a higher probability of being anomalous, which is evident from the purple shaded part of the probability distribution in the above figure." }, { "code": null, "e": 12876, "s": 11554, "text": "Any anomaly detection algorithm, whether supervised or unsupervised needs to be evaluated in order to see how effective the algorithm is. Since the number of occurrence of anomalies is relatively very small as compared to normal data points, we can’t use accuracy as an evaluation metric because for a model that predicts everything as non-anomalous, the accuracy will be greater than 99.9% and we wouldn’t have captured any anomaly. This is completely undesirable. Our requirement is to evaluate how many anomalies did we detect and how many did we miss. Predicting a non-anomalous example as anomalous will do almost no harm to any system but predicting an anomalous example as non-anomalous can cause significant damage. One metric that helps us in such an evaluation criteria is by computing the confusion matrix of the predicted values. A confusion matrix is a summary of prediction results on a classification problem. The number of correct and incorrect predictions are summarized with count values and broken down by each class. This is the key to the confusion matrix. The confusion matrix shows the ways in which your classification model is confused when it makes predictions. It gives us insight not only into the errors being made by a classifier but more importantly the types of errors that are being made." }, { "code": null, "e": 13576, "s": 12876, "text": "A true positive is an outcome where the model correctly predicts the positive class (non-anomalous data as non-anomalous). Similarly, a true negative is an outcome where the model correctly predicts the negative class (anomalous data as anomalous). A false positive is an outcome where the model incorrectly predicts the positive class (non-anomalous data as anomalous) and a false negative is an outcome where the model incorrectly predicts the negative class (anomalous data as non-anomalous). In the case of our anomaly detection algorithm, our goal is to reduce as many false negatives as we can. Lower the number of false negatives, better is the performance of the anomaly detection algorithm." }, { "code": null, "e": 14225, "s": 13576, "text": "We have missed a very important detail here. The anomaly detection algorithm we discussed above is an unsupervised learning algorithm, then how do we evaluate its performance? While collecting data, we definitely know which data is anomalous and which is not. The reason for not using supervised learning was that it cannot capture all the anomalies from such a limited number of anomalies. That is why we use unsupervised learning with inclusion-exclusion principle. Suppose we have 10,040 training examples, 10,000 of which are non-anomalous and 40 are anomalous. This data will be divided into training, cross-validation and test set as follows:" }, { "code": null, "e": 14268, "s": 14225, "text": "Training set: 8,000 non-anomalous examples" }, { "code": null, "e": 14336, "s": 14268, "text": "Cross-Validation set: 1,000 non-anomalous and 20 anomalous examples" }, { "code": null, "e": 14392, "s": 14336, "text": "Test set: 1,000 non-anomalous and 20 anomalous examples" }, { "code": null, "e": 14690, "s": 14392, "text": "This distribution will enable us to capture as many patterns that occur in non-anomalous data points and then we can compare and contrast them with 20 anomalies, each in cross-validation and test set. The point of creating a cross validation set here is to tune the value of the threshold point ε." }, { "code": null, "e": 14975, "s": 14690, "text": "We need to know how the anomaly detection algorithm analyses the patterns for non-anomalous data points in order to know whether there is a further scope of improvement. Let’s consider a data distribution in which the plotted points do not assume a circular shape, like the following." }, { "code": null, "e": 15296, "s": 14975, "text": "All the red points in the image above are non-anomalous examples. If we consider the point marked in green, using our intelligence we will flag this point as an anomaly. But, the way we the anomaly detection algorithm we discussed works, this point will lie in the region where it can be detected as a normal data point." }, { "code": null, "e": 16126, "s": 15296, "text": "The anomaly detection algorithm discussed so far works in circles. The inner circle is representative of the probability values of the normal distribution close to the mean. The second circle, where the green point lies is representative of the probability values that are close the first standard deviation from the mean and so on. This is undesirable because every time we won’t have data whose scatter plot results in a circular distribution in 2-dimensions, spherical distribution in 3-dimensions and so on. We need an anomaly detection algorithm that adapts according to the distribution of the data points and gives good results. Turns out that for this problem, we can use the Mahalanobis Distance (MD) property of a Multi-variate Gaussian Distribution (we’ve been dealing with multivariate gaussian distributions so far)." }, { "code": null, "e": 16833, "s": 16126, "text": "The Mahalanobis distance (MD) is the distance between two points in multivariate space. In a regular Euclidean space, variables (e.g. x, y, z) are represented by axes drawn at right angles to each other. The distance between any two points can be measured with a ruler. For uncorrelated variables, the Euclidean distance equals the MD. However, if two or more variables are correlated, the axes are no longer at right angles, and the measurements become impossible with a ruler. In addition, if you have more than three variables, you can’t plot them in regular 3D space at all. The MD solves this measurement problem, as it measures distances between points, even correlated points for multiple variables." }, { "code": null, "e": 17158, "s": 16833, "text": "The Mahalanobis distance measures distance relative to the centroid — a base or central point which can be thought of as an overall mean for multivariate data. The centroid is a point in multivariate space where all means from all variables intersect. The larger the MD, the further away from the centroid the data point is." }, { "code": null, "e": 17635, "s": 17158, "text": "To use Mahalanobis Distance for anomaly detection, we don’t need to compute the individual probability values for each feature. Instead, we can directly calculate the final probability of each data point that considers all the features of the data and above all, due to the non-zero off-diagonal values of Covariance Matrix Σ while calculating Mahalanobis Distance, the resultant anomaly detection curve is no more circular, rather, it fits the shape of the data distribution." }, { "code": null, "e": 17701, "s": 17635, "text": "Mahalanobis Distance is calculated using the formula given below." }, { "code": null, "e": 17859, "s": 17701, "text": "Once the Mahalanobis Distance is calculated, we can calculate P(X), the probability of the occurrence of a training example, given all n features as follows:" }, { "code": null, "e": 17924, "s": 17859, "text": "Where |Σ| represents the determinant of the covariance matrix Σ." }, { "code": null, "e": 17970, "s": 17924, "text": "The values μ and Σ are calculated as follows:" }, { "code": null, "e": 18243, "s": 17970, "text": "Finally, we can set a threshold value ε, where all values of P(X) < ε flag an anomaly in the data. However, this value is a parameter and can be tuned using the cross-validation set with the same data distribution we discussed for the previous anomaly detection algorithm." }, { "code": null, "e": 18709, "s": 18243, "text": "Before concluding the theoretical section of this post, it must be noted that although using Mahalanobis Distance for anomaly detection is a more generalized approach for anomaly detection, this very reason makes it computationally more expensive than the baseline algorithm. Also, we must have the number training examples m greater than the number of features n (m > n), otherwise the covariance matrix Σ will be non-invertible (i.e. Σ^-1 would become undefined)." }, { "code": null, "e": 19286, "s": 18709, "text": "Finally we’ve reached the concluding part of the theoretical section of the post. We understood the need of anomaly detection algorithm before we dove deep into the mathematics involved behind the anomaly detection algorithm. I recommend reading the theoretical part more than once if things are a bit cluttered in your head at this point, which is completely normal though. Now, let’s take a look back at the fraudulent credit card transaction dataset from Kaggle, which we solved using Support Vector Machines in this post and solve it using the anomaly detection algorithm." }, { "code": null, "e": 19566, "s": 19286, "text": "In this section, we’ll be using Anomaly Detection algorithm to determine fraudulent credit card transactions. Dataset for this problem can be found here. One thing to note here is that the features of this dataset are already computed as a result of PCA. This helps us in 2 ways:" }, { "code": null, "e": 19622, "s": 19566, "text": "(i) The confidentiality of the user data is maintained." }, { "code": null, "e": 19712, "s": 19622, "text": "(ii) The features in the dataset are independent of each other due to PCA transformation." }, { "code": null, "e": 19778, "s": 19712, "text": "Let’s start by loading the data in memory in a pandas data frame." }, { "code": null, "e": 20142, "s": 19778, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom sklearn import preprocessingfrom sklearn.neighbors import LocalOutlierFactorfrom sklearn.metrics import confusion_matrix, classification_report,accuracy_scoreimport osfor dirname, _, filenames in os.walk(‘/kaggle/input’): for filename in filenames print(os.path.join(dirname, filename))" }, { "code": null, "e": 20216, "s": 20142, "text": "df = pd.read_csv(\"/kaggle/input/creditcardfraud/creditcard.csv\")df.head()" }, { "code": null, "e": 20354, "s": 20216, "text": "We proceed with the data pre-processing step. Let’s have a look at how the values are distributed across various features of the dataset." }, { "code": null, "e": 20368, "s": 20354, "text": "df.describe()" }, { "code": null, "e": 20570, "s": 20368, "text": "The original dataset has over 284k+ data points, out of which only 492 are anomalies. Training the model on the entire dataset led to timeout on Kaggle, so I used 20% of the data ( > 56k data points )." }, { "code": null, "e": 20645, "s": 20570, "text": "print(df.shape)data= df.sample(frac = 0.2,random_state=1)print(data.shape)" }, { "code": null, "e": 20727, "s": 20645, "text": "The data has no null values, which can be checked by the following piece of code." }, { "code": null, "e": 20752, "s": 20727, "text": "df.isnull().values.any()" }, { "code": null, "e": 20997, "s": 20752, "text": "Let us plot normal transaction v/s anomalous transactions on a bar graph in order to realize the fraction of fraudulent transactions in the dataset. Additionally, also let us separate normal and fraudulent transactions in datasets of their own." }, { "code": null, "e": 21298, "s": 20997, "text": "num_classes = pd.value_counts(df['Class'], sort = True)num_classes.plot(kind = 'bar')plt.title(\"Transaction Class Distribution\")plt.xticks(range(2), [\"Normal\", \"Fraud\"])plt.xlabel(\"Class\")plt.ylabel(\"Frequency\")fraud = df[df['Class'] == 1]normal = df[df['Class'] == 0]print(fraud.shape, normal.shape)" }, { "code": null, "e": 21529, "s": 21298, "text": "In the dataset, we can only interpret the ‘Time’ and ‘Amount’ values against the output ‘Class’. Let us see, if we can find something observations that enable us to visibly differentiate between normal and fraudulent transactions." }, { "code": null, "e": 21834, "s": 21529, "text": "f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Time of transaction v/s Amount by Class type')ax1.scatter(fraud.Time, fraud.Amount)ax1.set_title('Fraud')ax2.scatter(normal.Time, normal.Amount)ax2.set_title('Normal')plt.xlabel('Time (in secs)')plt.ylabel('Amount')plt.xlim((0, 20000))plt.show()" }, { "code": null, "e": 22149, "s": 21834, "text": "f, (ax1, ax2) = plt.subplots(2, 1, sharex=True)f.suptitle('Amount per transaction by class')bins = 10ax1.hist(fraud.Amount, bins = bins)ax1.set_title('Fraud')ax2.hist(normal.Amount, bins = bins)ax2.set_title('Normal')plt.xlabel('Amount ($)')plt.ylabel('Number of Transactions')plt.xlim((0, 20000))plt.yscale('log')" }, { "code": null, "e": 22524, "s": 22149, "text": "From the first plot, we can observe that fraudulent transactions occur at the same time as normal transaction, making time an irrelevant factor. From the second plot, we can see that most of the fraudulent transactions are small amount transactions. This is however not a huge differentiating feature since majority of normal transactions are also small amount transactions." }, { "code": null, "e": 22759, "s": 22524, "text": "Before proceeding further, let us have a look at how many fraudulent and non-fraudulent transactions do we have in the reduced dataset (20% of the features) that we’ll use for training the machine learning model to identify anomalies." }, { "code": null, "e": 22974, "s": 22759, "text": "fraud = data[data['Class']==1]normal = data[data['Class']==0]anomaly_fraction = len(fraud)/float(len(normal))print(anomaly_fraction)print(\"Fraud Cases: \" + str(len(fraud)))print(\"Normal Cases: \" + str(len(normal)))" }, { "code": null, "e": 23340, "s": 22974, "text": "We have just 0.1% fraudulent transactions in the dataset. This means that a random guess by the model should yield 0.1% accuracy for fraudulent transactions. We’ll, however, construct a model that will have much better accuracy than this one. You might be thinking why I’ve mentioned this here. I’ll refer these lines while evaluating the final model’s performance." }, { "code": null, "e": 23584, "s": 23340, "text": "Recall that we learnt that each feature should be normally distributed in order to apply the unsupervised anomaly detection algorithm. Let us plot histograms for each feature and see which features don’t represent Gaussian distribution at all." }, { "code": null, "e": 23632, "s": 23584, "text": "data.hist(figsize=(15,15), bins = 64)plt.show()" }, { "code": null, "e": 23873, "s": 23632, "text": "From the above histograms, we can see that ‘Time’, ‘V1’ and ‘V24’ are the ones that don’t even approximate a Gaussian distribution. Let’s drop these features from the model training process. We were going to omit the ‘Time’ feature anyways." }, { "code": null, "e": 24137, "s": 23873, "text": "columns = data.columns.tolist()target=columns[-1]columns = columns[:-1]X_train = data.iloc[:45000, :-1]y_train = data.iloc[:45000, -1]X_test = data.iloc[45000:, :-1]y_test = data.iloc[45000:, -1]print(X_train.shape, X_test.shape)print(y_train.shape, y_test.shape)" }, { "code": null, "e": 24291, "s": 24137, "text": "Let us use the LocalOutlierFactor function from the scikit-learn library in order to use unsupervised learning method discussed above to train the model." }, { "code": null, "e": 24568, "s": 24291, "text": "model = LocalOutlierFactor(contamination=anomaly_fraction)y_train_pred = model.fit_predict(X_train)y_train_pred[y_train_pred == 1] = 0y_train_pred[y_train_pred == -1] = 1y_test_pred = model.fit_predict(X_test)y_test_pred[y_test_pred == 1] = 0y_test_pred[y_test_pred == -1] = 1" }, { "code": null, "e": 24869, "s": 24568, "text": "Now that we have trained the model, let us evaluate the model’s performance by having a look at the confusion matrix for the same as we discussed earlier that accuracy is not a good metric to evaluate any anomaly detection algorithm, especially the one which has such a skewed input data as this one." }, { "code": null, "e": 25475, "s": 24869, "text": "import itertoolsclasses = np.array(['0','1'])def plot_confusion_matrix(cm, classes,title='Confusion matrix', cmap=plt.cm.Blues):plt.imshow(cm, interpolation='nearest', cmap=cmap)plt.title(title)plt.colorbar()tick_marks = np.arange(len(classes))plt.xticks(tick_marks, classes, rotation=45)plt.yticks(tick_marks, classes)fmt = 'd'thresh = cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, format(cm[i, j], fmt),horizontalalignment=\"center\",color=\"white\" if cm[i, j] > thresh else \"black\")plt.tight_layout()plt.ylabel('True label')plt.xlabel('Predicted label')" }, { "code": null, "e": 25647, "s": 25475, "text": "The above function is a helper function that enables us to construct a confusion matrix. We’ll plot confusion matrices to evaluate both training and test set performances." }, { "code": null, "e": 25749, "s": 25647, "text": "cm_train = confusion_matrix(y_train, y_train_pred)plot_confusion_matrix(cm_train,[\"Normal\", \"Fraud\"])" }, { "code": null, "e": 25847, "s": 25749, "text": "cm_test = confusion_matrix(y_test_pred, y_test)plot_confusion_matrix(cm_test,[\"Normal\", \"Fraud\"])" }, { "code": null, "e": 26520, "s": 25847, "text": "We see that on the training set, the model detects 44,870 normal transactions correctly and only 55 normal transactions are labelled as fraud. This is quite good, but this is not something we are concerned about. We can see that out of the 75 fraudulent transactions in the training set, only 14 have been captured correctly whereas 61 are misclassified, which is a problem. When we compare this performance to the random guess probability of 0.1%, it is a significant improvement form that but not convincing enough. Even in the test set, we see that 11,936/11,942 normal transactions are correctly predicted, but only 6/19 fraudulent transactions are correctly captured." }, { "code": null, "e": 27489, "s": 26520, "text": "When I was solving this dataset, even I was surprised for a moment, but then I analysed the dataset critically and came to the conclusion that for this problem, this is the best unsupervised learning can do. One reason why unsupervised learning did not perform well enough is because most of the fraudulent transactions did not have much unusual characteristics regarding them which can be well separated from normal transactions. This is supported by the ‘Time’ and ‘Amount’ graphs that we plotted against the ‘Class’ feature. And I feel that this is the main reason that labels are provided with the dataset which flag transactions as fraudulent and non-fraudulent, since there aren’t any visibly distinguishing features for fraudulent transactions. The accuracy of detecting anomalies on the test set is 25%, which is way better than a random guess (the fraction of anomalies in the dataset is < 0.1%) despite having the accuracy of 99.84% accuracy on the test set." }, { "code": null, "e": 28190, "s": 27489, "text": "print('Total fraudulent transactions detected in training set: ' + str(cm_train[1][1]) + ' / ' + str(cm_train[1][1]+cm_train[1][0]))print('Total non-fraudulent transactions detected in training set: ' + str(cm_train[0][0]) + ' / ' + str(cm_train[0][1]+cm_train[0][0]))print('Probability to detect a fraudulent transaction in the training set: ' + str(cm_train[1][1]/(cm_train[1][1]+cm_train[1][0])))print('Probability to detect a non-fraudulent transaction in the training set: ' + str(cm_train[0][0]/(cm_train[0][1]+cm_train[0][0])))print(\"Accuracy of unsupervised anomaly detection model on the training set: \"+str(100*(cm_train[0][0]+cm_train[1][1]) / (sum(cm_train[0]) + sum(cm_train[1]))) + \"%\")" }, { "code": null, "e": 28855, "s": 28190, "text": "print('Total fraudulent transactions detected in test set: ' + str(cm_test[1][1]) + ' / ' + str(cm_test[1][1]+cm_test[1][0]))print('Total non-fraudulent transactions detected in test set: ' + str(cm_test[0][0]) + ' / ' + str(cm_test[0][1]+cm_test[0][0]))print('Probability to detect a fraudulent transaction in the test set: ' + str(cm_test[1][1]/(cm_test[1][1]+cm_test[1][0])))print('Probability to detect a non-fraudulent transaction in the test set: ' + str(cm_test[0][0]/(cm_test[0][1]+cm_test[0][0])))print(\"Accuracy of unsupervised anomaly detection model on the test set: \"+str(100*(cm_test[0][0]+cm_test[1][1]) / (sum(cm_test[0]) + sum(cm_test[1]))) + \"%\")" }, { "code": null, "e": 28904, "s": 28855, "text": "The entire code for this post can be found here." } ]
Java Program to format date with System.out.format
System.out.format is used in Java to format output. Firstly, create a Calendar object − Calendar calendar = Calendar.getInstance(); Now, use theDate-Time conversion characters to get the date, month and year − System.out.format("%te %tB, %tY%n", calendar, calendar, calendar); The following is the complete example − Live Demo import java.util.Locale; import java.util.Calendar; public class TestFormat { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); System.out.format("%te %tB, %tY%n", calendar, calendar, calendar); } } 22 November, 2018
[ { "code": null, "e": 1114, "s": 1062, "text": "System.out.format is used in Java to format output." }, { "code": null, "e": 1150, "s": 1114, "text": "Firstly, create a Calendar object −" }, { "code": null, "e": 1194, "s": 1150, "text": "Calendar calendar = Calendar.getInstance();" }, { "code": null, "e": 1272, "s": 1194, "text": "Now, use theDate-Time conversion characters to get the date, month and year −" }, { "code": null, "e": 1339, "s": 1272, "text": "System.out.format(\"%te %tB, %tY%n\", calendar, calendar, calendar);" }, { "code": null, "e": 1379, "s": 1339, "text": "The following is the complete example −" }, { "code": null, "e": 1390, "s": 1379, "text": " Live Demo" }, { "code": null, "e": 1642, "s": 1390, "text": "import java.util.Locale;\nimport java.util.Calendar;\npublic class TestFormat {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.format(\"%te %tB, %tY%n\", calendar, calendar, calendar);\n }\n}" }, { "code": null, "e": 1660, "s": 1642, "text": "22 November, 2018" } ]
Checking HTTP Status Code in Selenium.
We can check HTTP status code in Selenium. As we run tests, we can verify the status code of a response from a resource. Some of the various HTTP status codes are − 5XX – Error in server. 5XX – Error in server. 4XX – Resource not detected. 4XX – Resource not detected. 3XX - Redirected. 3XX - Redirected. 2XX – Ok. 2XX – Ok. An instance of the class HttpURLConnection is used to get the HTTP status code. To have a connection to an URL, the openConnection method shall be utilized. Then we have to take the help of setRequestMethod and pass HEAD as a parameter to that. To establish the connection, the connect method is to be applied to the object of the HttpURLConnection class. Finally, the getResponseCode method obtains the HTTP response code. HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm") .openConnection(); cn.setRequestMethod("HEAD"); cn.connect(); int c = cn.getResponseCode(); Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpRespCode{ public static void main(String[] args) throws MalformedURLException, IOException { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // wait of 4 seconds driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/index.htm"); // establish and open connection with URL HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm") .openConnection(); // set the HEAD request with setRequestMethod cn.setRequestMethod("HEAD"); // connection initiated and obtain status code cn.connect(); int c = cn.getResponseCode(); System.out.println("Http status code: " + c); driver.quit(); } }
[ { "code": null, "e": 1227, "s": 1062, "text": "We can check HTTP status code in Selenium. As we run tests, we can verify the status code of a response from a resource. Some of the various HTTP status codes are −" }, { "code": null, "e": 1250, "s": 1227, "text": "5XX – Error in server." }, { "code": null, "e": 1273, "s": 1250, "text": "5XX – Error in server." }, { "code": null, "e": 1302, "s": 1273, "text": "4XX – Resource not detected." }, { "code": null, "e": 1331, "s": 1302, "text": "4XX – Resource not detected." }, { "code": null, "e": 1349, "s": 1331, "text": "3XX - Redirected." }, { "code": null, "e": 1367, "s": 1349, "text": "3XX - Redirected." }, { "code": null, "e": 1377, "s": 1367, "text": "2XX – Ok." }, { "code": null, "e": 1387, "s": 1377, "text": "2XX – Ok." }, { "code": null, "e": 1632, "s": 1387, "text": "An instance of the class HttpURLConnection is used to get the HTTP status code. To have a connection to an URL, the openConnection method shall be utilized. Then we have to take the help of setRequestMethod and pass HEAD as a parameter to that." }, { "code": null, "e": 1811, "s": 1632, "text": "To establish the connection, the connect method is to be applied to the object of the HttpURLConnection class. Finally, the getResponseCode method obtains the HTTP response code." }, { "code": null, "e": 1996, "s": 1811, "text": "HttpURLConnection cn= (HttpURLConnection)new URL(\"https://www.tutorialspoint.com/index.htm\")\n.openConnection();\ncn.setRequestMethod(\"HEAD\");\ncn.connect();\nint c = cn.getResponseCode();" }, { "code": null, "e": 2017, "s": 1996, "text": "Code Implementation." }, { "code": null, "e": 3247, "s": 2017, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.URLConnection;\npublic class HttpRespCode{\n public static void main(String[] args) throws\n MalformedURLException, IOException {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n // wait of 4 seconds\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/index.htm\");\n // establish and open connection with URL\n HttpURLConnection cn= (HttpURLConnection)new\n URL(\"https://www.tutorialspoint.com/index.htm\")\n .openConnection();\n // set the HEAD request with setRequestMethod\n cn.setRequestMethod(\"HEAD\");\n // connection initiated and obtain status code\n cn.connect();\n int c = cn.getResponseCode();\n System.out.println(\"Http status code: \" + c);\n driver.quit();\n }\n}" } ]
Use ColumnTransformer in SciKit instead of LabelEncoding and OneHotEncoding for data preprocessing in Machine Learning | by Sunny Srinidhi | Towards Data Science
In a very old post — Label Encoder vs. One Hot Encoder in Machine Learning — I had demonstrated how to use label encoding and one hot encoding to separate out categorical text data into numbers and different columns. But the SciKit library has come a long way since I wrote that post, and it has made life a lot more easier. The developers of the library might have realised that people use LabelEncoding and OneHotEncoding very frequently. So they decided to come up with a new library called the ColumnTransformer, which will basically combine LabelEncoding and OneHotEncoding into just one line of code. And the result is exactly the same. In this post, we’ll quickly take a look at how we can do that with some code snippets. First, as usual, we need to import the required libraries. We’ll go with the convention here for the aliasing: import numpy as npimport pandas as pd Next, let’s get some data into a variable and see what we’re working with: dataset = pd.read_csv("/home/sunny/code/machine_learning/samples/sample.csv") You can use the “Variable explorer” view in Spyder to take a look at the data. In my case, it’s something like the following: As you can clearly make out, the data makes no sense and is clearly just for this demonstration. Anyway, the first column we have here is a text field, and is categorical in a sense. So we’ll have to label encode this and also one hot encode to be sure we’ll not be working with any hierarchy. For this, we’ll still need the OneHotEncoder library to be imported in our code. But instead of the LabelEncoder library, we’ll use the new ColumnTransformer. So let’s import these two first: from sklearn.preprocessing import OneHotEncoderfrom sklearn.compose import ColumnTransformer Next, we have to create an object of the ColumnTransformer class. But before we can do that, we need to understand the constructor signature of the class. The ColumnTransformer constructor takes quite a few arguments, but we’re only interested in two. The first argument is an array called transformers, which is a list of tuples. The array has the following elements in the same order: name: a name for the column transformer, which will make setting of parameters and searching of the transformer easy. transformer: here we’re supposed to provide an estimator. We can also just “passthrough” or “drop” if we want. But since we’re encoding the data in this example, we’ll use the OneHotEncoder here. Remember that the estimator you use here needs to support fit and transform. column(s): the list of columns which you want to be transformed. In this case, we’ll only transform the first column. The second parameter we’re interested in is the remainder. This will tell the transformer what to do with the other columns in the dataset. By default, only the columns which are transformed will be returned by the transformer. All other columns will be dropped. But we have the option to tell the transformer what to do with the other columns. We can either drop them, pass them through unchanged, or specify another estimator if we want to do some more processing. Now that we (somewhat) understand the signature of the constructor, let’s go ahead and create an object: columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough') As you can see from the snippet above, we’ll name the transformer simply “encoder.” We’re using the OneHotEncoder() constructor to provide a new instance as the estimator. And then we’re specifying that only the first column has to be transformed. We’re also making sure that the remainder columns are passed through without any changes. Once we have constructed this columnTransformer object, we have to fit and transform the dataset to label encode and one hot encode the column. For this, we’ll use the following simple command: dataset = np.array(columnTransformer.fit_transform(dataset), dtype = np.str) If you check your dataset now in the Variable explorer view, you should see something similar to this: As you can see, we have easily label encoded and one hot encoded a column in our dataset using only the ColumnTransformer class. This so much more easier and cleaner than using both LabelEncoder and OneHotEncoder classes. Follow me on Twitter for more Data Science, Machine Learning, and general tech updates. Also, you can follow my personal blog as I post a lot of my tutorials, how-to posts, and machine learning goodness there before Medium. If you like my posts here on Medium or on my personal blog, and would wish for me to continue doing this work, consider supporting me on Patreon.
[ { "code": null, "e": 497, "s": 172, "text": "In a very old post — Label Encoder vs. One Hot Encoder in Machine Learning — I had demonstrated how to use label encoding and one hot encoding to separate out categorical text data into numbers and different columns. But the SciKit library has come a long way since I wrote that post, and it has made life a lot more easier." }, { "code": null, "e": 902, "s": 497, "text": "The developers of the library might have realised that people use LabelEncoding and OneHotEncoding very frequently. So they decided to come up with a new library called the ColumnTransformer, which will basically combine LabelEncoding and OneHotEncoding into just one line of code. And the result is exactly the same. In this post, we’ll quickly take a look at how we can do that with some code snippets." }, { "code": null, "e": 1013, "s": 902, "text": "First, as usual, we need to import the required libraries. We’ll go with the convention here for the aliasing:" }, { "code": null, "e": 1051, "s": 1013, "text": "import numpy as npimport pandas as pd" }, { "code": null, "e": 1126, "s": 1051, "text": "Next, let’s get some data into a variable and see what we’re working with:" }, { "code": null, "e": 1204, "s": 1126, "text": "dataset = pd.read_csv(\"/home/sunny/code/machine_learning/samples/sample.csv\")" }, { "code": null, "e": 1330, "s": 1204, "text": "You can use the “Variable explorer” view in Spyder to take a look at the data. In my case, it’s something like the following:" }, { "code": null, "e": 1816, "s": 1330, "text": "As you can clearly make out, the data makes no sense and is clearly just for this demonstration. Anyway, the first column we have here is a text field, and is categorical in a sense. So we’ll have to label encode this and also one hot encode to be sure we’ll not be working with any hierarchy. For this, we’ll still need the OneHotEncoder library to be imported in our code. But instead of the LabelEncoder library, we’ll use the new ColumnTransformer. So let’s import these two first:" }, { "code": null, "e": 1909, "s": 1816, "text": "from sklearn.preprocessing import OneHotEncoderfrom sklearn.compose import ColumnTransformer" }, { "code": null, "e": 2296, "s": 1909, "text": "Next, we have to create an object of the ColumnTransformer class. But before we can do that, we need to understand the constructor signature of the class. The ColumnTransformer constructor takes quite a few arguments, but we’re only interested in two. The first argument is an array called transformers, which is a list of tuples. The array has the following elements in the same order:" }, { "code": null, "e": 2414, "s": 2296, "text": "name: a name for the column transformer, which will make setting of parameters and searching of the transformer easy." }, { "code": null, "e": 2687, "s": 2414, "text": "transformer: here we’re supposed to provide an estimator. We can also just “passthrough” or “drop” if we want. But since we’re encoding the data in this example, we’ll use the OneHotEncoder here. Remember that the estimator you use here needs to support fit and transform." }, { "code": null, "e": 2805, "s": 2687, "text": "column(s): the list of columns which you want to be transformed. In this case, we’ll only transform the first column." }, { "code": null, "e": 3272, "s": 2805, "text": "The second parameter we’re interested in is the remainder. This will tell the transformer what to do with the other columns in the dataset. By default, only the columns which are transformed will be returned by the transformer. All other columns will be dropped. But we have the option to tell the transformer what to do with the other columns. We can either drop them, pass them through unchanged, or specify another estimator if we want to do some more processing." }, { "code": null, "e": 3377, "s": 3272, "text": "Now that we (somewhat) understand the signature of the constructor, let’s go ahead and create an object:" }, { "code": null, "e": 3477, "s": 3377, "text": "columnTransformer = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')" }, { "code": null, "e": 3815, "s": 3477, "text": "As you can see from the snippet above, we’ll name the transformer simply “encoder.” We’re using the OneHotEncoder() constructor to provide a new instance as the estimator. And then we’re specifying that only the first column has to be transformed. We’re also making sure that the remainder columns are passed through without any changes." }, { "code": null, "e": 4009, "s": 3815, "text": "Once we have constructed this columnTransformer object, we have to fit and transform the dataset to label encode and one hot encode the column. For this, we’ll use the following simple command:" }, { "code": null, "e": 4086, "s": 4009, "text": "dataset = np.array(columnTransformer.fit_transform(dataset), dtype = np.str)" }, { "code": null, "e": 4189, "s": 4086, "text": "If you check your dataset now in the Variable explorer view, you should see something similar to this:" }, { "code": null, "e": 4411, "s": 4189, "text": "As you can see, we have easily label encoded and one hot encoded a column in our dataset using only the ColumnTransformer class. This so much more easier and cleaner than using both LabelEncoder and OneHotEncoder classes." }, { "code": null, "e": 4635, "s": 4411, "text": "Follow me on Twitter for more Data Science, Machine Learning, and general tech updates. Also, you can follow my personal blog as I post a lot of my tutorials, how-to posts, and machine learning goodness there before Medium." } ]
Betrothed numbers - GeeksforGeeks
16 Apr, 2021 Betrothed numbers are two positive numbers such that the sum of the proper divisors of either number is one more than (or one plus) the value of the other number. Our task is to find these pairs efficiently. Example : (48, 75) is an example of Betrothed numbers Divisors of 48 : 1, 2, 3, 4, 6, 8, 12, 16, 24. Their sum is 76. Divisors of 75 : 1, 3, 5, 15, 25. Their sum is 49. Given a positive integer n, print all Brothered numbers (which is a pair) such that one of the numbers in every pair is smaller than n. Example : Input : n = 1000 Output : (48, 75), (140, 195) Input : n = 10000 Output : (48, 75), (140, 195), (1050, 1925) (1575, 1648), (2024, 2295), (5775, 6128) (8892, 16587), (9504, 20735) The idea used in below program is simple. We traverse through all numbers from 1 to n-1. For every number num1, we find sum of its proper divisors say sum1. After finding sum1, we check if the number num2 = sum1 + 1 which has sum of divisors as num1 + 1 C++ Java Python C# PHP Javascript // CPP program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n.#include <iostream>using namespace std; void BetrothedNumbers(int n){ for (int num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors int sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == num1+1) printf("(%d, %d)\n", num1, num2); } }} // Driver codeint main(){ int n = 10000; BetrothedNumbers(n); return 0;} // JAVA program to find Betrothed number// pairs such that one of the numbers is// smaller than a given number n.import java.io.*; class GFG{ static void BetrothedNumbers(int n) { for (int num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors int sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == num1+1) System.out.println("(" + num1 + ", " + num2 + ")"); } } } // Driver code public static void main(String args[]) { int n = 10000; BetrothedNumbers(n); }} // This code is contributed by Nikita Tiwari. # Python program to find Betrothed number pairs# such that one of the numbers is smaller than# a given number n. def BetrothedNumbers(n) : for num1 in range (1,n) : # Calculate sum of num1's divisors sum1 = 1 # 1 is always a divisor # i=2 because we don't want to include # 1 as a divisor. i = 2 while i * i <= num1 : if (num1 % i == 0) : sum1 = sum1 + i # we do not want to include # a divisor twice if (i * i != num1) : sum1 += num1 / i i =i + 1 # Now check if num2 is the sum of # divisors of num1, so only the num # that equals to sum of divisors of # num1 is a nominee for num1. # This if is for not to make a #duplication of the nums, because #if sum1 is smaller than num1, this #means that we have already checked #the smaller one. if (sum1 > num1) : num2 = sum1 - 1 sum2 = 1 j = 2 while j * j <= num2 : if (num2 % j == 0) : sum2 += j if (j * j != num2) : sum2 += num2 / j j = j + 1 # checks if the sum divisors of # num2 is equal to num1. if (sum2 == num1+1) : print ('('+str(num1)+', '+str(num2)+')') # Driver code n = 10000BetrothedNumbers(n) # This code is contributed by Nikita Tiwari. // C# program to find Betrothed// number pairs such that one// of the numbers is smaller// than a given number n.using System; class GFG{ static void BetrothedNumbers(int n) { for (int num1 = 1; num1 < n; num1++) { // Calculate sum of // num1's divisors // 1 is always a divisor int sum1 = 1; // i=2 because we don't want // to include 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the // sum of divisors of num1, // so only the num that equals // to sum of divisors of num1 // is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors // of num2 is equal to num1. if (sum2 == num1 + 1) Console.WriteLine("(" + num1 + ", " + num2 + ")"); } } } // Driver code public static void Main() { int n = 10000; BetrothedNumbers(n); }} // This code is contributed by nitin mittal. <?php// PHP program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n. function BetrothedNumbers($n){ for ( $num1 = 1; $num1 < $n; $num1++) { // Calculate sum of num1's divisors // 1 is always a divisor $sum1 = 1; // i=2 because we don't want to include // 1 as a divisor. for ( $i = 2; $i * $i <= $num1; $i++) { if ($num1 % $i == 0) { $sum1 += $i; // we do not want to include // a divisor twice if ($i * $i != $num1) $sum1 += $num1 / $i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if ($sum1 > $num1) { $num2 = $sum1 - 1; $sum2 = 1; for ($j = 2; $j * $j <= $num2; $j++) { if ($num2 % $j == 0) { $sum2 += $j; if ($j * $j != $num2) $sum2 += $num2 / $j; } } // checks if the sum divisors of // num2 is equal to num1. if ($sum2 == $num1+1) echo"(",$num1," ",$num2,")\n"; } }} // Driver code $n = 10000; BetrothedNumbers($n); // This code is contributed by anuj_67.?> <script>// Javascript program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n.function BetrothedNumbers(n){ for (let num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors let sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (let i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += parseInt(num1 / i); } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { let num2 = sum1 - 1; let sum2 = 1; for (let j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += parseInt(num2 / j); } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == (num1+1)) document.write(`(${num1}, ${num2})<br>`); } }} // Driver code let n = 10000; BetrothedNumbers(n); // This code is contributed by rishavmahato348.</script> Output : (48, 75) (140, 195) (1050, 1925) (1575, 1648) (2024, 2295) (5775, 6128) (8892, 16587) (9504, 20735) This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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. nitin mittal vt_m besupujis rishavmahato348 number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Count all possible paths from top left to bottom right of a mXn matrix Modular multiplicative inverse Program to multiply two matrices Fizz Buzz Implementation Check if a number is Palindrome Count ways to reach the n'th stair Merge two sorted arrays with O(1) extra space Min Cost Path | DP-6
[ { "code": null, "e": 25963, "s": 25935, "text": "\n16 Apr, 2021" }, { "code": null, "e": 26183, "s": 25963, "text": "Betrothed numbers are two positive numbers such that the sum of the proper divisors of either number is one more than (or one plus) the value of the other number. Our task is to find these pairs efficiently. Example : " }, { "code": null, "e": 26378, "s": 26183, "text": "(48, 75) is an example of Betrothed numbers\nDivisors of 48 : 1, 2, 3, 4, 6, 8, 12, \n 16, 24. Their sum is 76.\nDivisors of 75 : 1, 3, 5, 15, 25. Their \n sum is 49." }, { "code": null, "e": 26526, "s": 26378, "text": "Given a positive integer n, print all Brothered numbers (which is a pair) such that one of the numbers in every pair is smaller than n. Example : " }, { "code": null, "e": 26725, "s": 26526, "text": "Input : n = 1000\nOutput : (48, 75), (140, 195)\n\nInput : n = 10000\nOutput : (48, 75), (140, 195), (1050, 1925)\n (1575, 1648), (2024, 2295), (5775, \n 6128) (8892, 16587), (9504, 20735)" }, { "code": null, "e": 26983, "s": 26727, "text": "The idea used in below program is simple. We traverse through all numbers from 1 to n-1. For every number num1, we find sum of its proper divisors say sum1. After finding sum1, we check if the number num2 = sum1 + 1 which has sum of divisors as num1 + 1 " }, { "code": null, "e": 26987, "s": 26983, "text": "C++" }, { "code": null, "e": 26992, "s": 26987, "text": "Java" }, { "code": null, "e": 26999, "s": 26992, "text": "Python" }, { "code": null, "e": 27002, "s": 26999, "text": "C#" }, { "code": null, "e": 27006, "s": 27002, "text": "PHP" }, { "code": null, "e": 27017, "s": 27006, "text": "Javascript" }, { "code": "// CPP program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n.#include <iostream>using namespace std; void BetrothedNumbers(int n){ for (int num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors int sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == num1+1) printf(\"(%d, %d)\\n\", num1, num2); } }} // Driver codeint main(){ int n = 10000; BetrothedNumbers(n); return 0;}", "e": 28652, "s": 27017, "text": null }, { "code": "// JAVA program to find Betrothed number// pairs such that one of the numbers is// smaller than a given number n.import java.io.*; class GFG{ static void BetrothedNumbers(int n) { for (int num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors int sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == num1+1) System.out.println(\"(\" + num1 + \", \" + num2 + \")\"); } } } // Driver code public static void main(String args[]) { int n = 10000; BetrothedNumbers(n); }} // This code is contributed by Nikita Tiwari.", "e": 30383, "s": 28652, "text": null }, { "code": "# Python program to find Betrothed number pairs# such that one of the numbers is smaller than# a given number n. def BetrothedNumbers(n) : for num1 in range (1,n) : # Calculate sum of num1's divisors sum1 = 1 # 1 is always a divisor # i=2 because we don't want to include # 1 as a divisor. i = 2 while i * i <= num1 : if (num1 % i == 0) : sum1 = sum1 + i # we do not want to include # a divisor twice if (i * i != num1) : sum1 += num1 / i i =i + 1 # Now check if num2 is the sum of # divisors of num1, so only the num # that equals to sum of divisors of # num1 is a nominee for num1. # This if is for not to make a #duplication of the nums, because #if sum1 is smaller than num1, this #means that we have already checked #the smaller one. if (sum1 > num1) : num2 = sum1 - 1 sum2 = 1 j = 2 while j * j <= num2 : if (num2 % j == 0) : sum2 += j if (j * j != num2) : sum2 += num2 / j j = j + 1 # checks if the sum divisors of # num2 is equal to num1. if (sum2 == num1+1) : print ('('+str(num1)+', '+str(num2)+')') # Driver code n = 10000BetrothedNumbers(n) # This code is contributed by Nikita Tiwari.", "e": 31956, "s": 30383, "text": null }, { "code": "// C# program to find Betrothed// number pairs such that one// of the numbers is smaller// than a given number n.using System; class GFG{ static void BetrothedNumbers(int n) { for (int num1 = 1; num1 < n; num1++) { // Calculate sum of // num1's divisors // 1 is always a divisor int sum1 = 1; // i=2 because we don't want // to include 1 as a divisor. for (int i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += num1 / i; } } // Now check if num2 is the // sum of divisors of num1, // so only the num that equals // to sum of divisors of num1 // is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { int num2 = sum1 - 1; int sum2 = 1; for (int j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += num2 / j; } } // checks if the sum divisors // of num2 is equal to num1. if (sum2 == num1 + 1) Console.WriteLine(\"(\" + num1 + \", \" + num2 + \")\"); } } } // Driver code public static void Main() { int n = 10000; BetrothedNumbers(n); }} // This code is contributed by nitin mittal.", "e": 33738, "s": 31956, "text": null }, { "code": "<?php// PHP program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n. function BetrothedNumbers($n){ for ( $num1 = 1; $num1 < $n; $num1++) { // Calculate sum of num1's divisors // 1 is always a divisor $sum1 = 1; // i=2 because we don't want to include // 1 as a divisor. for ( $i = 2; $i * $i <= $num1; $i++) { if ($num1 % $i == 0) { $sum1 += $i; // we do not want to include // a divisor twice if ($i * $i != $num1) $sum1 += $num1 / $i; } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if ($sum1 > $num1) { $num2 = $sum1 - 1; $sum2 = 1; for ($j = 2; $j * $j <= $num2; $j++) { if ($num2 % $j == 0) { $sum2 += $j; if ($j * $j != $num2) $sum2 += $num2 / $j; } } // checks if the sum divisors of // num2 is equal to num1. if ($sum2 == $num1+1) echo\"(\",$num1,\" \",$num2,\")\\n\"; } }} // Driver code $n = 10000; BetrothedNumbers($n); // This code is contributed by anuj_67.?>", "e": 35385, "s": 33738, "text": null }, { "code": "<script>// Javascript program to find Betrothed number pairs// such that one of the numbers is smaller than// a given number n.function BetrothedNumbers(n){ for (let num1 = 1; num1 < n; num1++) { // Calculate sum of num1's divisors let sum1 = 1; // 1 is always a divisor // i=2 because we don't want to include // 1 as a divisor. for (let i = 2; i * i <= num1; i++) { if (num1 % i == 0) { sum1 += i; // we do not want to include // a divisor twice if (i * i != num1) sum1 += parseInt(num1 / i); } } // Now check if num2 is the sum of // divisors of num1, so only the num // that equals to sum of divisors of // num1 is a nominee for num1. /* This if is for not to make a duplication of the nums, because if sum1 is smaller than num1, this means that we have already checked the smaller one.*/ if (sum1 > num1) { let num2 = sum1 - 1; let sum2 = 1; for (let j = 2; j * j <= num2; j++) { if (num2 % j == 0) { sum2 += j; if (j * j != num2) sum2 += parseInt(num2 / j); } } // checks if the sum divisors of // num2 is equal to num1. if (sum2 == (num1+1)) document.write(`(${num1}, ${num2})<br>`); } }} // Driver code let n = 10000; BetrothedNumbers(n); // This code is contributed by rishavmahato348.</script>", "e": 37060, "s": 35385, "text": null }, { "code": null, "e": 37071, "s": 37060, "text": "Output : " }, { "code": null, "e": 37171, "s": 37071, "text": "(48, 75)\n(140, 195)\n(1050, 1925)\n(1575, 1648)\n(2024, 2295)\n(5775, 6128)\n(8892, 16587)\n(9504, 20735)" }, { "code": null, "e": 37599, "s": 37171, "text": "This article is contributed by Shlomi Elhaiani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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": 37612, "s": 37599, "text": "nitin mittal" }, { "code": null, "e": 37617, "s": 37612, "text": "vt_m" }, { "code": null, "e": 37627, "s": 37617, "text": "besupujis" }, { "code": null, "e": 37643, "s": 37627, "text": "rishavmahato348" }, { "code": null, "e": 37657, "s": 37643, "text": "number-theory" }, { "code": null, "e": 37670, "s": 37657, "text": "Mathematical" }, { "code": null, "e": 37684, "s": 37670, "text": "number-theory" }, { "code": null, "e": 37697, "s": 37684, "text": "Mathematical" }, { "code": null, "e": 37795, "s": 37697, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37839, "s": 37795, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 37881, "s": 37839, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 37952, "s": 37881, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 37983, "s": 37952, "text": "Modular multiplicative inverse" }, { "code": null, "e": 38016, "s": 37983, "text": "Program to multiply two matrices" }, { "code": null, "e": 38041, "s": 38016, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 38073, "s": 38041, "text": "Check if a number is Palindrome" }, { "code": null, "e": 38108, "s": 38073, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 38154, "s": 38108, "text": "Merge two sorted arrays with O(1) extra space" } ]
Link Prediction - Predict edges in a network using Networkx - GeeksforGeeks
08 May, 2020 Link Prediction is used to predict future possible links in a network. Link Prediction is the algorithm based on which Facebook recommends People you May Know, Amazon predicts items you’re likely going to be interested in and Zomato recommends food you’re likely going to order. For this article, we would consider a Graph as constructed below: import networkx as nximport matplotlib.pyplot as plt G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) plt.figure(figsize =(10, 10))nx.draw_networkx(G, with_labels = True) Output: The following means can be assumed in order to successfully predict edges in a network : Triadic closureJaccard CoefficientResource Allocation IndexAdamic Adar IndexPreferential AttachmentCommunity Common NeighborCommunity Resource Allocation Triadic closure Jaccard Coefficient Resource Allocation Index Adamic Adar Index Preferential Attachment Community Common Neighbor Community Resource Allocation If two vertices are connected to the same third vertices, the tendency for them to share a connection is Triadic Closure. comm_neighb(X, Y) = |N(X) N(Y)|, where N(X) is the set of all neighbours of X. import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)])e = list(G.edges()) def triadic(e): new_edges = [] for i in e: a, b = i for j in e: x, y = j if i != j: if a == x and (b, y) not in e and (y, b) not in e: new_edges.append((b, y)) if a == y and (b, x) not in e and (x, b) not in e: new_edges.append((b, x)) if b == x and (a, y) not in e and (y, a) not in e: new_edges.append((a, y)) if b == y and (a, x) not in e and (x, a) not in e: new_edges.append((a, x)) return new_edges print("The possible new edges according to Triadic closure are :")print(triadic(e)) Output: The possible new edges according to Triadic closure are : [(2, 3), (2, 4), (3, 2), (4, 2), (1, 5), (3, 5), (5, 1), (5, 3)] It is calculated by number of common neighbors normalized by total number of neighbors. It is used to measure the similarity between two finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets. Jaccard Coefficient(X, Y) = import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.jaccard_coefficient(G)) Output: [(1, 5, 0.3333333333333333), (2, 3, 0.5), (2, 4, 0.3333333333333333), (2, 5, 0.0), (3, 5, 0.5)] The jaccard_coefficient built-in function of Networkx necessarily returns a list of 3 tuples (u, v, p), where u, v is the new edge which will be added next with a probability measure of p (p is the Jaccard Coefficient of nodes u and v). Among a number of similarity-based methods to predict missing links in a complex network, Research Allocation Index performs well with lower time complexity. It is defined as a fraction of a resource that a node can send to another through their common neighbors. Research Allocation Index(X, Y) = import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.resource_allocation_index(G))) Output: [(1, 5, 0.3333333333333333), (2, 3, 0.3333333333333333), (2, 4, 0.3333333333333333), (2, 5, 0), (3, 5, 0.3333333333333333)] The networkx package offers an in-built function of resource_allocation_index which offers a list of 3 tuples (u, v, p), where u, v is the new edge and p is the resource allocation index of the new edge u, v. This measure was introduced in 2003 to predict missing links in a Network, according to the amount of shared links between two nodes. It is calculated as follows: Adamic Adar Index(X, Y) = import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.adamic_adar_index(G))) Output: [(1, 5, 0.9102392266268373), (2, 3, 0.9102392266268373), (2, 4, 0.9102392266268373), (2, 5, 0), (3, 5, 0.9102392266268373)] The networkx package offers an in-built function of adamic_adar_index which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the adamic adar index of the new edge u, v. Preferential attachment means that the more connected a node is, the more likely it is to receive new links (refer to this article for referring to Barabasi Albert graph formed on the concepts of Preferential Attachment) Nodes with higher degree gets more neighbors. Preferential Attachment(X, Y) = |N(X)|.|N(Y)| import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.preferential_attachment(G))) Output: [(1, 5, 3), (2, 3, 2), (2, 4, 3), (2, 5, 1), (3, 5, 2)] The networkx package offers an in-built function of preferential_attachment which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the preferential attachment score of the new edge u, v. Number of common neighbors with bonus for neighbors in same community. For applying this, we have to specify the community of all nodes. Community Common Neighbors(X, Y) = |N(X) N(Y)| + ,where f(u) = 1, if u is in a community; otherwise 0. import networkx as nximport matplotlib.pyplot as plt G = nx.Graph()G.add_node('A', community = 0)G.add_node('B', community = 0)G.add_node('C', community = 0)G.add_node('D', community = 0)G.add_node('E', community = 1)G.add_node('F', community = 1)G.add_node('G', community = 1)G.add_node('H', community = 1)G.add_node('I', community = 1) G.add_edges_from([('A', 'B'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('C', 'D'), ('C', 'F'), ('E', 'F'), ('E', 'G'), ('F', 'G'), ('G', 'H'), ('G', 'I')]) nx.draw_networkx(G)print(list(nx.cn_soundarajan_hopcroft(G))) Output: [('I', 'A', 0), ('I', 'C', 0), ('I', 'D', 0), ('I', 'E', 2), ('I', 'H', 2), ('I', 'F', 2), ('I', 'B', 0), ('A', 'H', 0), ('A', 'C', 4), ('A', 'G', 1), ('A', 'F', 1), ('C', 'H', 0), ('C', 'G', 1), ('C', 'E', 1), ('D', 'G', 0), ('D', 'E', 1), ('D', 'H', 0), ('D', 'F', 1), ('D', 'B', 4), ('G', 'B', 0), ('E', 'H', 2), ('E', 'B', 1), ('H', 'F', 2), ('H', 'B', 0), ('F', 'B', 1)] The networkx package offers an in-built function of cn_soundarajan_hopcroft which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the score of the new edge u, v. Computes the resource allocation index of all node pairs using community information. Community Resource Allocation(X, Y) = import networkx as nx G = nx.Graph() G.add_node('A', community = 0)G.add_node('B', community = 0)G.add_node('C', community = 0)G.add_node('D', community = 0)G.add_node('E', community = 1)G.add_node('F', community = 1)G.add_node('G', community = 1)G.add_node('H', community = 1)G.add_node('I', community = 1) G.add_edges_from([('A', 'B'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('C', 'D'), ('C', 'F'), ('E', 'F'), ('E', 'G'), ('F', 'G'), ('G', 'H'), ('G', 'I')]) print(list(nx.ra_index_soundarajan_hopcroft(G))) Output: [('I', 'A', 0), ('I', 'C', 0), ('I', 'D', 0), ('I', 'E', 0.25), ('I', 'H', 0.25), ('I', 'F', 0.25), ('I', 'B', 0), ('A', 'H', 0), ('A', 'C', 1.0), ('A', 'G', 0), ('A', 'F', 0), ('C', 'H', 0), ('C', 'G', 0), ('C', 'E', 0), ('D', 'G', 0), ('D', 'E', 0), ('D', 'H', 0), ('D', 'F', 0), ('D', 'B', 0.6666666666666666), ('G', 'B', 0), ('E', 'H', 0.25), ('E', 'B', 0), ('H', 'F', 0.25), ('H', 'B', 0), ('F', 'B', 0)] The networkx package offers an in-built function of ra_index_soundarajan_hopcroft which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the score of the new edge u, v. Python Networx-module 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n08 May, 2020" }, { "code": null, "e": 25842, "s": 25563, "text": "Link Prediction is used to predict future possible links in a network. Link Prediction is the algorithm based on which Facebook recommends People you May Know, Amazon predicts items you’re likely going to be interested in and Zomato recommends food you’re likely going to order." }, { "code": null, "e": 25908, "s": 25842, "text": "For this article, we would consider a Graph as constructed below:" }, { "code": "import networkx as nximport matplotlib.pyplot as plt G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) plt.figure(figsize =(10, 10))nx.draw_networkx(G, with_labels = True)", "e": 26105, "s": 25908, "text": null }, { "code": null, "e": 26113, "s": 26105, "text": "Output:" }, { "code": null, "e": 26202, "s": 26113, "text": "The following means can be assumed in order to successfully predict edges in a network :" }, { "code": null, "e": 26356, "s": 26202, "text": "Triadic closureJaccard CoefficientResource Allocation IndexAdamic Adar IndexPreferential AttachmentCommunity Common NeighborCommunity Resource Allocation" }, { "code": null, "e": 26372, "s": 26356, "text": "Triadic closure" }, { "code": null, "e": 26392, "s": 26372, "text": "Jaccard Coefficient" }, { "code": null, "e": 26418, "s": 26392, "text": "Resource Allocation Index" }, { "code": null, "e": 26436, "s": 26418, "text": "Adamic Adar Index" }, { "code": null, "e": 26460, "s": 26436, "text": "Preferential Attachment" }, { "code": null, "e": 26486, "s": 26460, "text": "Community Common Neighbor" }, { "code": null, "e": 26516, "s": 26486, "text": "Community Resource Allocation" }, { "code": null, "e": 26638, "s": 26516, "text": "If two vertices are connected to the same third vertices, the tendency for them to share a connection is Triadic Closure." }, { "code": null, "e": 26718, "s": 26638, "text": "comm_neighb(X, Y) = |N(X) N(Y)|, where N(X) is the set of all neighbours of X." }, { "code": "import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)])e = list(G.edges()) def triadic(e): new_edges = [] for i in e: a, b = i for j in e: x, y = j if i != j: if a == x and (b, y) not in e and (y, b) not in e: new_edges.append((b, y)) if a == y and (b, x) not in e and (x, b) not in e: new_edges.append((b, x)) if b == x and (a, y) not in e and (y, a) not in e: new_edges.append((a, y)) if b == y and (a, x) not in e and (x, a) not in e: new_edges.append((a, x)) return new_edges print(\"The possible new edges according to Triadic closure are :\")print(triadic(e))", "e": 27415, "s": 26718, "text": null }, { "code": null, "e": 27423, "s": 27415, "text": "Output:" }, { "code": null, "e": 27547, "s": 27423, "text": "The possible new edges according to Triadic closure are :\n[(2, 3), (2, 4), (3, 2), (4, 2), (1, 5), (3, 5), (5, 1), (5, 3)]\n" }, { "code": null, "e": 27804, "s": 27547, "text": "It is calculated by number of common neighbors normalized by total number of neighbors. It is used to measure the similarity between two finite sample sets, and is defined as the size of the intersection divided by the size of the union of the sample sets." }, { "code": null, "e": 27833, "s": 27804, "text": "Jaccard Coefficient(X, Y) = " }, { "code": "import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.jaccard_coefficient(G))", "e": 27968, "s": 27833, "text": null }, { "code": null, "e": 27976, "s": 27968, "text": "Output:" }, { "code": null, "e": 28072, "s": 27976, "text": "[(1, 5, 0.3333333333333333), (2, 3, 0.5), (2, 4, 0.3333333333333333), (2, 5, 0.0), (3, 5, 0.5)]" }, { "code": null, "e": 28309, "s": 28072, "text": "The jaccard_coefficient built-in function of Networkx necessarily returns a list of 3 tuples (u, v, p), where u, v is the new edge which will be added next with a probability measure of p (p is the Jaccard Coefficient of nodes u and v)." }, { "code": null, "e": 28573, "s": 28309, "text": "Among a number of similarity-based methods to predict missing links in a complex network, Research Allocation Index performs well with lower time complexity. It is defined as a fraction of a resource that a node can send to another through their common neighbors." }, { "code": null, "e": 28608, "s": 28573, "text": "Research Allocation Index(X, Y) = " }, { "code": "import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.resource_allocation_index(G)))", "e": 28750, "s": 28608, "text": null }, { "code": null, "e": 28758, "s": 28750, "text": "Output:" }, { "code": null, "e": 28882, "s": 28758, "text": "[(1, 5, 0.3333333333333333), (2, 3, 0.3333333333333333), (2, 4, 0.3333333333333333), (2, 5, 0), (3, 5, 0.3333333333333333)]" }, { "code": null, "e": 29091, "s": 28882, "text": "The networkx package offers an in-built function of resource_allocation_index which offers a list of 3 tuples (u, v, p), where u, v is the new edge and p is the resource allocation index of the new edge u, v." }, { "code": null, "e": 29254, "s": 29091, "text": "This measure was introduced in 2003 to predict missing links in a Network, according to the amount of shared links between two nodes. It is calculated as follows:" }, { "code": null, "e": 29281, "s": 29254, "text": "Adamic Adar Index(X, Y) = " }, { "code": "import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.adamic_adar_index(G)))", "e": 29415, "s": 29281, "text": null }, { "code": null, "e": 29423, "s": 29415, "text": "Output:" }, { "code": null, "e": 29547, "s": 29423, "text": "[(1, 5, 0.9102392266268373), (2, 3, 0.9102392266268373), (2, 4, 0.9102392266268373), (2, 5, 0), (3, 5, 0.9102392266268373)]" }, { "code": null, "e": 29739, "s": 29547, "text": "The networkx package offers an in-built function of adamic_adar_index which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the adamic adar index of the new edge u, v." }, { "code": null, "e": 30006, "s": 29739, "text": "Preferential attachment means that the more connected a node is, the more likely it is to receive new links (refer to this article for referring to Barabasi Albert graph formed on the concepts of Preferential Attachment) Nodes with higher degree gets more neighbors." }, { "code": null, "e": 30052, "s": 30006, "text": "Preferential Attachment(X, Y) = |N(X)|.|N(Y)|" }, { "code": "import networkx as nx G = nx.Graph()G.add_edges_from([(1, 2), (1, 3), (1, 4), (3, 4), (4, 5)]) print(list(nx.preferential_attachment(G)))", "e": 30192, "s": 30052, "text": null }, { "code": null, "e": 30200, "s": 30192, "text": "Output:" }, { "code": null, "e": 30257, "s": 30200, "text": "[(1, 5, 3), (2, 3, 2), (2, 4, 3), (2, 5, 1), (3, 5, 2)]\n" }, { "code": null, "e": 30467, "s": 30257, "text": "The networkx package offers an in-built function of preferential_attachment which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the preferential attachment score of the new edge u, v." }, { "code": null, "e": 30604, "s": 30467, "text": "Number of common neighbors with bonus for neighbors in same community. For applying this, we have to specify the community of all nodes." }, { "code": null, "e": 30708, "s": 30604, "text": "Community Common Neighbors(X, Y) = |N(X) N(Y)| + ,where f(u) = 1, if u is in a community; otherwise 0." }, { "code": "import networkx as nximport matplotlib.pyplot as plt G = nx.Graph()G.add_node('A', community = 0)G.add_node('B', community = 0)G.add_node('C', community = 0)G.add_node('D', community = 0)G.add_node('E', community = 1)G.add_node('F', community = 1)G.add_node('G', community = 1)G.add_node('H', community = 1)G.add_node('I', community = 1) G.add_edges_from([('A', 'B'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('C', 'D'), ('C', 'F'), ('E', 'F'), ('E', 'G'), ('F', 'G'), ('G', 'H'), ('G', 'I')]) nx.draw_networkx(G)print(list(nx.cn_soundarajan_hopcroft(G)))", "e": 31308, "s": 30708, "text": null }, { "code": null, "e": 31316, "s": 31308, "text": "Output:" }, { "code": null, "e": 31717, "s": 31316, "text": "[('I', 'A', 0),\n ('I', 'C', 0),\n ('I', 'D', 0),\n ('I', 'E', 2),\n ('I', 'H', 2),\n ('I', 'F', 2),\n ('I', 'B', 0),\n ('A', 'H', 0),\n ('A', 'C', 4),\n ('A', 'G', 1),\n ('A', 'F', 1),\n ('C', 'H', 0),\n ('C', 'G', 1),\n ('C', 'E', 1),\n ('D', 'G', 0),\n ('D', 'E', 1),\n ('D', 'H', 0),\n ('D', 'F', 1),\n ('D', 'B', 4),\n ('G', 'B', 0),\n ('E', 'H', 2),\n ('E', 'B', 1),\n ('H', 'F', 2),\n ('H', 'B', 0),\n ('F', 'B', 1)]\n" }, { "code": null, "e": 31903, "s": 31717, "text": "The networkx package offers an in-built function of cn_soundarajan_hopcroft which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the score of the new edge u, v." }, { "code": null, "e": 31989, "s": 31903, "text": "Computes the resource allocation index of all node pairs using community information." }, { "code": null, "e": 32028, "s": 31989, "text": "Community Resource Allocation(X, Y) = " }, { "code": "import networkx as nx G = nx.Graph() G.add_node('A', community = 0)G.add_node('B', community = 0)G.add_node('C', community = 0)G.add_node('D', community = 0)G.add_node('E', community = 1)G.add_node('F', community = 1)G.add_node('G', community = 1)G.add_node('H', community = 1)G.add_node('I', community = 1) G.add_edges_from([('A', 'B'), ('A', 'D'), ('A', 'E'), ('B', 'C'), ('C', 'D'), ('C', 'F'), ('E', 'F'), ('E', 'G'), ('F', 'G'), ('G', 'H'), ('G', 'I')]) print(list(nx.ra_index_soundarajan_hopcroft(G)))", "e": 32586, "s": 32028, "text": null }, { "code": null, "e": 32594, "s": 32586, "text": "Output:" }, { "code": null, "e": 33029, "s": 32594, "text": "[('I', 'A', 0),\n ('I', 'C', 0),\n ('I', 'D', 0),\n ('I', 'E', 0.25),\n ('I', 'H', 0.25),\n ('I', 'F', 0.25),\n ('I', 'B', 0),\n ('A', 'H', 0),\n ('A', 'C', 1.0),\n ('A', 'G', 0),\n ('A', 'F', 0),\n ('C', 'H', 0),\n ('C', 'G', 0),\n ('C', 'E', 0),\n ('D', 'G', 0),\n ('D', 'E', 0),\n ('D', 'H', 0),\n ('D', 'F', 0),\n ('D', 'B', 0.6666666666666666),\n ('G', 'B', 0),\n ('E', 'H', 0.25),\n ('E', 'B', 0),\n ('H', 'F', 0.25),\n ('H', 'B', 0),\n ('F', 'B', 0)]\n" }, { "code": null, "e": 33221, "s": 33029, "text": "The networkx package offers an in-built function of ra_index_soundarajan_hopcroft which offers a list of 3 tuples (u, v, p) where u, v is the new edge and p is the score of the new edge u, v." }, { "code": null, "e": 33243, "s": 33221, "text": "Python Networx-module" }, { "code": null, "e": 33250, "s": 33243, "text": "Python" }, { "code": null, "e": 33348, "s": 33250, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33380, "s": 33348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33422, "s": 33380, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33464, "s": 33422, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33520, "s": 33464, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33547, "s": 33520, "text": "Python Classes and Objects" }, { "code": null, "e": 33586, "s": 33547, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33617, "s": 33586, "text": "Python | os.path.join() method" }, { "code": null, "e": 33639, "s": 33617, "text": "Defaultdict in Python" }, { "code": null, "e": 33668, "s": 33639, "text": "Create a directory in Python" } ]
Getting Saved Wifi Passwords using Python - GeeksforGeeks
20 Sep, 2021 Usually while connecting with the wifi we have to enter some password to access the network, but we are not directly able to see the password we have entered earlier i.e password of saved network. In this article, we will see how we can get all the saved WiFi name and passwords using Python, in order to do this we will use subprocess module of python.Wi-Fi is a wireless networking technology that allows devices such as computers (laptops and desktops), mobile devices (smartphones and wearables), and other equipment (printers and video cameras) to interface with the Internet.The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. Steps for Implementation :1. Import the subprocess module 2. Get the metadata of the wlan(wifi) with the help of check_output method 3. Decode the metadata and split the meta data according to the line 4. From the decoded metadata get the names of the saved wlan networks 5. Now for each name again get the metadata of wlan according to the name 6. Start try and catch block and inside the try block, decode and split this metadata and get the password of the given wifi name 7. Print the password and the wifi name and print blank if there is no password 8. In except block if process error occurred print encoding error occurred Below is the implementation Python3 # importing subprocessimport subprocess # getting meta datameta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']) # decoding meta datadata = meta_data.decode('utf-8', errors ="backslashreplace") # splitting data by line by linedata = data.split('\n') # creating a list of profilesprofiles = [] # traverse the datafor i in data: # find "All User Profile" in each item if "All User Profile" in i : # if found # split the item i = i.split(":") # item at index 1 will be the wifi name i = i[1] # formatting the name # first and last character is use less i = i[1:-1] # appending the wifi name in the list profiles.append(i) # printing heading print("{:<30}| {:<}".format("Wi-Fi Name", "Password"))print("----------------------------------------------") # traversing the profiles for i in profiles: # try catch block begins # try block try: # getting meta data with password using wifi name results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key = clear']) # decoding and splitting data line by line results = results.decode('utf-8', errors ="backslashreplace") results = results.split('\n') # finding password from the result list results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b] # if there is password it will print the pass word try: print("{:<30}| {:<}".format(i, results[0])) # else it will print blank in front of pass word except IndexError: print("{:<30}| {:<}".format(i, "")) # called when this process get failed except subprocess.CalledProcessError: print("Encoding Error Occured") Output : Wi-Fi Name | Password ----------------------------------------------- Engineer | ayush123 honor | 1234567890 Engineer_5GHz | ayush123 Redmi | 12345677 Ayush | 123123123 BiGX-cmtqaGFtYjc | rakshit123 UERJTTBV8e0GUmVkbWkg 2 | 987654321 DESKTOP-F32H70N 5009 | SUSHANT@123 UERJTTBV8e0GUmVkbWkg | Bunns | heyhotspot Hogwarts | sushant@123 Cgc wireless | database1234 Moto G (5) Plus 8691 | rakshit123 AndroidAP | udrw7859 AndroidAPab7e | 123000123 roshan | 12345678 Svj? | salonivij Hey | heythere AndroidAP202 | bhuvanbroo JARVIS | abhishek09 B6NO-wq5hamF0IGt1bWHCrg | 12345678 CDAC | simranarora5sos sooda367 gulshankumarar231 python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n20 Sep, 2021" }, { "code": null, "e": 26368, "s": 25537, "text": "Usually while connecting with the wifi we have to enter some password to access the network, but we are not directly able to see the password we have entered earlier i.e password of saved network. In this article, we will see how we can get all the saved WiFi name and passwords using Python, in order to do this we will use subprocess module of python.Wi-Fi is a wireless networking technology that allows devices such as computers (laptops and desktops), mobile devices (smartphones and wearables), and other equipment (printers and video cameras) to interface with the Internet.The subprocess module present in Python(both 2.x and 3.x) is used to run new applications or programs through Python code by creating new processes. It also helps to obtain the input/output/error pipes as well as the exit codes of various commands. " }, { "code": null, "e": 27001, "s": 26368, "text": "Steps for Implementation :1. Import the subprocess module 2. Get the metadata of the wlan(wifi) with the help of check_output method 3. Decode the metadata and split the meta data according to the line 4. From the decoded metadata get the names of the saved wlan networks 5. Now for each name again get the metadata of wlan according to the name 6. Start try and catch block and inside the try block, decode and split this metadata and get the password of the given wifi name 7. Print the password and the wifi name and print blank if there is no password 8. In except block if process error occurred print encoding error occurred " }, { "code": null, "e": 27031, "s": 27001, "text": "Below is the implementation " }, { "code": null, "e": 27039, "s": 27031, "text": "Python3" }, { "code": "# importing subprocessimport subprocess # getting meta datameta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']) # decoding meta datadata = meta_data.decode('utf-8', errors =\"backslashreplace\") # splitting data by line by linedata = data.split('\\n') # creating a list of profilesprofiles = [] # traverse the datafor i in data: # find \"All User Profile\" in each item if \"All User Profile\" in i : # if found # split the item i = i.split(\":\") # item at index 1 will be the wifi name i = i[1] # formatting the name # first and last character is use less i = i[1:-1] # appending the wifi name in the list profiles.append(i) # printing heading print(\"{:<30}| {:<}\".format(\"Wi-Fi Name\", \"Password\"))print(\"----------------------------------------------\") # traversing the profiles for i in profiles: # try catch block begins # try block try: # getting meta data with password using wifi name results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key = clear']) # decoding and splitting data line by line results = results.decode('utf-8', errors =\"backslashreplace\") results = results.split('\\n') # finding password from the result list results = [b.split(\":\")[1][1:-1] for b in results if \"Key Content\" in b] # if there is password it will print the pass word try: print(\"{:<30}| {:<}\".format(i, results[0])) # else it will print blank in front of pass word except IndexError: print(\"{:<30}| {:<}\".format(i, \"\")) # called when this process get failed except subprocess.CalledProcessError: print(\"Encoding Error Occured\")", "e": 28926, "s": 27039, "text": null }, { "code": null, "e": 28937, "s": 28926, "text": "Output : " }, { "code": null, "e": 29938, "s": 28937, "text": "Wi-Fi Name | Password\n-----------------------------------------------\nEngineer | ayush123\nhonor | 1234567890\nEngineer_5GHz | ayush123\nRedmi | 12345677\nAyush | 123123123\nBiGX-cmtqaGFtYjc | rakshit123\nUERJTTBV8e0GUmVkbWkg 2 | 987654321\nDESKTOP-F32H70N 5009 | SUSHANT@123\nUERJTTBV8e0GUmVkbWkg | \nBunns | heyhotspot\nHogwarts | sushant@123\nCgc wireless | database1234\nMoto G (5) Plus 8691 | rakshit123\nAndroidAP | udrw7859\nAndroidAPab7e | 123000123\nroshan | 12345678\nSvj? | salonivij\nHey | heythere\nAndroidAP202 | bhuvanbroo\nJARVIS | abhishek09\nB6NO-wq5hamF0IGt1bWHCrg | 12345678\nCDAC | " }, { "code": null, "e": 29956, "s": 29940, "text": "simranarora5sos" }, { "code": null, "e": 29965, "s": 29956, "text": "sooda367" }, { "code": null, "e": 29983, "s": 29965, "text": "gulshankumarar231" }, { "code": null, "e": 29998, "s": 29983, "text": "python-utility" }, { "code": null, "e": 30005, "s": 29998, "text": "Python" }, { "code": null, "e": 30021, "s": 30005, "text": "Python Programs" }, { "code": null, "e": 30119, "s": 30021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30151, "s": 30119, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30193, "s": 30151, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30235, "s": 30193, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30262, "s": 30235, "text": "Python Classes and Objects" }, { "code": null, "e": 30318, "s": 30262, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30340, "s": 30318, "text": "Defaultdict in Python" }, { "code": null, "e": 30379, "s": 30340, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 30425, "s": 30379, "text": "Python | Split string into list of characters" }, { "code": null, "e": 30463, "s": 30425, "text": "Python | Convert a list to dictionary" } ]
Python | Using PIL ImageGrab and PyTesseract - GeeksforGeeks
13 Oct, 2019 ImageGrab is a Python module that helps to capture the contents of the screen. PyTesseract is an Optical Character Recognition(OCR) tool for Python. Together they can be used to read the contents of a section of the screen. Installation – Pillow (a newer version of PIL) pip install Pillow PyTesseract pip install pytesseract Apart from this, a tesseract executable needs to be installed. The following functions were primarily used in the code – pytesseract.image_to_string(image, lang=**language**) – Takes the image and searches for words of the language in their text. cv2.cvtColor(image, **colour conversion**) – Used to make the image monochrome(using cv2.COLOR_BGR2GRAY). ImageGrab.grab(bbox=**Coordinates of the area of the screen to be captured**) – Used to repeatedly(using a loop) capture a specific part of the screen. The objectives of the code are: To use a loop to repeatedly capture a part of the screen.To convert the captured image into grayscale.Use PyTesseract to read the text in it. To use a loop to repeatedly capture a part of the screen. To convert the captured image into grayscale. Use PyTesseract to read the text in it. Code : Python code to use ImageGrab and PyTesseract # cv2.cvtColor takes a numpy ndarray as an argumentimport numpy as nm import pytesseract # importing OpenCVimport cv2 from PIL import ImageGrab def imToString(): # Path of tesseract executable pytesseract.pytesseract.tesseract_cmd ='**Path to tesseract executable**' while(True): # ImageGrab-To capture the screen image in a loop. # Bbox used to capture a specific area. cap = ImageGrab.grab(bbox =(700, 300, 1400, 900)) # Converted the image to monochrome for it to be easily # read by the OCR and obtained the output String. tesstr = pytesseract.image_to_string( cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), lang ='eng') print(tesstr) # Calling the functionimToString() The above code can be used to capture a certain section of the screen and read the text contents of it. NumpyOpenCV(cv2) Image-Processing Python-pil 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": 25562, "s": 25534, "text": "\n13 Oct, 2019" }, { "code": null, "e": 25786, "s": 25562, "text": "ImageGrab is a Python module that helps to capture the contents of the screen. PyTesseract is an Optical Character Recognition(OCR) tool for Python. Together they can be used to read the contents of a section of the screen." }, { "code": null, "e": 25801, "s": 25786, "text": "Installation –" }, { "code": null, "e": 25833, "s": 25801, "text": "Pillow (a newer version of PIL)" }, { "code": null, "e": 25852, "s": 25833, "text": "pip install Pillow" }, { "code": null, "e": 25864, "s": 25852, "text": "PyTesseract" }, { "code": null, "e": 25888, "s": 25864, "text": "pip install pytesseract" }, { "code": null, "e": 25951, "s": 25888, "text": "Apart from this, a tesseract executable needs to be installed." }, { "code": null, "e": 26009, "s": 25951, "text": "The following functions were primarily used in the code –" }, { "code": null, "e": 26135, "s": 26009, "text": "pytesseract.image_to_string(image, lang=**language**) – Takes the image and searches for words of the language in their text." }, { "code": null, "e": 26241, "s": 26135, "text": "cv2.cvtColor(image, **colour conversion**) – Used to make the image monochrome(using cv2.COLOR_BGR2GRAY)." }, { "code": null, "e": 26393, "s": 26241, "text": "ImageGrab.grab(bbox=**Coordinates of the area of the screen to be captured**) – Used to repeatedly(using a loop) capture a specific part of the screen." }, { "code": null, "e": 26425, "s": 26393, "text": "The objectives of the code are:" }, { "code": null, "e": 26567, "s": 26425, "text": "To use a loop to repeatedly capture a part of the screen.To convert the captured image into grayscale.Use PyTesseract to read the text in it." }, { "code": null, "e": 26625, "s": 26567, "text": "To use a loop to repeatedly capture a part of the screen." }, { "code": null, "e": 26671, "s": 26625, "text": "To convert the captured image into grayscale." }, { "code": null, "e": 26711, "s": 26671, "text": "Use PyTesseract to read the text in it." }, { "code": null, "e": 26763, "s": 26711, "text": "Code : Python code to use ImageGrab and PyTesseract" }, { "code": "# cv2.cvtColor takes a numpy ndarray as an argumentimport numpy as nm import pytesseract # importing OpenCVimport cv2 from PIL import ImageGrab def imToString(): # Path of tesseract executable pytesseract.pytesseract.tesseract_cmd ='**Path to tesseract executable**' while(True): # ImageGrab-To capture the screen image in a loop. # Bbox used to capture a specific area. cap = ImageGrab.grab(bbox =(700, 300, 1400, 900)) # Converted the image to monochrome for it to be easily # read by the OCR and obtained the output String. tesstr = pytesseract.image_to_string( cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY), lang ='eng') print(tesstr) # Calling the functionimToString()", "e": 27543, "s": 26763, "text": null }, { "code": null, "e": 27647, "s": 27543, "text": "The above code can be used to capture a certain section of the screen and read the text contents of it." }, { "code": null, "e": 27664, "s": 27647, "text": "NumpyOpenCV(cv2)" }, { "code": null, "e": 27681, "s": 27664, "text": "Image-Processing" }, { "code": null, "e": 27692, "s": 27681, "text": "Python-pil" }, { "code": null, "e": 27699, "s": 27692, "text": "Python" }, { "code": null, "e": 27797, "s": 27699, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27829, "s": 27797, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27871, "s": 27829, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27913, "s": 27871, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27940, "s": 27913, "text": "Python Classes and Objects" }, { "code": null, "e": 27996, "s": 27940, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28018, "s": 27996, "text": "Defaultdict in Python" }, { "code": null, "e": 28057, "s": 28018, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28088, "s": 28057, "text": "Python | os.path.join() method" }, { "code": null, "e": 28117, "s": 28088, "text": "Create a directory in Python" } ]
POWER() Function in SQL Server - GeeksforGeeks
30 Dec, 2020 POWER() function :This function in SQL Server is used to return a results after raising a specified exponent number to a specified base number. For example if the base is 5 and exponent is 2, this will return a result of 25. Features : This function is used to find a results after raising a specified exponent number to a specified base number. This function accepts two parameters base and exponent. The base value can be negative but not the exponent value. The base and exponent value can be in fraction. This function uses a formula“(base)(exponent) = Returned value”. Syntax : POWER(a, b) Parameter :This method accepts two parameters as given below : a : Specified base number. b : Specified exponent number. Returns :It returns a results after raising a specified exponent number to a specified base number. Example-1 :Getting a result of 49 for the base value 7 and exponent value 2. SELECT POWER(7, 2); Output : 49 Example-2 :Getting a result of 27 for 3 as the base and exponent value. SELECT POWER(3, 3); Output : 27 Example-3 :Using POWER() function with variables and getting a result of 1 for the base value 6 and exponent value 0. DECLARE @Base_Value INT; DECLARE @Exponent_Value INT; SET @Base_Value = 6; SET @Exponent_Value = 0; SELECT POWER(@Base_Value, @Exponent_Value); Output : 1 Example-4 :Getting a result of 0 for the base value 0 and exponent value 4. SELECT POWER(0, 4); Output : 0 Example-5 :Getting a result of -64 for the base value -4 and exponent value 3. SELECT POWER(-4, 3); Output : -64 Example-6 :Using POWER() function with variables and getting a result of 28.2 for the base float value 2.1 and exponent float value 4.5. DECLARE @Base_Value FLOAT; DECLARE @Exponent_Value FLOAT; SET @Base_Value = 2.1; SET @Exponent_Value = 4.5; SELECT POWER(@Base_Value, @Exponent_Value); Output : 28.182974409756689 Application :This function is used to return a results after raising a specified exponent number to a specified base number. DBMS-SQL SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL Interview Questions CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? Difference between DDL and DML in DBMS SQL | Views Difference between DELETE, DROP and TRUNCATE MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL | Subquery
[ { "code": null, "e": 25195, "s": 25167, "text": "\n30 Dec, 2020" }, { "code": null, "e": 25420, "s": 25195, "text": "POWER() function :This function in SQL Server is used to return a results after raising a specified exponent number to a specified base number. For example if the base is 5 and exponent is 2, this will return a result of 25." }, { "code": null, "e": 25431, "s": 25420, "text": "Features :" }, { "code": null, "e": 25541, "s": 25431, "text": "This function is used to find a results after raising a specified exponent number to a specified base number." }, { "code": null, "e": 25597, "s": 25541, "text": "This function accepts two parameters base and exponent." }, { "code": null, "e": 25656, "s": 25597, "text": "The base value can be negative but not the exponent value." }, { "code": null, "e": 25704, "s": 25656, "text": "The base and exponent value can be in fraction." }, { "code": null, "e": 25769, "s": 25704, "text": "This function uses a formula“(base)(exponent) = Returned value”." }, { "code": null, "e": 25778, "s": 25769, "text": "Syntax :" }, { "code": null, "e": 25790, "s": 25778, "text": "POWER(a, b)" }, { "code": null, "e": 25853, "s": 25790, "text": "Parameter :This method accepts two parameters as given below :" }, { "code": null, "e": 25880, "s": 25853, "text": "a : Specified base number." }, { "code": null, "e": 25911, "s": 25880, "text": "b : Specified exponent number." }, { "code": null, "e": 26011, "s": 25911, "text": "Returns :It returns a results after raising a specified exponent number to a specified base number." }, { "code": null, "e": 26088, "s": 26011, "text": "Example-1 :Getting a result of 49 for the base value 7 and exponent value 2." }, { "code": null, "e": 26108, "s": 26088, "text": "SELECT POWER(7, 2);" }, { "code": null, "e": 26117, "s": 26108, "text": "Output :" }, { "code": null, "e": 26120, "s": 26117, "text": "49" }, { "code": null, "e": 26192, "s": 26120, "text": "Example-2 :Getting a result of 27 for 3 as the base and exponent value." }, { "code": null, "e": 26212, "s": 26192, "text": "SELECT POWER(3, 3);" }, { "code": null, "e": 26221, "s": 26212, "text": "Output :" }, { "code": null, "e": 26225, "s": 26221, "text": " 27" }, { "code": null, "e": 26343, "s": 26225, "text": "Example-3 :Using POWER() function with variables and getting a result of 1 for the base value 6 and exponent value 0." }, { "code": null, "e": 26488, "s": 26343, "text": "DECLARE @Base_Value INT;\nDECLARE @Exponent_Value INT;\nSET @Base_Value = 6;\nSET @Exponent_Value = 0;\nSELECT POWER(@Base_Value, @Exponent_Value);\n" }, { "code": null, "e": 26497, "s": 26488, "text": "Output :" }, { "code": null, "e": 26499, "s": 26497, "text": "1" }, { "code": null, "e": 26575, "s": 26499, "text": "Example-4 :Getting a result of 0 for the base value 0 and exponent value 4." }, { "code": null, "e": 26595, "s": 26575, "text": "SELECT POWER(0, 4);" }, { "code": null, "e": 26604, "s": 26595, "text": "Output :" }, { "code": null, "e": 26606, "s": 26604, "text": "0" }, { "code": null, "e": 26685, "s": 26606, "text": "Example-5 :Getting a result of -64 for the base value -4 and exponent value 3." }, { "code": null, "e": 26707, "s": 26685, "text": "SELECT POWER(-4, 3);\n" }, { "code": null, "e": 26716, "s": 26707, "text": "Output :" }, { "code": null, "e": 26720, "s": 26716, "text": "-64" }, { "code": null, "e": 26857, "s": 26720, "text": "Example-6 :Using POWER() function with variables and getting a result of 28.2 for the base float value 2.1 and exponent float value 4.5." }, { "code": null, "e": 27010, "s": 26857, "text": "DECLARE @Base_Value FLOAT;\nDECLARE @Exponent_Value FLOAT;\nSET @Base_Value = 2.1;\nSET @Exponent_Value = 4.5;\nSELECT POWER(@Base_Value, @Exponent_Value);\n" }, { "code": null, "e": 27019, "s": 27010, "text": "Output :" }, { "code": null, "e": 27038, "s": 27019, "text": "28.182974409756689" }, { "code": null, "e": 27163, "s": 27038, "text": "Application :This function is used to return a results after raising a specified exponent number to a specified base number." }, { "code": null, "e": 27172, "s": 27163, "text": "DBMS-SQL" }, { "code": null, "e": 27183, "s": 27172, "text": "SQL-Server" }, { "code": null, "e": 27187, "s": 27183, "text": "SQL" }, { "code": null, "e": 27191, "s": 27187, "text": "SQL" }, { "code": null, "e": 27289, "s": 27191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27313, "s": 27289, "text": "SQL Interview Questions" }, { "code": null, "e": 27324, "s": 27313, "text": "CTE in SQL" }, { "code": null, "e": 27355, "s": 27324, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 27421, "s": 27355, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27460, "s": 27421, "text": "Difference between DDL and DML in DBMS" }, { "code": null, "e": 27472, "s": 27460, "text": "SQL | Views" }, { "code": null, "e": 27517, "s": 27472, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 27549, "s": 27517, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 27588, "s": 27549, "text": "Difference between DELETE and TRUNCATE" } ]
Minimize difference between any multiple of given three numbers with K - GeeksforGeeks
24 Dec, 2021 Given 4 integers A, B, C, and K the task is to find the minimum difference between any multiple of A, B, and C with K Examples: Input: A = 5, B = 4, C = 8, K = 9output: 1Explanation: Closest multiple of A, B and C greater than 9 is 10. Therefore, minimum difference is 10-9 = 1 Input: A = 6, B = 10, C = 9, K = 2Output: 4Explanation: Closest multiple of A, B and C greater than 2 is 6. Therefore, minimum difference is 6-2 = 4 Naive Approach: The task can be solved by using a for-loop to get the next multiples of A, B, and C, by keeping track of the closest multiple just greater than K Follow the below steps to solve the problem: Initialize 3 boolean variables say fa, fb, and fc to denote whether the multiples of A, B, and C becomes greater than K Start multiplying A, B, and C with cur initialized with 1 As soon as, one of the three numbers becomes greater than K, store the difference between the nearest multiple and K accordingly Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the difference between// closest multiple of A, B, C with Kvoid solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = INT_MAX; // Check whether multiples of A, B and C becomes // greater than K bool fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (1) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = min(ans, C - K); fc = true; } } cur++; } // Resultant answer cout << ans << endl;} // Driver Codeint main(){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); return 0;} // Java program for the above approachclass GFG{ // Function to find the difference between// closest multiple of A, B, C with Kstatic void solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = Integer.MAX_VALUE; // Check whether multiples of A, B and C becomes // greater than K boolean fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (true) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.min(ans, C - K); fc = true; } } cur++; } // Resultant answer System.out.print(ans +"\n");} // Driver Codepublic static void main(String[] args){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K);}} // This code is contributed by shikhasingrajput # Python Program to implement# the above approach # Function to find the difference between# closest multiple of A, B, C with Kdef solve(A, B, C, K): # Stores the minimum difference ans = 10 ** 9 # Check whether multiples of A, B and C becomes # greater than K fa = False fb = False fc = False # Start multiplication from 1 cur = 1 while (1): # Finding multiples A *= cur B *= cur C *= cur # All the multiples becomes # greater than K if (fa and fb and fb): break # Multiple of A if (not fa): # Valid multiple if (A >= K): # Minimize ans ans = min(ans, A - K) fa = True # Multiple of B if (not fb): # Valid multiple if (B >= K): # Minimize ans ans = min(ans, B - K) fb = True # Multiple of C if (not fc): # Valid multiple if (C >= K): # Minimize ans ans = min(ans, C - K) fc = True cur += 1 # Resultant answer print(ans) # Driver CodeA = 6B = 10C = 9K = 2solve(A, B, C, K) # This code is contributed by saurabh_jaiswal. // C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the difference between// closest multiple of A, B, C with Kstatic void solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = Int32.MaxValue; // Check whether multiples of A, B and C becomes // greater than K bool fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (true) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.Min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.Min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.Min(ans, C - K); fc = true; } } cur++; } // Resultant answer Console.Write(ans +"\n");} // Driver Code public static void Main() { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); }} // This code is contributed by sanjoy_62. <script> // JavaScript Program to implement // the above approach // Function to find the difference between // closest multiple of A, B, C with K function solve(A, B, C, K) { // Stores the minimum difference let ans = Number.MAX_VALUE; // Check whether multiples of A, B and C becomes // greater than K let fa = false, fb = false, fc = false; // Start multiplication from 1 let cur = 1; while (1) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.min(ans, C - K); fc = true; } } cur++; } // Resultant answer document.write(ans + '<br>'); } // Driver Code let A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); // This code is contributed by Potta Lokesh </script> 4 Time Complexity: O(min(K/A, K/B, K/C)) Auxiliary Space: O(1) Efficient Approach: Above approach can be generalized into a formula: min(⌈K/A⌉*A, ⌈K/B⌉*B, ⌈K/C⌉*C) − K. ⌈K/A⌉*A gives the nearest multiple of A just greater than K ⌈K/B⌉*B gives the nearest multiple of B just greater than K ⌈K/C⌉*C gives the nearest multiple of C just greater than K Difference of minimum of all these with K gives the desired result Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the difference between// closest multiple of A, B, C with Kvoid solve(int A, int B, int C, int K){ // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = min(fa - K, min(fc - K, fb - K)); cout << ans << endl;} // Drive codeint main(){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); return 0;} // Java program for the above approachpublic class GFG { // Function to find the difference between // closest multiple of A, B, C with K static void solve(int A, int B, int C, int K) { // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = Math.min(fa - K, Math.min(fc - K, fb - K)); System.out.println(ans); } // Drive code public static void main (String[] args) { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); } } // This code is contributed by AnkThon # Python3 program for the above approach # Function to find the difference between# closest multiple of A, B, C with Kdef solve( A, B, C, K) : # Stores the multiples of A, B, C # just greater than K # Multiple of A if ((K % A) != 0) : fa = ((K // A) + 1) * A; else : fa = (K // A) * A; # Multiple of B if ((K % B) != 0) : fb = ((K // B) + 1) * B; else : fb = (K // B) * B; # Multiple of C if ((K % C) != 0) : fc = ((K // C) + 1) * C; else : fc = (K // C) * C; # Store the resultant answer ans = min(fa - K, min(fc - K, fb - K)); print(ans); # Drive codeif __name__ == "__main__" : A = 6; B = 10; C = 9; K = 2; solve(A, B, C, K); # This code is contributed by AnkThon // C# program for the above approachusing System;public class GFG { // Function to find the difference between // closest multiple of A, B, C with K static void solve(int A, int B, int C, int K) { // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = Math.Min(fa - K, Math.Min(fc - K, fb - K)); Console.WriteLine(ans); } // Drive code public static void Main(string[] args) { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); }} // This code is contributed by ukasp. <script>// javascript program for the above approach // Function to find the difference between // closest multiple of A, B, C with K function solve(A , B , C , K) { // Stores the multiples of A, B, C // just greater than K var fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = parseInt((K / A) + 1) * A; } else { fa = parseInt(K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = parseInt((K / B) + 1) * B; } else { fb = parseInt(K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = parseInt((K / C) + 1) * C; } else { fc = parseInt(K / C) * C; } // Store the resultant answer var ans; ans = Math.min(fa - K, Math.min(fc - K, fb - K)); document.write(ans); } // Drive codevar A = 6, B = 10, C = 9, K = 2;solve(A, B, C, K); // This code is contributed by 29AjayKumar</script> 4 Time Complexity: O(1)Auxiliary Space: O(1) lokeshpotta20 shikhasingrajput _saurabh_jaiswal ankthon sanjoy_62 ukasp 29AjayKumar arorakashish0911 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Median in a stream of integers (running integers) Program to multiply two matrices Generate all permutation of a set in Python Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Newton's Divided Difference Interpolation Formula Program to print prime numbers from 1 to N. Singular Value Decomposition (SVD) Fizz Buzz Implementation Binomial Coefficient | DP-9 Program for Muller Method
[ { "code": null, "e": 25937, "s": 25909, "text": "\n24 Dec, 2021" }, { "code": null, "e": 26055, "s": 25937, "text": "Given 4 integers A, B, C, and K the task is to find the minimum difference between any multiple of A, B, and C with K" }, { "code": null, "e": 26065, "s": 26055, "text": "Examples:" }, { "code": null, "e": 26217, "s": 26065, "text": "Input: A = 5, B = 4, C = 8, K = 9output: 1Explanation: Closest multiple of A, B and C greater than 9 is 10. Therefore, minimum difference is 10-9 = 1" }, { "code": null, "e": 26366, "s": 26217, "text": "Input: A = 6, B = 10, C = 9, K = 2Output: 4Explanation: Closest multiple of A, B and C greater than 2 is 6. Therefore, minimum difference is 6-2 = 4" }, { "code": null, "e": 26573, "s": 26366, "text": "Naive Approach: The task can be solved by using a for-loop to get the next multiples of A, B, and C, by keeping track of the closest multiple just greater than K Follow the below steps to solve the problem:" }, { "code": null, "e": 26693, "s": 26573, "text": "Initialize 3 boolean variables say fa, fb, and fc to denote whether the multiples of A, B, and C becomes greater than K" }, { "code": null, "e": 26751, "s": 26693, "text": "Start multiplying A, B, and C with cur initialized with 1" }, { "code": null, "e": 26880, "s": 26751, "text": "As soon as, one of the three numbers becomes greater than K, store the difference between the nearest multiple and K accordingly" }, { "code": null, "e": 26931, "s": 26880, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26935, "s": 26931, "text": "C++" }, { "code": null, "e": 26940, "s": 26935, "text": "Java" }, { "code": null, "e": 26948, "s": 26940, "text": "Python3" }, { "code": null, "e": 26951, "s": 26948, "text": "C#" }, { "code": null, "e": 26962, "s": 26951, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the difference between// closest multiple of A, B, C with Kvoid solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = INT_MAX; // Check whether multiples of A, B and C becomes // greater than K bool fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (1) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = min(ans, C - K); fc = true; } } cur++; } // Resultant answer cout << ans << endl;} // Driver Codeint main(){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); return 0;}", "e": 28408, "s": 26962, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function to find the difference between// closest multiple of A, B, C with Kstatic void solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = Integer.MAX_VALUE; // Check whether multiples of A, B and C becomes // greater than K boolean fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (true) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.min(ans, C - K); fc = true; } } cur++; } // Resultant answer System.out.print(ans +\"\\n\");} // Driver Codepublic static void main(String[] args){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K);}} // This code is contributed by shikhasingrajput", "e": 29931, "s": 28408, "text": null }, { "code": "# Python Program to implement# the above approach # Function to find the difference between# closest multiple of A, B, C with Kdef solve(A, B, C, K): # Stores the minimum difference ans = 10 ** 9 # Check whether multiples of A, B and C becomes # greater than K fa = False fb = False fc = False # Start multiplication from 1 cur = 1 while (1): # Finding multiples A *= cur B *= cur C *= cur # All the multiples becomes # greater than K if (fa and fb and fb): break # Multiple of A if (not fa): # Valid multiple if (A >= K): # Minimize ans ans = min(ans, A - K) fa = True # Multiple of B if (not fb): # Valid multiple if (B >= K): # Minimize ans ans = min(ans, B - K) fb = True # Multiple of C if (not fc): # Valid multiple if (C >= K): # Minimize ans ans = min(ans, C - K) fc = True cur += 1 # Resultant answer print(ans) # Driver CodeA = 6B = 10C = 9K = 2solve(A, B, C, K) # This code is contributed by saurabh_jaiswal.", "e": 31214, "s": 29931, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG { // Function to find the difference between// closest multiple of A, B, C with Kstatic void solve(int A, int B, int C, int K){ // Stores the minimum difference int ans = Int32.MaxValue; // Check whether multiples of A, B and C becomes // greater than K bool fa = false, fb = false, fc = false; // Start multiplication from 1 int cur = 1; while (true) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.Min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.Min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.Min(ans, C - K); fc = true; } } cur++; } // Resultant answer Console.Write(ans +\"\\n\");} // Driver Code public static void Main() { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); }} // This code is contributed by sanjoy_62.", "e": 32779, "s": 31214, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to find the difference between // closest multiple of A, B, C with K function solve(A, B, C, K) { // Stores the minimum difference let ans = Number.MAX_VALUE; // Check whether multiples of A, B and C becomes // greater than K let fa = false, fb = false, fc = false; // Start multiplication from 1 let cur = 1; while (1) { // Finding multiples A *= cur; B *= cur; C *= cur; // All the multiples becomes // greater than K if (fa && fb && fb) break; // Multiple of A if (!fa) { // Valid multiple if (A >= K) { // Minimize ans ans = Math.min(ans, A - K); fa = true; } } // Multiple of B if (!fb) { // Valid multiple if (B >= K) { // Minimize ans ans = Math.min(ans, B - K); fb = true; } } // Multiple of C if (!fc) { // Valid multiple if (C >= K) { // Minimize ans ans = Math.min(ans, C - K); fc = true; } } cur++; } // Resultant answer document.write(ans + '<br>'); } // Driver Code let A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); // This code is contributed by Potta Lokesh </script>", "e": 34705, "s": 32779, "text": null }, { "code": null, "e": 34710, "s": 34708, "text": "4" }, { "code": null, "e": 34773, "s": 34712, "text": "Time Complexity: O(min(K/A, K/B, K/C)) Auxiliary Space: O(1)" }, { "code": null, "e": 34881, "s": 34775, "text": "Efficient Approach: Above approach can be generalized into a formula: min(⌈K/A⌉*A, ⌈K/B⌉*B, ⌈K/C⌉*C) − K." }, { "code": null, "e": 34943, "s": 34883, "text": "⌈K/A⌉*A gives the nearest multiple of A just greater than K" }, { "code": null, "e": 35003, "s": 34943, "text": "⌈K/B⌉*B gives the nearest multiple of B just greater than K" }, { "code": null, "e": 35063, "s": 35003, "text": "⌈K/C⌉*C gives the nearest multiple of C just greater than K" }, { "code": null, "e": 35130, "s": 35063, "text": "Difference of minimum of all these with K gives the desired result" }, { "code": null, "e": 35183, "s": 35132, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35189, "s": 35185, "text": "C++" }, { "code": null, "e": 35194, "s": 35189, "text": "Java" }, { "code": null, "e": 35202, "s": 35194, "text": "Python3" }, { "code": null, "e": 35205, "s": 35202, "text": "C#" }, { "code": null, "e": 35216, "s": 35205, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the difference between// closest multiple of A, B, C with Kvoid solve(int A, int B, int C, int K){ // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = min(fa - K, min(fc - K, fb - K)); cout << ans << endl;} // Drive codeint main(){ int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); return 0;}", "e": 36074, "s": 35216, "text": null }, { "code": "// Java program for the above approachpublic class GFG { // Function to find the difference between // closest multiple of A, B, C with K static void solve(int A, int B, int C, int K) { // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = Math.min(fa - K, Math.min(fc - K, fb - K)); System.out.println(ans); } // Drive code public static void main (String[] args) { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); } } // This code is contributed by AnkThon", "e": 37180, "s": 36074, "text": null }, { "code": "# Python3 program for the above approach # Function to find the difference between# closest multiple of A, B, C with Kdef solve( A, B, C, K) : # Stores the multiples of A, B, C # just greater than K # Multiple of A if ((K % A) != 0) : fa = ((K // A) + 1) * A; else : fa = (K // A) * A; # Multiple of B if ((K % B) != 0) : fb = ((K // B) + 1) * B; else : fb = (K // B) * B; # Multiple of C if ((K % C) != 0) : fc = ((K // C) + 1) * C; else : fc = (K // C) * C; # Store the resultant answer ans = min(fa - K, min(fc - K, fb - K)); print(ans); # Drive codeif __name__ == \"__main__\" : A = 6; B = 10; C = 9; K = 2; solve(A, B, C, K); # This code is contributed by AnkThon", "e": 37959, "s": 37180, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG { // Function to find the difference between // closest multiple of A, B, C with K static void solve(int A, int B, int C, int K) { // Stores the multiples of A, B, C // just greater than K int fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = ((K / A) + 1) * A; } else { fa = (K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = ((K / B) + 1) * B; } else { fb = (K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = ((K / C) + 1) * C; } else { fc = (K / C) * C; } // Store the resultant answer int ans; ans = Math.Min(fa - K, Math.Min(fc - K, fb - K)); Console.WriteLine(ans); } // Drive code public static void Main(string[] args) { int A = 6, B = 10, C = 9, K = 2; solve(A, B, C, K); }} // This code is contributed by ukasp.", "e": 39034, "s": 37959, "text": null }, { "code": "<script>// javascript program for the above approach // Function to find the difference between // closest multiple of A, B, C with K function solve(A , B , C , K) { // Stores the multiples of A, B, C // just greater than K var fa, fb, fc; // Multiple of A if ((K % A) != 0) { fa = parseInt((K / A) + 1) * A; } else { fa = parseInt(K / A) * A; } // Multiple of B if ((K % B) != 0) { fb = parseInt((K / B) + 1) * B; } else { fb = parseInt(K / B) * B; } // Multiple of C if ((K % C) != 0) { fc = parseInt((K / C) + 1) * C; } else { fc = parseInt(K / C) * C; } // Store the resultant answer var ans; ans = Math.min(fa - K, Math.min(fc - K, fb - K)); document.write(ans); } // Drive codevar A = 6, B = 10, C = 9, K = 2;solve(A, B, C, K); // This code is contributed by 29AjayKumar</script>", "e": 40101, "s": 39034, "text": null }, { "code": null, "e": 40106, "s": 40104, "text": "4" }, { "code": null, "e": 40151, "s": 40108, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 40167, "s": 40153, "text": "lokeshpotta20" }, { "code": null, "e": 40184, "s": 40167, "text": "shikhasingrajput" }, { "code": null, "e": 40201, "s": 40184, "text": "_saurabh_jaiswal" }, { "code": null, "e": 40209, "s": 40201, "text": "ankthon" }, { "code": null, "e": 40219, "s": 40209, "text": "sanjoy_62" }, { "code": null, "e": 40225, "s": 40219, "text": "ukasp" }, { "code": null, "e": 40237, "s": 40225, "text": "29AjayKumar" }, { "code": null, "e": 40254, "s": 40237, "text": "arorakashish0911" }, { "code": null, "e": 40267, "s": 40254, "text": "Mathematical" }, { "code": null, "e": 40280, "s": 40267, "text": "Mathematical" }, { "code": null, "e": 40378, "s": 40280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40428, "s": 40378, "text": "Median in a stream of integers (running integers)" }, { "code": null, "e": 40461, "s": 40428, "text": "Program to multiply two matrices" }, { "code": null, "e": 40505, "s": 40461, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 40558, "s": 40505, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 40608, "s": 40558, "text": "Newton's Divided Difference Interpolation Formula" }, { "code": null, "e": 40652, "s": 40608, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 40687, "s": 40652, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 40712, "s": 40687, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 40740, "s": 40712, "text": "Binomial Coefficient | DP-9" } ]
std::move in Utility in C++ | Move Semantics, Move Constructors and Move Assignment Operators - GeeksforGeeks
11 Feb, 2022 Prerequisites: lvalue referencervalue referenceCopy Semantics (Copy Constructor) lvalue reference rvalue reference Copy Semantics (Copy Constructor) References: In C++ there are two types of references- lvalue reference:An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.Simply, a variable or object that has a name and memory address.It uses one ampersand (&).rvalue reference:An rvalue is an expression that will appear only on the right-hand side of an assignment.A variable or object has only a memory address (temporary objects).It uses two ampersands (&&). lvalue reference:An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.Simply, a variable or object that has a name and memory address.It uses one ampersand (&). An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment. Simply, a variable or object that has a name and memory address. It uses one ampersand (&). rvalue reference:An rvalue is an expression that will appear only on the right-hand side of an assignment.A variable or object has only a memory address (temporary objects).It uses two ampersands (&&). An rvalue is an expression that will appear only on the right-hand side of an assignment. A variable or object has only a memory address (temporary objects). It uses two ampersands (&&). Move Constructor And Semantics: The move constructor was introduced in C++11. The need or purpose of a move constructor is to steal or move as many resources as it can from the source (original) object, as fast as possible, because the source does not need to have a meaningful value anymore, and/or because it is going to be destroyed in a moment anyway. So that one can avoid unnecessarily creating copies of an object and make efficient use of the resources While one can steal the resources, but one must leave the source (original) object in a valid state where it can be correctly destroyed. Move constructors typically “steal” the resource of the source (original) object rather than making several copies of them, and leaves the source object in a “valid but unspecified state”. The copy constructor uses the lvalue references which are marked with one ampersand (&) while the move constructor uses the rvalue references are marked with two ampersands (&&). std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another. std::move() is defined in the <utility> header. Syntax: template< class T > typename std::remove_reference<T>::type&& move(T&& t) noexcept; (since C++11)(until C++14) template< class T > constexpr std::remove_reference_t<T>&& move(T&& t) noexcept (since C++14) Example: Below is the C++ program to show what happens without using move semantics i.e. before C++11. C++14 // C++ program to implement// the above approach // for std::string#include <string> // for std::cout#include <iostream> // for EXIT_SUCCESS macro#include <cstdlib> // for std::vector#include <vector> // for std::move()#include <utility> // Declarationstd::vector<std::string> createAndInsert(); // Driver codeint main(){ // Constructing an empty vector // of strings std::vector<std::string> vecString; // calling createAndInsert() and // initializing the local vecString // object vecString = createAndInsert(); // Printing content of the vector for (const auto& s : vecString) { std::cout << s << '\n'; } return EXIT_SUCCESS;} // Definitionstd::vector<std::string> createAndInsert(){ // constructing a vector of // strings with an size of // 3 elements std::vector<std::string> vec; vec.reserve(3); // constructing & initializing // a string with "Hello" std::string str("Hello"); // Inserting a copy of string // object vec.push_back(str); // Inserting a copy of an // temporary string object vec.push_back(str + str); // Again inserting a copy of // string object vec.push_back(std::move(str)); // Finally, returning the local // vector return vec;} Hello HelloHello Hello Explanation: Assuming the program is compiled and executed using a compiler that doesn’t support move semantics. In the main() function, 1. std::vector<std::string> vecString;- An empty vector is created with no elements in it. 2. vecString = createAndInsert();- The createAndInsert() function is called.3. In createAndInsert() function- std::vector<std::string> vec;- Another new empty vector named as vec is created. vec.reserve(3);- Reserving the size of 3 elements. std::string str(“Hello”);- A string named as str initialized with a “Hello”. vec.push_back( str );- A string is passed by value into the vector vec. Therefore a (deep) copy of str will be created and inserted into the vec by calling a copy constructor of the String class. vec.push_back( str + str );- This is a three-stage process-A temporary object will be created (str + str) with its own separate memory.This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created.As of now, the temporary object is no longer needed hence it will be destroyed. A temporary object will be created (str + str) with its own separate memory.This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created.As of now, the temporary object is no longer needed hence it will be destroyed. A temporary object will be created (str + str) with its own separate memory. This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created. As of now, the temporary object is no longer needed hence it will be destroyed. Note: Here, we unnecessarily allocate & deallocate the memory of the temporary string object. which can be optimized (improved) further just by moving the data from the source object. vec.push_back( str );- The same process as of Line no. 5 will be carried out. Remember at this point the str string object will be last used. return vec;- This is at the end of the createAndInsert() function-Firstly, the string object str will be destroyed because the scope is left where it is declared.Secondly, a local vector of string i.e vec is returned. As the return type of the function is not by a reference. Hence, a deep copy of the whole vector will be created by allocating at a separate memory location and then destroys the local vec object because the scope is left where it is declared.Finally, the copy of the vector of strings will be returned to the caller main() function. Firstly, the string object str will be destroyed because the scope is left where it is declared. Secondly, a local vector of string i.e vec is returned. As the return type of the function is not by a reference. Hence, a deep copy of the whole vector will be created by allocating at a separate memory location and then destroys the local vec object because the scope is left where it is declared. Finally, the copy of the vector of strings will be returned to the caller main() function. At the last, after returning to the caller main() function, simply printing the elements of the local vecString vector. Example: Below is the C++ program to implement the above concept using move semantics i.e. since C++11 and later. C++14 // C++ program to implement// the above approach // for std::string#include <string> // for std::cout#include <iostream> // for EXIT_SUCCESS macro#include <cstdlib> // for std::vector#include <vector> // for std::move()#include <utility> // Declarationstd::vector<std::string> createAndInsert(); // Driver codeint main(){ // Constructing an empty vector // of strings std::vector<std::string> vecString; // calling createAndInsert() and // initializing the local vecString // object vecString = createAndInsert(); // Printing content of the vector for (const auto& s : vecString) { std::cout << s << '\n'; } return EXIT_SUCCESS;} // Definitionstd::vector<std::string> createAndInsert(){ // constructing a vector of // strings with an size of // 3 elements std::vector<std::string> vec; vec.reserve(3); // constructing & initializing // a string with "Hello" std::string str("Hello"); // Inserting a copy of string // object vec.push_back(str); // Inserting a copy of an // temporary string object vec.push_back(str + str); // Again inserting a copy of // string object vec.push_back(std::move(str)); // Finally, returning the local // vector return vec;} Hello HelloHello Hello Explanation: Here, in order to use the move semantics. The compiler must support the C++11 standards or above. The story of execution for the main() function and createAndInsert() function remains the same till the line vec.push_back( str ); A question may arise why the temporary object is not moved to vector vec using std::move(). The reason behind it is the push_back() method of the vector. Since C++11 the push_back() method has been provided with its new overloaded version. Syntax: constexpr void push_back(const T& value); (since C++20)void push_back(T&& value); (since C++11) (until C++20)void push_back(const T& value); (until C++20)constexpr void push_back(T&& value); (since C++20) constexpr void push_back(const T& value); (since C++20) void push_back(T&& value); (since C++11) (until C++20) void push_back(const T& value); (until C++20) constexpr void push_back(T&& value); (since C++20) vec.push_back(str + str);-A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required.After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data.Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics. A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required.After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data.Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics. A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required. After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data. Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics. vec.push_back(std::move(str));- Here the compiler is explicitly hinted that “object is no longer needed” named as str (lvalue reference) with the help of std::move() function by converting the lvalue reference into rvalue reference and the resource of the str will be moved to the vector. Then the state of str becomes a “valid but unspecified state”. This doesn’t matter to us because for the last time we are going to use and soon be destroyed in a moment anyway. Lastly, return the local vector of string called vec to its caller. In the end, returned to the caller main() function, and simply printing the elements of the local vecString vector. A question may arise while returning the vec object to its caller. As it is not required anymore and also a whole temporary object of a vector is going to be created and also local vector vec will be destroyed, then why std::move() is not used to steal the value and return it. Its answer is simple and obvious, there is optimization at the compiler level known as (Named) Return Value Object, more popularly known as RVO. Some Fallback Of Move Semantics: Calling a std::move() on a const object usually has no effect.It doesn’t make any sense to steal or move the resources of a const object.See constObjectCallFunc() function in the below programCopy semantics is used as a fallback for move semantics if and only if copy semantics is supported.See baz() function in the below programIf there is no implementation taking the rvalue reference as an argument the ordinary const lvalue reference will be used.See baz() function in the below programIf a function or method is missing with rvalue reference as argument & const lvalue reference as an argument. Then the compile-time error will be generated.See bar() function in the below program Calling a std::move() on a const object usually has no effect.It doesn’t make any sense to steal or move the resources of a const object.See constObjectCallFunc() function in the below program It doesn’t make any sense to steal or move the resources of a const object. See constObjectCallFunc() function in the below program Copy semantics is used as a fallback for move semantics if and only if copy semantics is supported.See baz() function in the below program See baz() function in the below program If there is no implementation taking the rvalue reference as an argument the ordinary const lvalue reference will be used.See baz() function in the below program See baz() function in the below program If a function or method is missing with rvalue reference as argument & const lvalue reference as an argument. Then the compile-time error will be generated.See bar() function in the below program See bar() function in the below program Note: The foo() function have all necessary types of arguments. Below is the C++ program to implement all the above concepts- C++14 // C++ program to implement// the above concept // for std::cout & std::endl#include <iostream> // for std::move()#include <utility> // for std::string#include <string> // for EXIT_SUCCESS macro#include <cstdlib> // foo() taking a non-const lvalue// reference argumentvoid foo(std::string& str); // foo() taking a const lvalue// reference argumentvoid foo(const std::string& str); // foo() taking a rvalue// reference argumentvoid foo(std::string&& str); // baz() taking a const lvalue// reference argumentvoid baz(const std::string& str); // baz() taking a non-const lvalue// reference argumentvoid baz(std::string& str); // bar() taking a non-const lvalue// reference argumentvoid bar(std::string& str); // constObjectCallFunc() taking a// rvalue reference argumentvoid constObjectCallFunc(std::string&& str); // Driver codeint main(){ // foo(std::string&& str) will // be called foo(std::string("Hello")); std::string goodBye("Good Bye!"); // foo(std::string& str) will be called foo(goodBye); // foo(std::string&& str) will be called foo(std::move(goodBye + " using std::move()")); std::cout << "\n\n\n"; // move semantics fallback // baz(const std::string& str) will be called baz(std::string("This is temporary string object")); // baz(const std::string& str) will be called baz(std::move(std::string( "This is temporary string object using std::move()"))); std::cout << "\n\n\n"; std::string failToCall("This will fail to call"); /* Reasons to fail bar() call - 1. No rvalue reference implementation available // First Preference 2. No const lvalue reference implementation available // Second Preference 3. Finally fails to invoke bar() function */ // bar(std::move(failToCall)); // Error : check the error message for more // better understanding std::cout << "\n\n\n"; const std::string constObj( "Calling a std::move() on a const object usually has no effect."); // constObjectCallFunc(std::move(constObj)); // Error : because of const qualifier // It doesn't make any sense to steal or // move the resources of a const object return EXIT_SUCCESS;} void foo(const std::string& str){ // do something std::cout << "foo(const std::string& str) : " << "\n\t" << str << std::endl;} void foo(std::string& str){ // do something std::cout << "foo(std::string& str) : " << "\n\t" << str << std::endl;} void foo(std::string&& str){ // do something std::cout << "foo(std::string&& str) : " << "\n\t" << str << std::endl;} void baz(const std::string& str){ // do something std::cout << "baz(const std::string& str) : " << "\n\t" << str << std::endl;} void baz(std::string& str){ // do something std::cout << "baz(std::string& str) : " << "\n\t" << str << std::endl;} void bar(std::string& str){ // do something std::cout << "bar(std::string&& str) : " << "\n\t" << str << std::endl;} void constObjectCallFunc(std::string&& str){ // do something std::cout << "constObjectCallFunc(std::string&& str) : " << "\n\t" << str << std::endl;} foo(std::string&& str) : Hello foo(std::string& str) : Good Bye! foo(std::string&& str) : Good Bye! using std::move() baz(const std::string& str) : This is temporary string object baz(const std::string& str) : This is temporary string object using std::move() Summary: Move semantics allows us to optimize the copying of objects, where we do not need the worth. It is often used implicitly (for unnamed temporary objects or local return values) or explicitly with std::move(). std::move() means “no longer need this value”. An object marked with std::move() is never partially destroyed. i.e. The destructor will be called to destroy the object properly. simmytarika5 mayurkedari16 surindertarika1234 ruhelaa48 openberry Blogathon-2021 Constructors References STL Blogathon C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create a Table With Multiple Foreign Keys in SQL? How to Import JSON Data into SQL Server? Stratified Sampling in Pandas How to Install Tkinter in Windows? Python program to convert XML to Dictionary Vector in C++ STL Arrays in C/C++ Initialize a vector in C++ (6 different ways) Inheritance in C++ Map in C++ Standard Template Library (STL)
[ { "code": null, "e": 26097, "s": 26069, "text": "\n11 Feb, 2022" }, { "code": null, "e": 26112, "s": 26097, "text": "Prerequisites:" }, { "code": null, "e": 26178, "s": 26112, "text": "lvalue referencervalue referenceCopy Semantics (Copy Constructor)" }, { "code": null, "e": 26195, "s": 26178, "text": "lvalue reference" }, { "code": null, "e": 26212, "s": 26195, "text": "rvalue reference" }, { "code": null, "e": 26246, "s": 26212, "text": "Copy Semantics (Copy Constructor)" }, { "code": null, "e": 26258, "s": 26246, "text": "References:" }, { "code": null, "e": 26300, "s": 26258, "text": "In C++ there are two types of references-" }, { "code": null, "e": 26718, "s": 26300, "text": "lvalue reference:An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.Simply, a variable or object that has a name and memory address.It uses one ampersand (&).rvalue reference:An rvalue is an expression that will appear only on the right-hand side of an assignment.A variable or object has only a memory address (temporary objects).It uses two ampersands (&&)." }, { "code": null, "e": 26935, "s": 26718, "text": "lvalue reference:An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment.Simply, a variable or object that has a name and memory address.It uses one ampersand (&)." }, { "code": null, "e": 27045, "s": 26935, "text": "An lvalue is an expression that will appear on the left-hand side or on the right-hand side of an assignment." }, { "code": null, "e": 27110, "s": 27045, "text": "Simply, a variable or object that has a name and memory address." }, { "code": null, "e": 27137, "s": 27110, "text": "It uses one ampersand (&)." }, { "code": null, "e": 27339, "s": 27137, "text": "rvalue reference:An rvalue is an expression that will appear only on the right-hand side of an assignment.A variable or object has only a memory address (temporary objects).It uses two ampersands (&&)." }, { "code": null, "e": 27429, "s": 27339, "text": "An rvalue is an expression that will appear only on the right-hand side of an assignment." }, { "code": null, "e": 27497, "s": 27429, "text": "A variable or object has only a memory address (temporary objects)." }, { "code": null, "e": 27526, "s": 27497, "text": "It uses two ampersands (&&)." }, { "code": null, "e": 27558, "s": 27526, "text": "Move Constructor And Semantics:" }, { "code": null, "e": 27987, "s": 27558, "text": "The move constructor was introduced in C++11. The need or purpose of a move constructor is to steal or move as many resources as it can from the source (original) object, as fast as possible, because the source does not need to have a meaningful value anymore, and/or because it is going to be destroyed in a moment anyway. So that one can avoid unnecessarily creating copies of an object and make efficient use of the resources" }, { "code": null, "e": 28124, "s": 27987, "text": "While one can steal the resources, but one must leave the source (original) object in a valid state where it can be correctly destroyed." }, { "code": null, "e": 28313, "s": 28124, "text": "Move constructors typically “steal” the resource of the source (original) object rather than making several copies of them, and leaves the source object in a “valid but unspecified state”." }, { "code": null, "e": 28492, "s": 28313, "text": "The copy constructor uses the lvalue references which are marked with one ampersand (&) while the move constructor uses the rvalue references are marked with two ampersands (&&)." }, { "code": null, "e": 28698, "s": 28492, "text": "std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another." }, { "code": null, "e": 28746, "s": 28698, "text": "std::move() is defined in the <utility> header." }, { "code": null, "e": 28754, "s": 28746, "text": "Syntax:" }, { "code": null, "e": 28881, "s": 28754, "text": "template< class T > typename std::remove_reference<T>::type&& move(T&& t) noexcept; (since C++11)(until C++14)" }, { "code": null, "e": 28997, "s": 28881, "text": "template< class T > constexpr std::remove_reference_t<T>&& move(T&& t) noexcept (since C++14)" }, { "code": null, "e": 29100, "s": 28997, "text": "Example: Below is the C++ program to show what happens without using move semantics i.e. before C++11." }, { "code": null, "e": 29106, "s": 29100, "text": "C++14" }, { "code": "// C++ program to implement// the above approach // for std::string#include <string> // for std::cout#include <iostream> // for EXIT_SUCCESS macro#include <cstdlib> // for std::vector#include <vector> // for std::move()#include <utility> // Declarationstd::vector<std::string> createAndInsert(); // Driver codeint main(){ // Constructing an empty vector // of strings std::vector<std::string> vecString; // calling createAndInsert() and // initializing the local vecString // object vecString = createAndInsert(); // Printing content of the vector for (const auto& s : vecString) { std::cout << s << '\\n'; } return EXIT_SUCCESS;} // Definitionstd::vector<std::string> createAndInsert(){ // constructing a vector of // strings with an size of // 3 elements std::vector<std::string> vec; vec.reserve(3); // constructing & initializing // a string with \"Hello\" std::string str(\"Hello\"); // Inserting a copy of string // object vec.push_back(str); // Inserting a copy of an // temporary string object vec.push_back(str + str); // Again inserting a copy of // string object vec.push_back(std::move(str)); // Finally, returning the local // vector return vec;}", "e": 30369, "s": 29106, "text": null }, { "code": null, "e": 30392, "s": 30369, "text": "Hello\nHelloHello\nHello" }, { "code": null, "e": 30405, "s": 30392, "text": "Explanation:" }, { "code": null, "e": 30531, "s": 30405, "text": "Assuming the program is compiled and executed using a compiler that doesn’t support move semantics. In the main() function, " }, { "code": null, "e": 30732, "s": 30531, "text": "1. std::vector<std::string> vecString;- An empty vector is created with no elements in it. 2. vecString = createAndInsert();- The createAndInsert() function is called.3. In createAndInsert() function-" }, { "code": null, "e": 30813, "s": 30732, "text": "std::vector<std::string> vec;- Another new empty vector named as vec is created." }, { "code": null, "e": 30864, "s": 30813, "text": "vec.reserve(3);- Reserving the size of 3 elements." }, { "code": null, "e": 30941, "s": 30864, "text": "std::string str(“Hello”);- A string named as str initialized with a “Hello”." }, { "code": null, "e": 31137, "s": 30941, "text": "vec.push_back( str );- A string is passed by value into the vector vec. Therefore a (deep) copy of str will be created and inserted into the vec by calling a copy constructor of the String class." }, { "code": null, "e": 31505, "s": 31137, "text": "vec.push_back( str + str );- This is a three-stage process-A temporary object will be created (str + str) with its own separate memory.This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created.As of now, the temporary object is no longer needed hence it will be destroyed." }, { "code": null, "e": 31814, "s": 31505, "text": "A temporary object will be created (str + str) with its own separate memory.This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created.As of now, the temporary object is no longer needed hence it will be destroyed." }, { "code": null, "e": 31891, "s": 31814, "text": "A temporary object will be created (str + str) with its own separate memory." }, { "code": null, "e": 32045, "s": 31891, "text": "This temporary object is inserted into vector vec which is passed by value again means that a (deep) copy of the temporary string object will be created." }, { "code": null, "e": 32125, "s": 32045, "text": "As of now, the temporary object is no longer needed hence it will be destroyed." }, { "code": null, "e": 32310, "s": 32125, "text": "Note: Here, we unnecessarily allocate & deallocate the memory of the temporary string object. which can be optimized (improved) further just by moving the data from the source object. " }, { "code": null, "e": 32452, "s": 32310, "text": "vec.push_back( str );- The same process as of Line no. 5 will be carried out. Remember at this point the str string object will be last used." }, { "code": null, "e": 33004, "s": 32452, "text": "return vec;- This is at the end of the createAndInsert() function-Firstly, the string object str will be destroyed because the scope is left where it is declared.Secondly, a local vector of string i.e vec is returned. As the return type of the function is not by a reference. Hence, a deep copy of the whole vector will be created by allocating at a separate memory location and then destroys the local vec object because the scope is left where it is declared.Finally, the copy of the vector of strings will be returned to the caller main() function." }, { "code": null, "e": 33101, "s": 33004, "text": "Firstly, the string object str will be destroyed because the scope is left where it is declared." }, { "code": null, "e": 33401, "s": 33101, "text": "Secondly, a local vector of string i.e vec is returned. As the return type of the function is not by a reference. Hence, a deep copy of the whole vector will be created by allocating at a separate memory location and then destroys the local vec object because the scope is left where it is declared." }, { "code": null, "e": 33492, "s": 33401, "text": "Finally, the copy of the vector of strings will be returned to the caller main() function." }, { "code": null, "e": 33612, "s": 33492, "text": "At the last, after returning to the caller main() function, simply printing the elements of the local vecString vector." }, { "code": null, "e": 33727, "s": 33612, "text": "Example: Below is the C++ program to implement the above concept using move semantics i.e. since C++11 and later. " }, { "code": null, "e": 33733, "s": 33727, "text": "C++14" }, { "code": "// C++ program to implement// the above approach // for std::string#include <string> // for std::cout#include <iostream> // for EXIT_SUCCESS macro#include <cstdlib> // for std::vector#include <vector> // for std::move()#include <utility> // Declarationstd::vector<std::string> createAndInsert(); // Driver codeint main(){ // Constructing an empty vector // of strings std::vector<std::string> vecString; // calling createAndInsert() and // initializing the local vecString // object vecString = createAndInsert(); // Printing content of the vector for (const auto& s : vecString) { std::cout << s << '\\n'; } return EXIT_SUCCESS;} // Definitionstd::vector<std::string> createAndInsert(){ // constructing a vector of // strings with an size of // 3 elements std::vector<std::string> vec; vec.reserve(3); // constructing & initializing // a string with \"Hello\" std::string str(\"Hello\"); // Inserting a copy of string // object vec.push_back(str); // Inserting a copy of an // temporary string object vec.push_back(str + str); // Again inserting a copy of // string object vec.push_back(std::move(str)); // Finally, returning the local // vector return vec;}", "e": 34996, "s": 33733, "text": null }, { "code": null, "e": 35019, "s": 34996, "text": "Hello\nHelloHello\nHello" }, { "code": null, "e": 35032, "s": 35019, "text": "Explanation:" }, { "code": null, "e": 35261, "s": 35032, "text": "Here, in order to use the move semantics. The compiler must support the C++11 standards or above. The story of execution for the main() function and createAndInsert() function remains the same till the line vec.push_back( str );" }, { "code": null, "e": 35501, "s": 35261, "text": "A question may arise why the temporary object is not moved to vector vec using std::move(). The reason behind it is the push_back() method of the vector. Since C++11 the push_back() method has been provided with its new overloaded version." }, { "code": null, "e": 35510, "s": 35501, "text": "Syntax: " }, { "code": null, "e": 35915, "s": 35510, "text": "constexpr void push_back(const T& value); (since C++20)void push_back(T&& value); (since C++11) (until C++20)void push_back(const T& value); (until C++20)constexpr void push_back(T&& value); (since C++20)" }, { "code": null, "e": 36010, "s": 35915, "text": "constexpr void push_back(const T& value); (since C++20)" }, { "code": null, "e": 36126, "s": 36010, "text": "void push_back(T&& value); (since C++11) (until C++20)" }, { "code": null, "e": 36227, "s": 36126, "text": "void push_back(const T& value); (until C++20)" }, { "code": null, "e": 36323, "s": 36227, "text": "constexpr void push_back(T&& value); (since C++20)" }, { "code": null, "e": 37109, "s": 36323, "text": "vec.push_back(str + str);-A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required.After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data.Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics." }, { "code": null, "e": 37869, "s": 37109, "text": "A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required.After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data.Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics." }, { "code": null, "e": 38180, "s": 37869, "text": "A temporary object will be created (str + str) with its own separate memory and will make a call to overloaded push_back() method (version 2nd or 4th depends on the version of C++) which will steal (or moved) the data from the temporary source object (str + str) to the vector vec as it is no longer required." }, { "code": null, "e": 38415, "s": 38180, "text": "After performing the move the temporary object gets destroyed. Thus rather than calling the copy constructor (copy semantics), it is optimized just by copying the size of the string and manipulating pointers to the memory of the data." }, { "code": null, "e": 38631, "s": 38415, "text": "Here, the important point to note is that we make use of the memory which will soon no longer owns its memory. In another word, we somehow optimized it. That’s all because of the rvalue reference and move semantics." }, { "code": null, "e": 39097, "s": 38631, "text": "vec.push_back(std::move(str));- Here the compiler is explicitly hinted that “object is no longer needed” named as str (lvalue reference) with the help of std::move() function by converting the lvalue reference into rvalue reference and the resource of the str will be moved to the vector. Then the state of str becomes a “valid but unspecified state”. This doesn’t matter to us because for the last time we are going to use and soon be destroyed in a moment anyway." }, { "code": null, "e": 39165, "s": 39097, "text": "Lastly, return the local vector of string called vec to its caller." }, { "code": null, "e": 39281, "s": 39165, "text": "In the end, returned to the caller main() function, and simply printing the elements of the local vecString vector." }, { "code": null, "e": 39705, "s": 39281, "text": "A question may arise while returning the vec object to its caller. As it is not required anymore and also a whole temporary object of a vector is going to be created and also local vector vec will be destroyed, then why std::move() is not used to steal the value and return it. Its answer is simple and obvious, there is optimization at the compiler level known as (Named) Return Value Object, more popularly known as RVO. " }, { "code": null, "e": 39739, "s": 39705, "text": "Some Fallback Of Move Semantics: " }, { "code": null, "e": 40426, "s": 39739, "text": "Calling a std::move() on a const object usually has no effect.It doesn’t make any sense to steal or move the resources of a const object.See constObjectCallFunc() function in the below programCopy semantics is used as a fallback for move semantics if and only if copy semantics is supported.See baz() function in the below programIf there is no implementation taking the rvalue reference as an argument the ordinary const lvalue reference will be used.See baz() function in the below programIf a function or method is missing with rvalue reference as argument & const lvalue reference as an argument. Then the compile-time error will be generated.See bar() function in the below program" }, { "code": null, "e": 40619, "s": 40426, "text": "Calling a std::move() on a const object usually has no effect.It doesn’t make any sense to steal or move the resources of a const object.See constObjectCallFunc() function in the below program" }, { "code": null, "e": 40695, "s": 40619, "text": "It doesn’t make any sense to steal or move the resources of a const object." }, { "code": null, "e": 40751, "s": 40695, "text": "See constObjectCallFunc() function in the below program" }, { "code": null, "e": 40890, "s": 40751, "text": "Copy semantics is used as a fallback for move semantics if and only if copy semantics is supported.See baz() function in the below program" }, { "code": null, "e": 40930, "s": 40890, "text": "See baz() function in the below program" }, { "code": null, "e": 41092, "s": 40930, "text": "If there is no implementation taking the rvalue reference as an argument the ordinary const lvalue reference will be used.See baz() function in the below program" }, { "code": null, "e": 41132, "s": 41092, "text": "See baz() function in the below program" }, { "code": null, "e": 41328, "s": 41132, "text": "If a function or method is missing with rvalue reference as argument & const lvalue reference as an argument. Then the compile-time error will be generated.See bar() function in the below program" }, { "code": null, "e": 41368, "s": 41328, "text": "See bar() function in the below program" }, { "code": null, "e": 41432, "s": 41368, "text": "Note: The foo() function have all necessary types of arguments." }, { "code": null, "e": 41495, "s": 41432, "text": "Below is the C++ program to implement all the above concepts- " }, { "code": null, "e": 41501, "s": 41495, "text": "C++14" }, { "code": "// C++ program to implement// the above concept // for std::cout & std::endl#include <iostream> // for std::move()#include <utility> // for std::string#include <string> // for EXIT_SUCCESS macro#include <cstdlib> // foo() taking a non-const lvalue// reference argumentvoid foo(std::string& str); // foo() taking a const lvalue// reference argumentvoid foo(const std::string& str); // foo() taking a rvalue// reference argumentvoid foo(std::string&& str); // baz() taking a const lvalue// reference argumentvoid baz(const std::string& str); // baz() taking a non-const lvalue// reference argumentvoid baz(std::string& str); // bar() taking a non-const lvalue// reference argumentvoid bar(std::string& str); // constObjectCallFunc() taking a// rvalue reference argumentvoid constObjectCallFunc(std::string&& str); // Driver codeint main(){ // foo(std::string&& str) will // be called foo(std::string(\"Hello\")); std::string goodBye(\"Good Bye!\"); // foo(std::string& str) will be called foo(goodBye); // foo(std::string&& str) will be called foo(std::move(goodBye + \" using std::move()\")); std::cout << \"\\n\\n\\n\"; // move semantics fallback // baz(const std::string& str) will be called baz(std::string(\"This is temporary string object\")); // baz(const std::string& str) will be called baz(std::move(std::string( \"This is temporary string object using std::move()\"))); std::cout << \"\\n\\n\\n\"; std::string failToCall(\"This will fail to call\"); /* Reasons to fail bar() call - 1. No rvalue reference implementation available // First Preference 2. No const lvalue reference implementation available // Second Preference 3. Finally fails to invoke bar() function */ // bar(std::move(failToCall)); // Error : check the error message for more // better understanding std::cout << \"\\n\\n\\n\"; const std::string constObj( \"Calling a std::move() on a const object usually has no effect.\"); // constObjectCallFunc(std::move(constObj)); // Error : because of const qualifier // It doesn't make any sense to steal or // move the resources of a const object return EXIT_SUCCESS;} void foo(const std::string& str){ // do something std::cout << \"foo(const std::string& str) : \" << \"\\n\\t\" << str << std::endl;} void foo(std::string& str){ // do something std::cout << \"foo(std::string& str) : \" << \"\\n\\t\" << str << std::endl;} void foo(std::string&& str){ // do something std::cout << \"foo(std::string&& str) : \" << \"\\n\\t\" << str << std::endl;} void baz(const std::string& str){ // do something std::cout << \"baz(const std::string& str) : \" << \"\\n\\t\" << str << std::endl;} void baz(std::string& str){ // do something std::cout << \"baz(std::string& str) : \" << \"\\n\\t\" << str << std::endl;} void bar(std::string& str){ // do something std::cout << \"bar(std::string&& str) : \" << \"\\n\\t\" << str << std::endl;} void constObjectCallFunc(std::string&& str){ // do something std::cout << \"constObjectCallFunc(std::string&& str) : \" << \"\\n\\t\" << str << std::endl;}", "e": 44743, "s": 41501, "text": null }, { "code": null, "e": 45031, "s": 44743, "text": "foo(std::string&& str) : \n Hello\nfoo(std::string& str) : \n Good Bye!\nfoo(std::string&& str) : \n Good Bye! using std::move()\n\n\n\nbaz(const std::string& str) : \n This is temporary string object\nbaz(const std::string& str) : \n This is temporary string object using std::move()" }, { "code": null, "e": 45041, "s": 45031, "text": "Summary: " }, { "code": null, "e": 45249, "s": 45041, "text": "Move semantics allows us to optimize the copying of objects, where we do not need the worth. It is often used implicitly (for unnamed temporary objects or local return values) or explicitly with std::move()." }, { "code": null, "e": 45296, "s": 45249, "text": "std::move() means “no longer need this value”." }, { "code": null, "e": 45427, "s": 45296, "text": "An object marked with std::move() is never partially destroyed. i.e. The destructor will be called to destroy the object properly." }, { "code": null, "e": 45442, "s": 45429, "text": "simmytarika5" }, { "code": null, "e": 45456, "s": 45442, "text": "mayurkedari16" }, { "code": null, "e": 45475, "s": 45456, "text": "surindertarika1234" }, { "code": null, "e": 45485, "s": 45475, "text": "ruhelaa48" }, { "code": null, "e": 45495, "s": 45485, "text": "openberry" }, { "code": null, "e": 45510, "s": 45495, "text": "Blogathon-2021" }, { "code": null, "e": 45523, "s": 45510, "text": "Constructors" }, { "code": null, "e": 45534, "s": 45523, "text": "References" }, { "code": null, "e": 45538, "s": 45534, "text": "STL" }, { "code": null, "e": 45548, "s": 45538, "text": "Blogathon" }, { "code": null, "e": 45552, "s": 45548, "text": "C++" }, { "code": null, "e": 45556, "s": 45552, "text": "STL" }, { "code": null, "e": 45560, "s": 45556, "text": "CPP" }, { "code": null, "e": 45658, "s": 45560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45715, "s": 45658, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 45756, "s": 45715, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 45786, "s": 45756, "text": "Stratified Sampling in Pandas" }, { "code": null, "e": 45821, "s": 45786, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 45865, "s": 45821, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 45883, "s": 45865, "text": "Vector in C++ STL" }, { "code": null, "e": 45899, "s": 45883, "text": "Arrays in C/C++" }, { "code": null, "e": 45945, "s": 45899, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 45964, "s": 45945, "text": "Inheritance in C++" } ]
How to set the title and fonts of your Seaborn Chart? - GeeksforGeeks
25 Feb, 2021 In this article, we are going to see how to set the title and fonts in seaborn chart. Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages and seaborn is an amazing visualization library for statistical graphics plotting in Python. Installation: For python environment : pip install seaborn For conda environment : conda install seaborn Python3 # Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = "white" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = "g") Output: Now we can add a title using set_title() function. This function is capable of a set title and font styling. Syntax: Axes.set_title(label, fontdict) Parameters: label: String fontdict: A dictionary controlling the appearance of the title text. Example 1: Adding title in the seaborn chart. In this example, we are going to set the title using set_title() function. Syntax: set_title(“Label”) Code: Python3 # Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = "white" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = "g").set_title('Seaborn') Output: Example 2: Increase font size of the title. Here we are increasing the size of the font using fontsize attributes. Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’}) Code: Python3 # Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = "white" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = "g").set_title( 'Seaborn', fontdict = { 'fontsize': 30}) Output: Example 3: Setting vertical alignment of a font. Here we are setting alignment of a font using verticalalignment attributes. Valid verticalalignment value for align; supported values are ‘top’, ‘bottom’, ‘center’, ‘baseline’, ‘center_baseline’. Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’, verticalalignment =”‘top’, ‘bottom’, ‘center’, ‘baseline’, ‘center_baseline'”}) Code: Python3 # Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = "white" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = "g").set_title( 'seaborn', fontdict= { 'fontsize': 30, 'verticalalignment': 'bottom'}) Output: Example 4: Setting horizontal alignment. Here we are setting the alignment of a font using horizontalalignment attributes. Valid horizontalalignment value for align; supported values are center’, ‘right’, ‘left’. Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’, horizontalalignment =”‘center’, ‘right’, ‘left'”}) Code: Python3 # Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = "white" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = "g").set_title( 'seaborn', fontdict= { 'fontsize': 24, 'horizontalalignment': 'left'}) Output: Now check for right side alignment using horizontalalignment’: ‘right’: Python3 # Importing librariesimport numpy as npimport seaborn as sns # Selecting style as white,# dark, whitegrid, darkgrid# or tickssns.set(style="white") # Generate a random univariate# datasetrs = np.random.RandomState(10)d = rs.normal(size=50) # Plot a simple histogram and kde# with binsize determined automaticallysns.distplot(d, kde=True, color="g").set_title( 'seaborn', fontdict={'fontsize': 24, 'horizontalalignment': 'right'}) Output: Picked Python-Seaborn 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n25 Feb, 2021" }, { "code": null, "e": 25907, "s": 25537, "text": "In this article, we are going to see how to set the title and fonts in seaborn chart. Data Visualization is the presentation of data in pictorial format. It is extremely important for Data Analysis, primarily because of the fantastic ecosystem of data-centric Python packages and seaborn is an amazing visualization library for statistical graphics plotting in Python. " }, { "code": null, "e": 25921, "s": 25907, "text": "Installation:" }, { "code": null, "e": 25947, "s": 25921, "text": "For python environment : " }, { "code": null, "e": 25967, "s": 25947, "text": "pip install seaborn" }, { "code": null, "e": 25992, "s": 25967, "text": "For conda environment : " }, { "code": null, "e": 26014, "s": 25992, "text": "conda install seaborn" }, { "code": null, "e": 26022, "s": 26014, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = \"white\" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = \"g\")", "e": 26429, "s": 26022, "text": null }, { "code": null, "e": 26437, "s": 26429, "text": "Output:" }, { "code": null, "e": 26547, "s": 26437, "text": "Now we can add a title using set_title() function. This function is capable of a set title and font styling. " }, { "code": null, "e": 26587, "s": 26547, "text": "Syntax: Axes.set_title(label, fontdict)" }, { "code": null, "e": 26599, "s": 26587, "text": "Parameters:" }, { "code": null, "e": 26613, "s": 26599, "text": "label: String" }, { "code": null, "e": 26682, "s": 26613, "text": "fontdict: A dictionary controlling the appearance of the title text." }, { "code": null, "e": 26728, "s": 26682, "text": "Example 1: Adding title in the seaborn chart." }, { "code": null, "e": 26803, "s": 26728, "text": "In this example, we are going to set the title using set_title() function." }, { "code": null, "e": 26830, "s": 26803, "text": "Syntax: set_title(“Label”)" }, { "code": null, "e": 26836, "s": 26830, "text": "Code:" }, { "code": null, "e": 26844, "s": 26836, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = \"white\" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = \"g\").set_title('Seaborn')", "e": 27272, "s": 26844, "text": null }, { "code": null, "e": 27280, "s": 27272, "text": "Output:" }, { "code": null, "e": 27324, "s": 27280, "text": "Example 2: Increase font size of the title." }, { "code": null, "e": 27395, "s": 27324, "text": "Here we are increasing the size of the font using fontsize attributes." }, { "code": null, "e": 27452, "s": 27395, "text": "Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’})" }, { "code": null, "e": 27458, "s": 27452, "text": "Code:" }, { "code": null, "e": 27466, "s": 27458, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = \"white\" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = \"g\").set_title( 'Seaborn', fontdict = { 'fontsize': 30})", "e": 27926, "s": 27466, "text": null }, { "code": null, "e": 27934, "s": 27926, "text": "Output:" }, { "code": null, "e": 27983, "s": 27934, "text": "Example 3: Setting vertical alignment of a font." }, { "code": null, "e": 28179, "s": 27983, "text": "Here we are setting alignment of a font using verticalalignment attributes. Valid verticalalignment value for align; supported values are ‘top’, ‘bottom’, ‘center’, ‘baseline’, ‘center_baseline’." }, { "code": null, "e": 28315, "s": 28179, "text": "Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’, verticalalignment =”‘top’, ‘bottom’, ‘center’, ‘baseline’, ‘center_baseline'”})" }, { "code": null, "e": 28321, "s": 28315, "text": "Code:" }, { "code": null, "e": 28329, "s": 28321, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = \"white\" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = \"g\").set_title( 'seaborn', fontdict= { 'fontsize': 30, 'verticalalignment': 'bottom'})", "e": 28819, "s": 28329, "text": null }, { "code": null, "e": 28827, "s": 28819, "text": "Output:" }, { "code": null, "e": 28868, "s": 28827, "text": "Example 4: Setting horizontal alignment." }, { "code": null, "e": 29040, "s": 28868, "text": "Here we are setting the alignment of a font using horizontalalignment attributes. Valid horizontalalignment value for align; supported values are center’, ‘right’, ‘left’." }, { "code": null, "e": 29147, "s": 29040, "text": "Syntax: set_title(“Label”, fontdict={ ‘fontsize : int’, horizontalalignment =”‘center’, ‘right’, ‘left'”})" }, { "code": null, "e": 29153, "s": 29147, "text": "Code:" }, { "code": null, "e": 29161, "s": 29153, "text": "Python3" }, { "code": "# Importing libraries import numpy as np import seaborn as sns # Selecting style as white, # dark, whitegrid, darkgrid # or ticks sns.set( style = \"white\" ) # Generate a random univariate # dataset rs = np.random.RandomState( 10 ) d = rs.normal( size = 50 ) # Plot a simple histogram and kde # with binsize determined automatically sns.distplot(d, kde = True, color = \"g\").set_title( 'seaborn', fontdict= { 'fontsize': 24, 'horizontalalignment': 'left'})", "e": 29655, "s": 29161, "text": null }, { "code": null, "e": 29663, "s": 29655, "text": "Output:" }, { "code": null, "e": 29735, "s": 29663, "text": "Now check for right side alignment using horizontalalignment’: ‘right’:" }, { "code": null, "e": 29743, "s": 29735, "text": "Python3" }, { "code": "# Importing librariesimport numpy as npimport seaborn as sns # Selecting style as white,# dark, whitegrid, darkgrid# or tickssns.set(style=\"white\") # Generate a random univariate# datasetrs = np.random.RandomState(10)d = rs.normal(size=50) # Plot a simple histogram and kde# with binsize determined automaticallysns.distplot(d, kde=True, color=\"g\").set_title( 'seaborn', fontdict={'fontsize': 24, 'horizontalalignment': 'right'})", "e": 30177, "s": 29743, "text": null }, { "code": null, "e": 30185, "s": 30177, "text": "Output:" }, { "code": null, "e": 30192, "s": 30185, "text": "Picked" }, { "code": null, "e": 30207, "s": 30192, "text": "Python-Seaborn" }, { "code": null, "e": 30214, "s": 30207, "text": "Python" }, { "code": null, "e": 30312, "s": 30214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30344, "s": 30312, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30386, "s": 30344, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30428, "s": 30386, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30484, "s": 30428, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30511, "s": 30484, "text": "Python Classes and Objects" }, { "code": null, "e": 30550, "s": 30511, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30581, "s": 30550, "text": "Python | os.path.join() method" }, { "code": null, "e": 30610, "s": 30581, "text": "Create a directory in Python" }, { "code": null, "e": 30632, "s": 30610, "text": "Defaultdict in Python" } ]
How to search special character in an angular smart table? - GeeksforGeeks
15 Sep, 2020 Introduction on Smart table: It is an Angularjs module used for display purpose as a table format with a set of features like filtering, sorting, etc., This is very much helpful during report preparation, filtering and searching of data in a quicker manner in angular js. It is lightweight, developer-friendly, robust, modular, and extensible Approaches: We can start using smart table by using the below ways bower install angular-smart-table (or) npm install angular-smart-table Once the above scripts are executed, we are set in using angular-smart-table Syntax: Add the module angular.module(‘<nameofyourapp>’, [‘smart-table’] to the angular application.Just like following normal html table structure, on the table element, need to add the “st-table” attribute to inform smart-table about the collection that will display the data, (i.e., using repeater)For Searching a content in angular-smart-table, we need to use, stSearch directive. It can be a comma-separated list of search items that need to be searchedstDebounceTime attribute (the value is in millisecond) can be used in order to control the searching time. Sometimes useless calls will be made (when especially connected to the server) and in order to overcome, this attribute is needed.During search, the input can be a regular expression pattern. Sometimes, in order to escape regexp specific characters in the input, we need to use stSearchEscape attribute. Add the module angular.module(‘<nameofyourapp>’, [‘smart-table’] to the angular application. Just like following normal html table structure, on the table element, need to add the “st-table” attribute to inform smart-table about the collection that will display the data, (i.e., using repeater) For Searching a content in angular-smart-table, we need to use, stSearch directive. It can be a comma-separated list of search items that need to be searched stDebounceTime attribute (the value is in millisecond) can be used in order to control the searching time. Sometimes useless calls will be made (when especially connected to the server) and in order to overcome, this attribute is needed. During search, the input can be a regular expression pattern. Sometimes, in order to escape regexp specific characters in the input, we need to use stSearchEscape attribute. Basic Examples and Explanations: Let us see the sample code of searching in the smart table along with filtering and pagination is seen in below code Data is retrieved from “http://coderszine.com/demo/rest-api/v1/employee/read” for our sample stSafeSrc attribute: As we have taken data from the restful endpoint (even from a remote database, restful endpoint, ajax call, etc)we need to use this attribute without fail. Moreover smart table creates a copy of the displayed collection and since asynchronous data is involved, this attribute is a must. Here “employees” retrieved as asynchronously and need to be rendered and it is specified in st-safe-src sort is applied on all columns and hence st-sort is given for sorting. pagination is applied to have 5 records per page. Input : With the above approaches, let us render the data in a smart table with search, sort, and pagination functionalities SampleApp = angular.module('SampleApp', ['SampleApp.controllers', 'smart-table']); angular.module('SampleApp.controllers', []).controller('sampleController',['$scope', '$http', function($scope, $http) { $scope.loading = false; $scope.getData = function() { $scope.loading = true; $http.get("http://coderszine.com/demo/rest-api/v1/employee/read") .then(function(response){ $scope.employees = response.data; $scope.loading = false; }); } $scope.getData();}]); HTML: <!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-smart-table/2.1.8/smart-table.min.js"> </script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans" /> <!-- Indication to know we are using smartTableApp.js --> <script src="smartTableApp.js"> </script> </head> <body> <!-- Including our SampleApp and iterate in Angular JS --> <div class="container" ng-app="SampleApp" ng-controller="sampleController"> <h2>Angular Smart Table Example with Pagination, Search and Sorting in a simpler way</h2> <div ng-show="loading"><h3>Loading the data...</h3> </div> <table st-table="displayEmployee" st-safe-src="employees" class="table table-striped"> <thead> <tr> <th colspan="1"> <input st-search placeholder= "Please provide data to search" class="input-sm form-control" type="search" /> </th> </tr> <tr> <th st-sort="name">Employee Name</th> <th st-sort="gender">Gender</th> <th st-sort="age">Employee Age</th> <th st-sort="skills">Skills</th> <th st-sort="designation"> Employee Designation</th> </tr> </thead> <tbody> <tr st-select-row="row" st-select-mode="multiple" ng-repeat="employee in displayEmployee"> <td>{{employee.name}}</td> <td>{{employee.gender}}</td> <td>{{employee.age}}</td> <td>{{employee.skills}}</td> <td>{{employee.designation}}</td> </tr> </tbody> <tfoot> <tr> <td colspan="5" class="text-center"> <div st-pagination="" st-items-by-page="5"></div> </td> </tr> </tfoot> </table> </div> </body></html> Output: After Searching a text Sorting based on Designation AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n15 Sep, 2020" }, { "code": null, "e": 26383, "s": 26354, "text": "Introduction on Smart table:" }, { "code": null, "e": 26697, "s": 26383, "text": "It is an Angularjs module used for display purpose as a table format with a set of features like filtering, sorting, etc., This is very much helpful during report preparation, filtering and searching of data in a quicker manner in angular js. It is lightweight, developer-friendly, robust, modular, and extensible" }, { "code": null, "e": 26709, "s": 26697, "text": "Approaches:" }, { "code": null, "e": 26764, "s": 26709, "text": "We can start using smart table by using the below ways" }, { "code": null, "e": 26803, "s": 26764, "text": "bower install angular-smart-table (or)" }, { "code": null, "e": 26835, "s": 26803, "text": "npm install angular-smart-table" }, { "code": null, "e": 26912, "s": 26835, "text": "Once the above scripts are executed, we are set in using angular-smart-table" }, { "code": null, "e": 26920, "s": 26912, "text": "Syntax:" }, { "code": null, "e": 27783, "s": 26920, "text": "Add the module angular.module(‘<nameofyourapp>’, [‘smart-table’] to the angular application.Just like following normal html table structure, on the table element, need to add the “st-table” attribute to inform smart-table about the collection that will display the data, (i.e., using repeater)For Searching a content in angular-smart-table, we need to use, stSearch directive. It can be a comma-separated list of search items that need to be searchedstDebounceTime attribute (the value is in millisecond) can be used in order to control the searching time. Sometimes useless calls will be made (when especially connected to the server) and in order to overcome, this attribute is needed.During search, the input can be a regular expression pattern. Sometimes, in order to escape regexp specific characters in the input, we need to use stSearchEscape attribute." }, { "code": null, "e": 27876, "s": 27783, "text": "Add the module angular.module(‘<nameofyourapp>’, [‘smart-table’] to the angular application." }, { "code": null, "e": 28080, "s": 27876, "text": "Just like following normal html table structure, on the table element, need to add the “st-table” attribute to inform smart-table about the collection that will display the data, (i.e., using repeater)" }, { "code": null, "e": 28238, "s": 28080, "text": "For Searching a content in angular-smart-table, we need to use, stSearch directive. It can be a comma-separated list of search items that need to be searched" }, { "code": null, "e": 28476, "s": 28238, "text": "stDebounceTime attribute (the value is in millisecond) can be used in order to control the searching time. Sometimes useless calls will be made (when especially connected to the server) and in order to overcome, this attribute is needed." }, { "code": null, "e": 28650, "s": 28476, "text": "During search, the input can be a regular expression pattern. Sometimes, in order to escape regexp specific characters in the input, we need to use stSearchEscape attribute." }, { "code": null, "e": 28683, "s": 28650, "text": "Basic Examples and Explanations:" }, { "code": null, "e": 28800, "s": 28683, "text": "Let us see the sample code of searching in the smart table along with filtering and pagination is seen in below code" }, { "code": null, "e": 28893, "s": 28800, "text": "Data is retrieved from “http://coderszine.com/demo/rest-api/v1/employee/read” for our sample" }, { "code": null, "e": 28914, "s": 28893, "text": "stSafeSrc attribute:" }, { "code": null, "e": 29200, "s": 28914, "text": "As we have taken data from the restful endpoint (even from a remote database, restful endpoint, ajax call, etc)we need to use this attribute without fail. Moreover smart table creates a copy of the displayed collection and since asynchronous data is involved, this attribute is a must." }, { "code": null, "e": 29304, "s": 29200, "text": "Here “employees” retrieved as asynchronously and need to be rendered and it is specified in st-safe-src" }, { "code": null, "e": 29375, "s": 29304, "text": "sort is applied on all columns and hence st-sort is given for sorting." }, { "code": null, "e": 29425, "s": 29375, "text": "pagination is applied to have 5 records per page." }, { "code": null, "e": 29433, "s": 29425, "text": "Input :" }, { "code": null, "e": 29550, "s": 29433, "text": "With the above approaches, let us render the data in a smart table with search, sort, and pagination functionalities" }, { "code": "SampleApp = angular.module('SampleApp', ['SampleApp.controllers', 'smart-table']); angular.module('SampleApp.controllers', []).controller('sampleController',['$scope', '$http', function($scope, $http) { $scope.loading = false; $scope.getData = function() { $scope.loading = true; $http.get(\"http://coderszine.com/demo/rest-api/v1/employee/read\") .then(function(response){ $scope.employees = response.data; $scope.loading = false; }); } $scope.getData();}]);", "e": 30075, "s": 29550, "text": null }, { "code": null, "e": 30081, "s": 30075, "text": "HTML:" }, { "code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/angular-smart-table/2.1.8/smart-table.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Open+Sans\" /> <!-- Indication to know we are using smartTableApp.js --> <script src=\"smartTableApp.js\"> </script> </head> <body> <!-- Including our SampleApp and iterate in Angular JS --> <div class=\"container\" ng-app=\"SampleApp\" ng-controller=\"sampleController\"> <h2>Angular Smart Table Example with Pagination, Search and Sorting in a simpler way</h2> <div ng-show=\"loading\"><h3>Loading the data...</h3> </div> <table st-table=\"displayEmployee\" st-safe-src=\"employees\" class=\"table table-striped\"> <thead> <tr> <th colspan=\"1\"> <input st-search placeholder= \"Please provide data to search\" class=\"input-sm form-control\" type=\"search\" /> </th> </tr> <tr> <th st-sort=\"name\">Employee Name</th> <th st-sort=\"gender\">Gender</th> <th st-sort=\"age\">Employee Age</th> <th st-sort=\"skills\">Skills</th> <th st-sort=\"designation\"> Employee Designation</th> </tr> </thead> <tbody> <tr st-select-row=\"row\" st-select-mode=\"multiple\" ng-repeat=\"employee in displayEmployee\"> <td>{{employee.name}}</td> <td>{{employee.gender}}</td> <td>{{employee.age}}</td> <td>{{employee.skills}}</td> <td>{{employee.designation}}</td> </tr> </tbody> <tfoot> <tr> <td colspan=\"5\" class=\"text-center\"> <div st-pagination=\"\" st-items-by-page=\"5\"></div> </td> </tr> </tfoot> </table> </div> </body></html>", "e": 32960, "s": 30081, "text": null }, { "code": null, "e": 32968, "s": 32960, "text": "Output:" }, { "code": null, "e": 32991, "s": 32968, "text": "After Searching a text" }, { "code": null, "e": 33020, "s": 32991, "text": "Sorting based on Designation" }, { "code": null, "e": 33035, "s": 33020, "text": "AngularJS-Misc" }, { "code": null, "e": 33045, "s": 33035, "text": "AngularJS" }, { "code": null, "e": 33062, "s": 33045, "text": "Web Technologies" }, { "code": null, "e": 33160, "s": 33062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33195, "s": 33160, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 33230, "s": 33195, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 33254, "s": 33230, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 33289, "s": 33254, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 33342, "s": 33289, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 33382, "s": 33342, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33415, "s": 33382, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33460, "s": 33415, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33503, "s": 33460, "text": "How to fetch data from an API in ReactJS ?" } ]
GATE | GATE-CS-2005 | Question 43 - GeeksforGeeks
28 Jun, 2021 Let f: B → C and g: A → B be two functions and let h = f o g. Given that h is an onto function. Which one of the following is TRUE?(A) f and g should both be onto functions.(B) f should be onto but g need not be onto(C) g should be onto but f need not be onto(D) both f and g need not be ontoAnswer: (B)Explanation: A function f: X → Y is called on-to function if for every value in set Y, there is a value in set X. Given that, f: B → C and g: A → B and h = f o g. Note that the sign o represents composition. h is basically f(g(x)). So h is a function from set A to set C. It is also given that h is an onto function which means for every value in C there is a value in A. We map from C to A using B. So for every value in C, there must be a value in B. It means f must be onto. But g may or may not be onto as there may be some values in B which don’t map to A. Example : Let us consider following sets A : {a1, a2, a3} B : {b1, b2} C : {c1} And following function values f(b1) = c1 g(a1) = b1, g(a2) = b1, g(a3) = b1 Values of h() would be, h(a1) = c1, h(a2) = c1, h(a3) = c1 Here h is onto, therefore f is onto, but g is onto as b2 is not mapped to any value in A. Given that, f: B → C and g: A → B and h = f o g. Quiz of this Question GATE-CS-2005 GATE-GATE-CS-2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25783, "s": 25755, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26200, "s": 25783, "text": "Let f: B → C and g: A → B be two functions and let h = f o g. Given that h is an onto function. Which one of the following is TRUE?(A) f and g should both be onto functions.(B) f should be onto but g need not be onto(C) g should be onto but f need not be onto(D) both f and g need not be ontoAnswer: (B)Explanation: A function f: X → Y is called on-to function if for every value in set Y, there is a value in set X." }, { "code": null, "e": 26465, "s": 26200, "text": "Given that, f: B → C and g: A → B and h = f o g. \n\nNote that the sign o represents composition. \n\nh is basically f(g(x)). So h is a function from set A\nto set C.\n\nIt is also given that h is an onto function which means\nfor every value in C there is a value in A. " }, { "code": null, "e": 26571, "s": 26465, "text": "We map from C to A using B. So for every value in C, there must be a value in B. It means f must be onto." }, { "code": null, "e": 26655, "s": 26571, "text": "But g may or may not be onto as there may be some values in B which don’t map to A." }, { "code": null, "e": 26665, "s": 26655, "text": "Example :" }, { "code": null, "e": 26964, "s": 26665, "text": "Let us consider following sets\nA : {a1, a2, a3}\nB : {b1, b2}\nC : {c1}\n\nAnd following function values\nf(b1) = c1\ng(a1) = b1, g(a2) = b1, g(a3) = b1\n\nValues of h() would be,\nh(a1) = c1, h(a2) = c1, h(a3) = c1\n\nHere h is onto, therefore f is onto, but g is \nonto as b2 is not mapped to any value in A." }, { "code": null, "e": 27013, "s": 26964, "text": "Given that, f: B → C and g: A → B and h = f o g." }, { "code": null, "e": 27035, "s": 27013, "text": "Quiz of this Question" }, { "code": null, "e": 27048, "s": 27035, "text": "GATE-CS-2005" }, { "code": null, "e": 27066, "s": 27048, "text": "GATE-GATE-CS-2005" }, { "code": null, "e": 27071, "s": 27066, "text": "GATE" }, { "code": null, "e": 27169, "s": 27071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27203, "s": 27169, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27237, "s": 27203, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27271, "s": 27237, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27304, "s": 27271, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27340, "s": 27304, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27376, "s": 27340, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27410, "s": 27376, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27444, "s": 27410, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27478, "s": 27444, "text": "GATE | GATE-CS-2009 | Question 38" } ]
numpy.reshape() in Python - GeeksforGeeks
09 Mar, 2022 The numpy.reshape() function shapes an array without changing the data of the array. Syntax: numpy.reshape(array, shape, order = 'C') Parameters : array : [array_like]Input array shape : [int or tuples of int] e.g. if we are aranging an array with 10 elements then shaping it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2) order : [C-contiguous, F-contiguous, A-contiguous; optional] C-contiguous order in memory(last index varies the fastest) C order means that operating row-rise on the array will be slightly quicker FORTRAN-contiguous order in memory (first index varies the fastest). F order means that column-wise operations will be faster. ‘A’ means to read / write the elements in Fortran-like index order if, array is Fortran contiguous in memory, C-like order otherwise Return : Array which is reshaped without changing the data. Python # Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print("Original array : \n", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print("\narray reshaped with 2 rows and 4 columns : \n", array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print("\narray reshaped with 2 rows and 4 columns : \n", array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print("\nOriginal array reshaped to 3D : \n", array4) Output : Original array : [0 1 2 3 4 5 6 7] array reshaped with 2 rows and 4 columns : [[0 1 2 3] [4 5 6 7]] array reshaped with 4 rows and 2 columns : [[0 1] [2 3] [4 5] [6 7]] Original array reshaped to 3D : [[[0 1] [2 3]] [[4 5] [6 7]]] [[0 1 2 3] [4 5 6 7]] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.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. AditiGoyal1 saurabh1990aror jeetasitsarkar sooda367 knspavankumar subhajitghosh1997 vinayedula Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Defaultdict in Python Enumerate() in Python sum() function in Python Python String | replace() How to Install PIP on Windows ? Deque in Python Different ways to create Pandas Dataframe Stack in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25379, "s": 25351, "text": "\n09 Mar, 2022" }, { "code": null, "e": 25464, "s": 25379, "text": "The numpy.reshape() function shapes an array without changing the data of the array." }, { "code": null, "e": 25513, "s": 25464, "text": "Syntax: numpy.reshape(array, shape, order = 'C')" }, { "code": null, "e": 25527, "s": 25513, "text": "Parameters : " }, { "code": null, "e": 26261, "s": 25527, "text": "array : [array_like]Input array\nshape : [int or tuples of int] e.g. if we are aranging an array with 10 elements then shaping\n it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)\norder : [C-contiguous, F-contiguous, A-contiguous; optional] \n C-contiguous order in memory(last index varies the fastest)\n C order means that operating row-rise on the array will be slightly quicker\n FORTRAN-contiguous order in memory (first index varies the fastest).\n F order means that column-wise operations will be faster. \n ‘A’ means to read / write the elements in Fortran-like index order if,\n array is Fortran contiguous in memory, C-like order otherwise" }, { "code": null, "e": 26271, "s": 26261, "text": "Return : " }, { "code": null, "e": 26322, "s": 26271, "text": "Array which is reshaped without changing the data." }, { "code": null, "e": 26329, "s": 26322, "text": "Python" }, { "code": "# Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print(\"Original array : \\n\", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print(\"\\narray reshaped with 2 rows and 4 columns : \\n\", array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print(\"\\narray reshaped with 2 rows and 4 columns : \\n\", array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print(\"\\nOriginal array reshaped to 3D : \\n\", array4)", "e": 26948, "s": 26329, "text": null }, { "code": null, "e": 26958, "s": 26948, "text": "Output : " }, { "code": null, "e": 27238, "s": 26958, "text": "Original array : \n [0 1 2 3 4 5 6 7]\n\narray reshaped with 2 rows and 4 columns : \n [[0 1 2 3]\n [4 5 6 7]]\n\narray reshaped with 4 rows and 2 columns : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]]\n\nOriginal array reshaped to 3D : \n [[[0 1]\n [2 3]]\n [[4 5]\n [6 7]]]\n \n \n [[0 1 2 3]\n [4 5 6 7]]" }, { "code": null, "e": 27252, "s": 27238, "text": "References : " }, { "code": null, "e": 27328, "s": 27252, "text": "https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html" }, { "code": null, "e": 27433, "s": 27328, "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": 27733, "s": 27433, "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." }, { "code": null, "e": 27858, "s": 27733, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27870, "s": 27858, "text": "AditiGoyal1" }, { "code": null, "e": 27886, "s": 27870, "text": "saurabh1990aror" }, { "code": null, "e": 27901, "s": 27886, "text": "jeetasitsarkar" }, { "code": null, "e": 27910, "s": 27901, "text": "sooda367" }, { "code": null, "e": 27924, "s": 27910, "text": "knspavankumar" }, { "code": null, "e": 27942, "s": 27924, "text": "subhajitghosh1997" }, { "code": null, "e": 27953, "s": 27942, "text": "vinayedula" }, { "code": null, "e": 27984, "s": 27953, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 27997, "s": 27984, "text": "Python-numpy" }, { "code": null, "e": 28004, "s": 27997, "text": "Python" }, { "code": null, "e": 28102, "s": 28004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28124, "s": 28102, "text": "Defaultdict in Python" }, { "code": null, "e": 28146, "s": 28124, "text": "Enumerate() in Python" }, { "code": null, "e": 28171, "s": 28146, "text": "sum() function in Python" }, { "code": null, "e": 28197, "s": 28171, "text": "Python String | replace()" }, { "code": null, "e": 28229, "s": 28197, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28245, "s": 28229, "text": "Deque in Python" }, { "code": null, "e": 28287, "s": 28245, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28303, "s": 28287, "text": "Stack in Python" }, { "code": null, "e": 28332, "s": 28303, "text": "*args and **kwargs in Python" } ]
Python Tkinter | Moving objects using Canvas.move() method - GeeksforGeeks
18 Nov, 2021 The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x is horizontal distance from upper-left corner. y is vertical distance from upper-left corner. We will use class to see the working of the move() method. Class parameters- Data members used: master x y canvas rectangleMember functions used: movement() left() right() up() down()Widgets used: CanvasTkinter method used: Canvas.create_rectangle() pack() Canvas.move() after() bind() Below is the Python implementation: Python3 # imports every file form tkinter and tkinter.ttkfrom tkinter import *from tkinter.ttk import * class GFG: def __init__(self, master = None): self.master = master # to take care movement in x direction self.x = 1 # to take care movement in y direction self.y = 0 # canvas object to create shape self.canvas = Canvas(master) # creating rectangle self.rectangle = self.canvas.create_rectangle( 5, 5, 25, 25, fill = "black") self.canvas.pack() # calling class's movement method to # move the rectangle self.movement() def movement(self): # This is where the move() method is called # This moves the rectangle to x, y coordinates self.canvas.move(self.rectangle, self.x, self.y) self.canvas.after(100, self.movement) # for motion in negative x direction def left(self, event): print(event.keysym) self.x = -5 self.y = 0 # for motion in positive x direction def right(self, event): print(event.keysym) self.x = 5 self.y = 0 # for motion in positive y direction def up(self, event): print(event.keysym) self.x = 0 self.y = -5 # for motion in negative y direction def down(self, event): print(event.keysym) self.x = 0 self.y = 5 if __name__ == "__main__": # object of class Tk, responsible for creating # a tkinter toplevel window master = Tk() gfg = GFG(master) # This will bind arrow keys to the tkinter # toplevel which will navigate the image or drawing master.bind("<KeyPress-Left>", lambda e: gfg.left(e)) master.bind("<KeyPress-Right>", lambda e: gfg.right(e)) master.bind("<KeyPress-Up>", lambda e: gfg.up(e)) master.bind("<KeyPress-Down>", lambda e: gfg.down(e)) # Infinite loop breaks only by interrupt mainloop() Output: Extra print statements are used in the above code to show the proper working of the move() method. keysym keyword (Tkinter reserved) is used to print which keyboard key is pressed. surinderdawra388 kapoorsagar226 kumaripunam984122 Python-gui Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25833, "s": 25805, "text": "\n18 Nov, 2021" }, { "code": null, "e": 25975, "s": 25833, "text": "The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level." }, { "code": null, "e": 26278, "s": 25975, "text": "Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x is horizontal distance from upper-left corner. y is vertical distance from upper-left corner." }, { "code": null, "e": 26337, "s": 26278, "text": "We will use class to see the working of the move() method." }, { "code": null, "e": 26357, "s": 26337, "text": "Class parameters- " }, { "code": null, "e": 26568, "s": 26357, "text": "Data members used: master x y canvas rectangleMember functions used: movement() left() right() up() down()Widgets used: CanvasTkinter method used: Canvas.create_rectangle() pack() Canvas.move() after() bind() " }, { "code": null, "e": 26606, "s": 26568, "text": "Below is the Python implementation: " }, { "code": null, "e": 26614, "s": 26606, "text": "Python3" }, { "code": "# imports every file form tkinter and tkinter.ttkfrom tkinter import *from tkinter.ttk import * class GFG: def __init__(self, master = None): self.master = master # to take care movement in x direction self.x = 1 # to take care movement in y direction self.y = 0 # canvas object to create shape self.canvas = Canvas(master) # creating rectangle self.rectangle = self.canvas.create_rectangle( 5, 5, 25, 25, fill = \"black\") self.canvas.pack() # calling class's movement method to # move the rectangle self.movement() def movement(self): # This is where the move() method is called # This moves the rectangle to x, y coordinates self.canvas.move(self.rectangle, self.x, self.y) self.canvas.after(100, self.movement) # for motion in negative x direction def left(self, event): print(event.keysym) self.x = -5 self.y = 0 # for motion in positive x direction def right(self, event): print(event.keysym) self.x = 5 self.y = 0 # for motion in positive y direction def up(self, event): print(event.keysym) self.x = 0 self.y = -5 # for motion in negative y direction def down(self, event): print(event.keysym) self.x = 0 self.y = 5 if __name__ == \"__main__\": # object of class Tk, responsible for creating # a tkinter toplevel window master = Tk() gfg = GFG(master) # This will bind arrow keys to the tkinter # toplevel which will navigate the image or drawing master.bind(\"<KeyPress-Left>\", lambda e: gfg.left(e)) master.bind(\"<KeyPress-Right>\", lambda e: gfg.right(e)) master.bind(\"<KeyPress-Up>\", lambda e: gfg.up(e)) master.bind(\"<KeyPress-Down>\", lambda e: gfg.down(e)) # Infinite loop breaks only by interrupt mainloop()", "e": 28569, "s": 26614, "text": null }, { "code": null, "e": 28579, "s": 28569, "text": "Output: " }, { "code": null, "e": 28761, "s": 28579, "text": "Extra print statements are used in the above code to show the proper working of the move() method. keysym keyword (Tkinter reserved) is used to print which keyboard key is pressed. " }, { "code": null, "e": 28778, "s": 28761, "text": "surinderdawra388" }, { "code": null, "e": 28793, "s": 28778, "text": "kapoorsagar226" }, { "code": null, "e": 28811, "s": 28793, "text": "kumaripunam984122" }, { "code": null, "e": 28822, "s": 28811, "text": "Python-gui" }, { "code": null, "e": 28837, "s": 28822, "text": "Python-tkinter" }, { "code": null, "e": 28844, "s": 28837, "text": "Python" }, { "code": null, "e": 28942, "s": 28844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28960, "s": 28942, "text": "Python Dictionary" }, { "code": null, "e": 28995, "s": 28960, "text": "Read a file line by line in Python" }, { "code": null, "e": 29027, "s": 28995, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29049, "s": 29027, "text": "Enumerate() in Python" }, { "code": null, "e": 29091, "s": 29049, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29121, "s": 29091, "text": "Iterate over a list in Python" }, { "code": null, "e": 29147, "s": 29121, "text": "Python String | replace()" }, { "code": null, "e": 29176, "s": 29147, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29220, "s": 29176, "text": "Reading and Writing to text files in Python" } ]
NZEC error in Python - GeeksforGeeks
19 Oct, 2021 While coding in various competitive sites, many people must have encountered NZEC errors. NZEC (non zero exit code) as the name suggests occurs when your code is failed to return 0. When a code returns 0 it means it is successfully executed otherwise it will return some other number depending on the type of error.When the program ends and it is supposed to return “0” to indicate if finished fine and is not able to do so it causes NZEC. Of course, there are more cases associated with NZEC. Why does NZEC occur?(one example) In python, generally, multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases, int(input()) is not able to read the input properly and shows error like NZEC. How to resolve? For Example, Think of a simple program where you have to read 2 integers and print them(in input file both integers are in same line). Suppose you have two integers as shown below:23 45Instead of using : n = int(input()) k = int(input()) Use: n, k = raw_input().split(" ") n = int(n) k = int(k) to delimit input by white spaces. Wrong code n = int(input())k = int(input())print n," ",k Input:2 3When you run the above code in IDE with above input you will get error:- Traceback (most recent call last): File "b712edd81d4a972de2a9189fac8a83ed.py", line 1, in n = int(input()) File "", line 1 2 3 ^ SyntaxError: unexpected EOF while parsing The above code will work fine when the input is in 2 two different lines. You can test yourself. To overcome this problem you need to use split. Correct code n, k = raw_input().split(" ")n = int(n)k = int(k)print n," ",k Input: 7 3 Output: 7 3 Some prominent reasons for NZEC error Infinite Recursion or if you have run out of stack memory.Input and output both are NOT exactly same as the test cases.As the online platforms, test your program using a computer code which matches your output with the specified outputs exactly.This type of error is also shown when your program is performing basic programming mistakes like dividing by 0.Check for the values of your variables, they can be vulnerable to integer flow. Infinite Recursion or if you have run out of stack memory. Input and output both are NOT exactly same as the test cases. As the online platforms, test your program using a computer code which matches your output with the specified outputs exactly. This type of error is also shown when your program is performing basic programming mistakes like dividing by 0. Check for the values of your variables, they can be vulnerable to integer flow. There could be some other reasons also for the occurrence NZEC error, I have listed the frequent ones. This article is contributed by Aakash Tiwari. 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. puja84375 Competitive Programming Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Fast I/O for Competitive Programming 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
[ { "code": null, "e": 42677, "s": 42649, "text": "\n19 Oct, 2021" }, { "code": null, "e": 43171, "s": 42677, "text": "While coding in various competitive sites, many people must have encountered NZEC errors. NZEC (non zero exit code) as the name suggests occurs when your code is failed to return 0. When a code returns 0 it means it is successfully executed otherwise it will return some other number depending on the type of error.When the program ends and it is supposed to return “0” to indicate if finished fine and is not able to do so it causes NZEC. Of course, there are more cases associated with NZEC." }, { "code": null, "e": 43205, "s": 43171, "text": "Why does NZEC occur?(one example)" }, { "code": null, "e": 43499, "s": 43205, "text": "In python, generally, multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases, int(input()) is not able to read the input properly and shows error like NZEC." }, { "code": null, "e": 43515, "s": 43499, "text": "How to resolve?" }, { "code": null, "e": 43719, "s": 43515, "text": "For Example, Think of a simple program where you have to read 2 integers and print them(in input file both integers are in same line). Suppose you have two integers as shown below:23 45Instead of using :" }, { "code": null, "e": 43753, "s": 43719, "text": "n = int(input())\nk = int(input())" }, { "code": null, "e": 43758, "s": 43753, "text": "Use:" }, { "code": null, "e": 43810, "s": 43758, "text": "n, k = raw_input().split(\" \")\nn = int(n)\nk = int(k)" }, { "code": null, "e": 43844, "s": 43810, "text": "to delimit input by white spaces." }, { "code": null, "e": 43855, "s": 43844, "text": "Wrong code" }, { "code": "n = int(input())k = int(input())print n,\" \",k", "e": 43901, "s": 43855, "text": null }, { "code": null, "e": 43983, "s": 43901, "text": "Input:2 3When you run the above code in IDE with above input you will get error:-" }, { "code": null, "e": 44174, "s": 43983, "text": "Traceback (most recent call last):\n File \"b712edd81d4a972de2a9189fac8a83ed.py\", line 1, in \n n = int(input())\n File \"\", line 1\n 2 3\n ^\nSyntaxError: unexpected EOF while parsing\n" }, { "code": null, "e": 44319, "s": 44174, "text": "The above code will work fine when the input is in 2 two different lines. You can test yourself. To overcome this problem you need to use split." }, { "code": null, "e": 44332, "s": 44319, "text": "Correct code" }, { "code": "n, k = raw_input().split(\" \")n = int(n)k = int(k)print n,\" \",k", "e": 44395, "s": 44332, "text": null }, { "code": null, "e": 44402, "s": 44395, "text": "Input:" }, { "code": null, "e": 44406, "s": 44402, "text": "7 3" }, { "code": null, "e": 44414, "s": 44406, "text": "Output:" }, { "code": null, "e": 44421, "s": 44414, "text": "7 3\n" }, { "code": null, "e": 44459, "s": 44421, "text": "Some prominent reasons for NZEC error" }, { "code": null, "e": 44895, "s": 44459, "text": "Infinite Recursion or if you have run out of stack memory.Input and output both are NOT exactly same as the test cases.As the online platforms, test your program using a computer code which matches your output with the specified outputs exactly.This type of error is also shown when your program is performing basic programming mistakes like dividing by 0.Check for the values of your variables, they can be vulnerable to integer flow." }, { "code": null, "e": 44954, "s": 44895, "text": "Infinite Recursion or if you have run out of stack memory." }, { "code": null, "e": 45016, "s": 44954, "text": "Input and output both are NOT exactly same as the test cases." }, { "code": null, "e": 45143, "s": 45016, "text": "As the online platforms, test your program using a computer code which matches your output with the specified outputs exactly." }, { "code": null, "e": 45255, "s": 45143, "text": "This type of error is also shown when your program is performing basic programming mistakes like dividing by 0." }, { "code": null, "e": 45335, "s": 45255, "text": "Check for the values of your variables, they can be vulnerable to integer flow." }, { "code": null, "e": 45438, "s": 45335, "text": "There could be some other reasons also for the occurrence NZEC error, I have listed the frequent ones." }, { "code": null, "e": 45735, "s": 45438, "text": "This article is contributed by Aakash Tiwari. 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": 45860, "s": 45735, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 45870, "s": 45860, "text": "puja84375" }, { "code": null, "e": 45894, "s": 45870, "text": "Competitive Programming" }, { "code": null, "e": 45901, "s": 45894, "text": "Python" }, { "code": null, "e": 45999, "s": 45901, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46042, "s": 45999, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 46085, "s": 46042, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 46126, "s": 46085, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 46204, "s": 46126, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 46241, "s": 46204, "text": "Fast I/O for Competitive Programming" }, { "code": null, "e": 46269, "s": 46241, "text": "Read JSON file using Python" }, { "code": null, "e": 46319, "s": 46269, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 46341, "s": 46319, "text": "Python map() function" }, { "code": null, "e": 46385, "s": 46341, "text": "How to get column names in Pandas dataframe" } ]
BinaryField - Django Models - GeeksforGeeks
05 Aug, 2021 BinaryField is a special field to store raw binary data. It can be assigned bytes, bytearray, or memoryview. By default, BinaryField sets editable to False, that is it can’t be included in a ModelForm. Since BinaryField stores raw data or in other terms a python object, it can not be manually entered and needs to be assigned through a view or django shell. This is what editable to False means, that is it can’t be edited through any form. Syntax field_name = models.BinaryField(**options) Illustration of BinaryField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. Python3 from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.BinaryField() Add the geeks app to INSTALLED_APPS Python3 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py Python3 # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.BinaryField()), ], ), ] Thus, an geeks_field BigIntegerField is created when you run makemigrations on the project.It is a field to store raw binary data. Any type of data can be converted into bytes including integers, strings, images, etc. Let’s try to save a string into the BinaryField. String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to the specified encoding. Python3 # importing the model# from geeks appfrom geeks.models import GeeksModel # creating a stringtest_string = "GFG is best" # creating a bytes objectres = bytes(test_string, 'utf-8') # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = res)geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel Possible errorsAs specified, BinaryField is a non-editable field, if you manually try to make it editable using editable=True it will create unexpected errors. It should be created in a function so that objects can be allocated to it. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to BinaryField will enable it to store empty values for that table in relational database. Here are the option and attributes that an BinaryField can use. NaveenArora kk9826225 Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25580, "s": 25552, "text": "\n05 Aug, 2021" }, { "code": null, "e": 26022, "s": 25580, "text": "BinaryField is a special field to store raw binary data. It can be assigned bytes, bytearray, or memoryview. By default, BinaryField sets editable to False, that is it can’t be included in a ModelForm. Since BinaryField stores raw data or in other terms a python object, it can not be manually entered and needs to be assigned through a view or django shell. This is what editable to False means, that is it can’t be edited through any form." }, { "code": null, "e": 26029, "s": 26022, "text": "Syntax" }, { "code": null, "e": 26072, "s": 26029, "text": "field_name = models.BinaryField(**options)" }, { "code": null, "e": 26186, "s": 26072, "text": "Illustration of BinaryField using an Example. Consider a project named geeksforgeeks having an app named geeks. " }, { "code": null, "e": 26274, "s": 26186, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 26325, "s": 26274, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26358, "s": 26325, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26419, "s": 26358, "text": "Enter the following code into models.py file of geeks app. " }, { "code": null, "e": 26427, "s": 26419, "text": "Python3" }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.BinaryField()", "e": 26579, "s": 26427, "text": null }, { "code": null, "e": 26616, "s": 26579, "text": "Add the geeks app to INSTALLED_APPS " }, { "code": null, "e": 26624, "s": 26616, "text": "Python3" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 26861, "s": 26624, "text": null }, { "code": null, "e": 26919, "s": 26861, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 26951, "s": 26919, "text": "Python manage.py makemigrations" }, { "code": null, "e": 27053, "s": 26951, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py " }, { "code": null, "e": 27061, "s": 27053, "text": "Python3" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.BinaryField()), ], ), ]", "e": 27624, "s": 27061, "text": null }, { "code": null, "e": 27756, "s": 27624, "text": "Thus, an geeks_field BigIntegerField is created when you run makemigrations on the project.It is a field to store raw binary data. " }, { "code": null, "e": 28108, "s": 27756, "text": "Any type of data can be converted into bytes including integers, strings, images, etc. Let’s try to save a string into the BinaryField. String can be converted to bytes using the generic bytes function. This function internally points to CPython Library which implicitly calls the encode function for converting the string to the specified encoding. " }, { "code": null, "e": 28116, "s": 28108, "text": "Python3" }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a stringtest_string = \"GFG is best\" # creating a bytes objectres = bytes(test_string, 'utf-8') # creating a instance of# GeeksModelgeek_object = GeeksModel.objects.create(geeks_field = res)geek_object.save()", "e": 28408, "s": 28116, "text": null }, { "code": null, "e": 28487, "s": 28408, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel " }, { "code": null, "e": 28723, "s": 28487, "text": "Possible errorsAs specified, BinaryField is a non-editable field, if you manually try to make it editable using editable=True it will create unexpected errors. It should be created in a function so that objects can be allocated to it. " }, { "code": null, "e": 29004, "s": 28723, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to BinaryField will enable it to store empty values for that table in relational database. " }, { "code": null, "e": 29069, "s": 29004, "text": "Here are the option and attributes that an BinaryField can use. " }, { "code": null, "e": 29083, "s": 29071, "text": "NaveenArora" }, { "code": null, "e": 29093, "s": 29083, "text": "kk9826225" }, { "code": null, "e": 29107, "s": 29093, "text": "Django-models" }, { "code": null, "e": 29121, "s": 29107, "text": "Python Django" }, { "code": null, "e": 29128, "s": 29121, "text": "Python" }, { "code": null, "e": 29226, "s": 29128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29258, "s": 29226, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29300, "s": 29258, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29342, "s": 29300, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29398, "s": 29342, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29425, "s": 29398, "text": "Python Classes and Objects" }, { "code": null, "e": 29456, "s": 29425, "text": "Python | os.path.join() method" }, { "code": null, "e": 29495, "s": 29456, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29524, "s": 29495, "text": "Create a directory in Python" }, { "code": null, "e": 29546, "s": 29524, "text": "Defaultdict in Python" } ]
matplotlib.pyplot.axhline() in Python - GeeksforGeeks
12 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. The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis. Syntax: matplotlib.pyplot.axhline(y=0, xmin=0, xmax=1, **kwargs) Parameters: This method accept the following parameters that are described below: y: This parameter is an optional and it is position in data coordinates of the horizontal line. xmin: This parameter is a scalar and optional. Its default value is 0. xmax: This parameter is a scalar and optional. Its default value is 1. Returns: This returns the following: line : This returns the line created by this function. Below examples illustrate the matplotlib.pyplot.axhline() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib.pyplot.annotate() function import numpy as npimport matplotlib.pyplot as plt t = np.linspace(-10, 10, 100)sig = 1 / t plt.axhline(y = 0, color ="green", linestyle ="--")plt.axhline(y = 0.5, color ="green", linestyle =":")plt.axhline(y = 1.0, color ="green", linestyle ="--") plt.axvline(color ="black") plt.plot(t, sig, linewidth = 2, label = r"$\sigma(t) = \frac{1}{x}$") plt.xlim(-10, 10)plt.xlabel("t")plt.title("Graph of 1 / x")plt.legend(fontsize = 14) plt.show() Output: Example #2: # Implementation of matplotlib.pyplot.annotate() # function import numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 13, 100) plt.rcParams['lines.linewidth'] = 2plt.figure() plt.plot(x, np.sin(x), label ='Line1', color ='green', linestyle ="--") plt.plot(x, np.sin(x + 0.5), label ='Line2', color ='black', linestyle =":") plt.axhline(0, label ='Line3', color ='black') plt.title('Axhline() Example')l = plt.legend(loc ='upper right') # legend between blue and orange # linel.set_zorder(2.5) plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python 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 Graph Plotting in Python | Set 1 Python | Get unique values from a list
[ { "code": null, "e": 25839, "s": 25811, "text": "\n12 Apr, 2020" }, { "code": null, "e": 26034, "s": 25839, "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." }, { "code": null, "e": 26146, "s": 26034, "text": "The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis." }, { "code": null, "e": 26211, "s": 26146, "text": "Syntax: matplotlib.pyplot.axhline(y=0, xmin=0, xmax=1, **kwargs)" }, { "code": null, "e": 26293, "s": 26211, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26389, "s": 26293, "text": "y: This parameter is an optional and it is position in data coordinates of the horizontal line." }, { "code": null, "e": 26460, "s": 26389, "text": "xmin: This parameter is a scalar and optional. Its default value is 0." }, { "code": null, "e": 26531, "s": 26460, "text": "xmax: This parameter is a scalar and optional. Its default value is 1." }, { "code": null, "e": 26568, "s": 26531, "text": "Returns: This returns the following:" }, { "code": null, "e": 26623, "s": 26568, "text": "line : This returns the line created by this function." }, { "code": null, "e": 26712, "s": 26623, "text": "Below examples illustrate the matplotlib.pyplot.axhline() function in matplotlib.pyplot:" }, { "code": null, "e": 26724, "s": 26712, "text": "Example #1:" }, { "code": "# Implementation of matplotlib.pyplot.annotate() function import numpy as npimport matplotlib.pyplot as plt t = np.linspace(-10, 10, 100)sig = 1 / t plt.axhline(y = 0, color =\"green\", linestyle =\"--\")plt.axhline(y = 0.5, color =\"green\", linestyle =\":\")plt.axhline(y = 1.0, color =\"green\", linestyle =\"--\") plt.axvline(color =\"black\") plt.plot(t, sig, linewidth = 2, label = r\"$\\sigma(t) = \\frac{1}{x}$\") plt.xlim(-10, 10)plt.xlabel(\"t\")plt.title(\"Graph of 1 / x\")plt.legend(fontsize = 14) plt.show()", "e": 27240, "s": 26724, "text": null }, { "code": null, "e": 27248, "s": 27240, "text": "Output:" }, { "code": null, "e": 27260, "s": 27248, "text": "Example #2:" }, { "code": "# Implementation of matplotlib.pyplot.annotate() # function import numpy as npimport matplotlib.pyplot as plt x = np.linspace(0, 13, 100) plt.rcParams['lines.linewidth'] = 2plt.figure() plt.plot(x, np.sin(x), label ='Line1', color ='green', linestyle =\"--\") plt.plot(x, np.sin(x + 0.5), label ='Line2', color ='black', linestyle =\":\") plt.axhline(0, label ='Line3', color ='black') plt.title('Axhline() Example')l = plt.legend(loc ='upper right') # legend between blue and orange # linel.set_zorder(2.5) plt.show()", "e": 27803, "s": 27260, "text": null }, { "code": null, "e": 27811, "s": 27803, "text": "Output:" }, { "code": null, "e": 27829, "s": 27811, "text": "Python-matplotlib" }, { "code": null, "e": 27836, "s": 27829, "text": "Python" }, { "code": null, "e": 27934, "s": 27836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27966, "s": 27934, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27995, "s": 27966, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28032, "s": 27995, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28068, "s": 28032, "text": "Convert integer to string in Python" }, { "code": null, "e": 28110, "s": 28068, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28152, "s": 28110, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28179, "s": 28152, "text": "Python Classes and Objects" }, { "code": null, "e": 28235, "s": 28179, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28268, "s": 28235, "text": "Graph Plotting in Python | Set 1" } ]
JDBC Using Model Object and Singleton Class - GeeksforGeeks
28 Jul, 2021 This article explains how to perform JDBC operation using a Model object and a Singleton connection class from a MySQL database. JDBC is an Application Programming Interface for Java which connects a Java application with a database to perform CRUD operations. Pre requisite: JDK 7+ (Click here to download) MySQL Database (Click here to download) MySQL J Connector (Click here to download) JDBC basic (Click here to learn JDBC) Eclipse or any other IDE Model Class: The model class is highly used in the MVC pattern where it works as an intermediate medium between business logic and the view. Usually, a model contains some variables and methods of a specific entity. Singleton Class: Singleton class is a software design pattern that ensures there will be one single instance of that class. There are multiple ways to achieve a singleton class. Approach: We are going to create an Organization database that contains an Employee table. We will also create a java application that will connect with the Organization database. The connection will be established by a singleton class which will contain all the necessary driver information. From the java application, we will perform some data manipulation tasks like insert, delete, update and retrieve using a model object of Employee. Creating a MySQL database and a table:create database org; use org; create table employee( emp_id int auto_increment, emp_name varchar(400), emp_address varchar(400), primary key (emp_id) ); Project setup in eclipse:Create a project in eclipse named ‘jdbc’Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folderAdd jars to java build pathCreate 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.mainDatabase connection: Create a singleton connection class DatabaseConnection in com.jdbc.util package. Use your MySQL username and password on the variable user and pass. Look carefully at the last part of the “url” variable. It is mandatory to keep the name the same as the database name. The name of my database is “org” that’s why I put “org” in the URL variable.DatabaseConnection ClassDatabaseConnection Classpackage com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = "jdbc:mysql:// localhost:3306/org"; String user = "root"; String pass = "root"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }}Model class: Create a model class named Employee in com.jdbc.model package. It should contain all the attributes as variables.Model ClassModel Classpackage com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return "Employee [emp_id=" + emp_id + ", emp_name=" + emp_name + ", emp_address=" + emp_address + "]"; }}Database Access Object(DAO): We will create an EmployeeDao interface and another class EmployeeDaoImplementation which implements EmployeeDao. This implemented class will be used as a DAO to perform CRUD operations. We will use PreparedStatement to execute the query. PreparedStatement has 3 special methods:executeQuery(): used to retrieve dataexecuteUpdate(): used to insert, update, deleteexecute(): used to createEmployeeDao InterfaceEmployeeDaoImplementation ClassEmployeeDao Interfacepackage com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;}EmployeeDaoImplementation Classpackage com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = "insert into employee(emp_name, " + "emp_address) VALUES (?, ?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = "delete from employee where emp_id =?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = "select * from employee where emp_id= ?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = "select * from employee"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = "update employee set emp_name=?, " + " emp_address= ? where emp_id = ?"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }}Test the application: Finally, its time to perform the CRUD application using all the methods of EmployeeDaoImplementation. Create a class Application in com.jdbc.main package.Driver codeDriver codepackage com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name("Haider"); emp.setEmp_address("Mars"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + " " + e.getEmp_name() + " " + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address("Asgard"); empDao.update(tempEmployee); // delete empDao.delete(1); }} Creating a MySQL database and a table:create database org; use org; create table employee( emp_id int auto_increment, emp_name varchar(400), emp_address varchar(400), primary key (emp_id) ); create database org; use org; create table employee( emp_id int auto_increment, emp_name varchar(400), emp_address varchar(400), primary key (emp_id) ); Project setup in eclipse:Create a project in eclipse named ‘jdbc’Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folderAdd jars to java build pathCreate 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.main Create a project in eclipse named ‘jdbc’ Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folder Add jars to java build path Create 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.main Database connection: Create a singleton connection class DatabaseConnection in com.jdbc.util package. Use your MySQL username and password on the variable user and pass. Look carefully at the last part of the “url” variable. It is mandatory to keep the name the same as the database name. The name of my database is “org” that’s why I put “org” in the URL variable.DatabaseConnection ClassDatabaseConnection Classpackage com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = "jdbc:mysql:// localhost:3306/org"; String user = "root"; String pass = "root"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }} DatabaseConnection Class package com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = "jdbc:mysql:// localhost:3306/org"; String user = "root"; String pass = "root"; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }} Model class: Create a model class named Employee in com.jdbc.model package. It should contain all the attributes as variables.Model ClassModel Classpackage com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return "Employee [emp_id=" + emp_id + ", emp_name=" + emp_name + ", emp_address=" + emp_address + "]"; }} Model Class package com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return "Employee [emp_id=" + emp_id + ", emp_name=" + emp_name + ", emp_address=" + emp_address + "]"; }} Database Access Object(DAO): We will create an EmployeeDao interface and another class EmployeeDaoImplementation which implements EmployeeDao. This implemented class will be used as a DAO to perform CRUD operations. We will use PreparedStatement to execute the query. PreparedStatement has 3 special methods:executeQuery(): used to retrieve dataexecuteUpdate(): used to insert, update, deleteexecute(): used to createEmployeeDao InterfaceEmployeeDaoImplementation ClassEmployeeDao Interfacepackage com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;}EmployeeDaoImplementation Classpackage com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = "insert into employee(emp_name, " + "emp_address) VALUES (?, ?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = "delete from employee where emp_id =?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = "select * from employee where emp_id= ?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = "select * from employee"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = "update employee set emp_name=?, " + " emp_address= ? where emp_id = ?"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }} executeQuery(): used to retrieve data executeUpdate(): used to insert, update, delete execute(): used to create EmployeeDao Interface EmployeeDaoImplementation Class package com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;} package com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = "insert into employee(emp_name, " + "emp_address) VALUES (?, ?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = "delete from employee where emp_id =?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = "select * from employee where emp_id= ?"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = "select * from employee"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt("emp_id")); emp.setEmp_name(rs.getString("emp_name")); emp.setEmp_address(rs.getString("emp_address")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = "update employee set emp_name=?, " + " emp_address= ? where emp_id = ?"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }} Test the application: Finally, its time to perform the CRUD application using all the methods of EmployeeDaoImplementation. Create a class Application in com.jdbc.main package.Driver codeDriver codepackage com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name("Haider"); emp.setEmp_address("Mars"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + " " + e.getEmp_name() + " " + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address("Asgard"); empDao.update(tempEmployee); // delete empDao.delete(1); }} Driver code package com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name("Haider"); emp.setEmp_address("Mars"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + " " + e.getEmp_name() + " " + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address("Asgard"); empDao.update(tempEmployee); // delete empDao.delete(1); }} Output: For the insert operation, you have to look to your Employee table in the Org database. For read one item, use id to fetch data and print it to console. For displaying all the items, just call the method and print it to console. The update operation should change the updated value into the database. The delete operation will delete the information of that id from the database. gabaa406 JDBC mysql DBMS Design Pattern Java Programs SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Deadlock in DBMS Types of Functional dependencies in DBMS KDD Process in Data Mining Conflict Serializability in DBMS What is Temporary Table in SQL? SDE SHEET - A Complete Guide for SDE Preparation Singleton Class in Java Design Patterns | Set 1 (Introduction) Singleton Design Pattern | Implementation Unified Modeling Language (UML) | Sequence Diagrams
[ { "code": null, "e": 25549, "s": 25521, "text": "\n28 Jul, 2021" }, { "code": null, "e": 25678, "s": 25549, "text": "This article explains how to perform JDBC operation using a Model object and a Singleton connection class from a MySQL database." }, { "code": null, "e": 25810, "s": 25678, "text": "JDBC is an Application Programming Interface for Java which connects a Java application with a database to perform CRUD operations." }, { "code": null, "e": 25825, "s": 25810, "text": "Pre requisite:" }, { "code": null, "e": 25857, "s": 25825, "text": "JDK 7+ (Click here to download)" }, { "code": null, "e": 25897, "s": 25857, "text": "MySQL Database (Click here to download)" }, { "code": null, "e": 25940, "s": 25897, "text": "MySQL J Connector (Click here to download)" }, { "code": null, "e": 25978, "s": 25940, "text": "JDBC basic (Click here to learn JDBC)" }, { "code": null, "e": 26003, "s": 25978, "text": "Eclipse or any other IDE" }, { "code": null, "e": 26219, "s": 26003, "text": "Model Class: The model class is highly used in the MVC pattern where it works as an intermediate medium between business logic and the view. Usually, a model contains some variables and methods of a specific entity." }, { "code": null, "e": 26397, "s": 26219, "text": "Singleton Class: Singleton class is a software design pattern that ensures there will be one single instance of that class. There are multiple ways to achieve a singleton class." }, { "code": null, "e": 26837, "s": 26397, "text": "Approach: We are going to create an Organization database that contains an Employee table. We will also create a java application that will connect with the Organization database. The connection will be established by a singleton class which will contain all the necessary driver information. From the java application, we will perform some data manipulation tasks like insert, delete, update and retrieve using a model object of Employee." }, { "code": null, "e": 34433, "s": 26837, "text": "Creating a MySQL database and a table:create database org;\nuse org;\ncreate table employee(\n emp_id int auto_increment,\n emp_name varchar(400),\n emp_address varchar(400),\n primary key (emp_id)\n);\nProject setup in eclipse:Create a project in eclipse named ‘jdbc’Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folderAdd jars to java build pathCreate 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.mainDatabase connection: Create a singleton connection class DatabaseConnection in com.jdbc.util package. Use your MySQL username and password on the variable user and pass. Look carefully at the last part of the “url” variable. It is mandatory to keep the name the same as the database name. The name of my database is “org” that’s why I put “org” in the URL variable.DatabaseConnection ClassDatabaseConnection Classpackage com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = \"jdbc:mysql:// localhost:3306/org\"; String user = \"root\"; String pass = \"root\"; try { Class.forName(\"com.mysql.jdbc.Driver\"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }}Model class: Create a model class named Employee in com.jdbc.model package. It should contain all the attributes as variables.Model ClassModel Classpackage com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return \"Employee [emp_id=\" + emp_id + \", emp_name=\" + emp_name + \", emp_address=\" + emp_address + \"]\"; }}Database Access Object(DAO): We will create an EmployeeDao interface and another class EmployeeDaoImplementation which implements EmployeeDao. This implemented class will be used as a DAO to perform CRUD operations. We will use PreparedStatement to execute the query. PreparedStatement has 3 special methods:executeQuery(): used to retrieve dataexecuteUpdate(): used to insert, update, deleteexecute(): used to createEmployeeDao InterfaceEmployeeDaoImplementation ClassEmployeeDao Interfacepackage com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;}EmployeeDaoImplementation Classpackage com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = \"insert into employee(emp_name, \" + \"emp_address) VALUES (?, ?)\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = \"delete from employee where emp_id =?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = \"select * from employee where emp_id= ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = \"select * from employee\"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = \"update employee set emp_name=?, \" + \" emp_address= ? where emp_id = ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }}Test the application: Finally, its time to perform the CRUD application using all the methods of EmployeeDaoImplementation. Create a class Application in com.jdbc.main package.Driver codeDriver codepackage com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name(\"Haider\"); emp.setEmp_address(\"Mars\"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + \" \" + e.getEmp_name() + \" \" + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address(\"Asgard\"); empDao.update(tempEmployee); // delete empDao.delete(1); }}" }, { "code": null, "e": 34641, "s": 34433, "text": "Creating a MySQL database and a table:create database org;\nuse org;\ncreate table employee(\n emp_id int auto_increment,\n emp_name varchar(400),\n emp_address varchar(400),\n primary key (emp_id)\n);\n" }, { "code": null, "e": 34811, "s": 34641, "text": "create database org;\nuse org;\ncreate table employee(\n emp_id int auto_increment,\n emp_name varchar(400),\n emp_address varchar(400),\n primary key (emp_id)\n);\n" }, { "code": null, "e": 35070, "s": 34811, "text": "Project setup in eclipse:Create a project in eclipse named ‘jdbc’Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folderAdd jars to java build pathCreate 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.main" }, { "code": null, "e": 35111, "s": 35070, "text": "Create a project in eclipse named ‘jdbc’" }, { "code": null, "e": 35199, "s": 35111, "text": "Create a folder on that project named ‘jars’ and paste MySQL J Connector on that folder" }, { "code": null, "e": 35227, "s": 35199, "text": "Add jars to java build path" }, { "code": null, "e": 35307, "s": 35227, "text": "Create 4 package: com.jdbc.util, com.jdbc.dao, com.jdbc.model and com.jdbc.main" }, { "code": null, "e": 36353, "s": 35307, "text": "Database connection: Create a singleton connection class DatabaseConnection in com.jdbc.util package. Use your MySQL username and password on the variable user and pass. Look carefully at the last part of the “url” variable. It is mandatory to keep the name the same as the database name. The name of my database is “org” that’s why I put “org” in the URL variable.DatabaseConnection ClassDatabaseConnection Classpackage com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = \"jdbc:mysql:// localhost:3306/org\"; String user = \"root\"; String pass = \"root\"; try { Class.forName(\"com.mysql.jdbc.Driver\"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }}" }, { "code": null, "e": 36378, "s": 36353, "text": "DatabaseConnection Class" }, { "code": "package com.jdbc.util; import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException; public class DatabaseConnection { private static Connection con = null; static { String url = \"jdbc:mysql:// localhost:3306/org\"; String user = \"root\"; String pass = \"root\"; try { Class.forName(\"com.mysql.jdbc.Driver\"); con = DriverManager.getConnection(url, user, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } public static Connection getConnection() { return con; }}", "e": 37011, "s": 36378, "text": null }, { "code": null, "e": 38066, "s": 37011, "text": "Model class: Create a model class named Employee in com.jdbc.model package. It should contain all the attributes as variables.Model ClassModel Classpackage com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return \"Employee [emp_id=\" + emp_id + \", emp_name=\" + emp_name + \", emp_address=\" + emp_address + \"]\"; }}" }, { "code": null, "e": 38078, "s": 38066, "text": "Model Class" }, { "code": "package com.jdbc.model; public class Employee { int emp_id; String emp_name; String emp_address; public Employee() {} public Employee(String emp_name, String emp_address) { this.emp_name = emp_name; this.emp_address = emp_address; } public int getEmp_id() { return emp_id; } public void setEmp_id(int emp_id) { this.emp_id = emp_id; } public String getEmp_name() { return emp_name; } public void setEmp_name(String emp_name) { this.emp_name = emp_name; } public String getEmp_address() { return emp_address; } public void setEmp_address(String emp_address) { this.emp_address = emp_address; } @Override public String toString() { return \"Employee [emp_id=\" + emp_id + \", emp_name=\" + emp_name + \", emp_address=\" + emp_address + \"]\"; }}", "e": 38985, "s": 38078, "text": null }, { "code": null, "e": 42761, "s": 38985, "text": "Database Access Object(DAO): We will create an EmployeeDao interface and another class EmployeeDaoImplementation which implements EmployeeDao. This implemented class will be used as a DAO to perform CRUD operations. We will use PreparedStatement to execute the query. PreparedStatement has 3 special methods:executeQuery(): used to retrieve dataexecuteUpdate(): used to insert, update, deleteexecute(): used to createEmployeeDao InterfaceEmployeeDaoImplementation ClassEmployeeDao Interfacepackage com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;}EmployeeDaoImplementation Classpackage com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = \"insert into employee(emp_name, \" + \"emp_address) VALUES (?, ?)\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = \"delete from employee where emp_id =?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = \"select * from employee where emp_id= ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = \"select * from employee\"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = \"update employee set emp_name=?, \" + \" emp_address= ? where emp_id = ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }}" }, { "code": null, "e": 42799, "s": 42761, "text": "executeQuery(): used to retrieve data" }, { "code": null, "e": 42847, "s": 42799, "text": "executeUpdate(): used to insert, update, delete" }, { "code": null, "e": 42873, "s": 42847, "text": "execute(): used to create" }, { "code": null, "e": 42895, "s": 42873, "text": "EmployeeDao Interface" }, { "code": null, "e": 42927, "s": 42895, "text": "EmployeeDaoImplementation Class" }, { "code": "package com.jdbc.dao; import java.sql.SQLException;import java.util.List; import com.jdbc.model.Employee; public interface EmployeeDao { public int add(Employee emp) throws SQLException; public void delete(int id) throws SQLException; public Employee getEmployee(int id) throws SQLException; public List<Employee> getEmployees() throws SQLException; public void update(Employee emp) throws SQLException;}", "e": 43387, "s": 42927, "text": null }, { "code": "package com.jdbc.dao; import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List; import com.jdbc.model.Employee;import com.jdbc.util.DatabaseConnection; public class EmployeeDaoImplementation implements EmployeeDao { static Connection con = DatabaseConnection.getConnection(); @Override public int add(Employee emp) throws SQLException { String query = \"insert into employee(emp_name, \" + \"emp_address) VALUES (?, ?)\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); int n = ps.executeUpdate(); return n; } @Override public void delete(int id) throws SQLException { String query = \"delete from employee where emp_id =?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); ps.executeUpdate(); } @Override public Employee getEmployee(int id) throws SQLException { String query = \"select * from employee where emp_id= ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, id); Employee emp = new Employee(); ResultSet rs = ps.executeQuery(); boolean check = false; while (rs.next()) { check = true; emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); } if (check == true) { return emp; } else return null; } @Override public List<Employee> getEmployees() throws SQLException { String query = \"select * from employee\"; PreparedStatement ps = con.prepareStatement(query); ResultSet rs = ps.executeQuery(); List<Employee> ls = new ArrayList(); while (rs.next()) { Employee emp = new Employee(); emp.setEmp_id(rs.getInt(\"emp_id\")); emp.setEmp_name(rs.getString(\"emp_name\")); emp.setEmp_address(rs.getString(\"emp_address\")); ls.add(emp); } return ls; } @Override public void update(Employee emp) throws SQLException { String query = \"update employee set emp_name=?, \" + \" emp_address= ? where emp_id = ?\"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, emp.getEmp_name()); ps.setString(2, emp.getEmp_address()); ps.setInt(3, emp.getEmp_id()); ps.executeUpdate(); }}", "e": 46183, "s": 43387, "text": null }, { "code": null, "e": 47440, "s": 46183, "text": "Test the application: Finally, its time to perform the CRUD application using all the methods of EmployeeDaoImplementation. Create a class Application in com.jdbc.main package.Driver codeDriver codepackage com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name(\"Haider\"); emp.setEmp_address(\"Mars\"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + \" \" + e.getEmp_name() + \" \" + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address(\"Asgard\"); empDao.update(tempEmployee); // delete empDao.delete(1); }}" }, { "code": null, "e": 47452, "s": 47440, "text": "Driver code" }, { "code": "package com.jdbc.main; import java.sql.SQLException;import java.util.List; import com.jdbc.dao.EmployeeDaoImplementation;import com.jdbc.model.Employee; public class Application { public static void main(String[] args) throws SQLException { Employee emp = new Employee(); emp.setEmp_name(\"Haider\"); emp.setEmp_address(\"Mars\"); EmployeeDaoImplementation empDao = new EmployeeDaoImplementation(); // add empDao.add(emp); // read Employee e = empDao.getEmployee(1); System.out.println(e.getEmp_id() + \" \" + e.getEmp_name() + \" \" + e.getEmp_address()); // read All List<Employee> ls = empDao.getEmployees(); for (Employee allEmp : ls) { System.out.println(allEmp); } // update Employee tempEmployee = empDao.getEmployee(1); tempEmployee.setEmp_address(\"Asgard\"); empDao.update(tempEmployee); // delete empDao.delete(1); }}", "e": 48511, "s": 47452, "text": null }, { "code": null, "e": 48519, "s": 48511, "text": "Output:" }, { "code": null, "e": 48606, "s": 48519, "text": "For the insert operation, you have to look to your Employee table in the Org database." }, { "code": null, "e": 48671, "s": 48606, "text": "For read one item, use id to fetch data and print it to console." }, { "code": null, "e": 48747, "s": 48671, "text": "For displaying all the items, just call the method and print it to console." }, { "code": null, "e": 48819, "s": 48747, "text": "The update operation should change the updated value into the database." }, { "code": null, "e": 48898, "s": 48819, "text": "The delete operation will delete the information of that id from the database." }, { "code": null, "e": 48907, "s": 48898, "text": "gabaa406" }, { "code": null, "e": 48912, "s": 48907, "text": "JDBC" }, { "code": null, "e": 48918, "s": 48912, "text": "mysql" }, { "code": null, "e": 48923, "s": 48918, "text": "DBMS" }, { "code": null, "e": 48938, "s": 48923, "text": "Design Pattern" }, { "code": null, "e": 48952, "s": 48938, "text": "Java Programs" }, { "code": null, "e": 48956, "s": 48952, "text": "SQL" }, { "code": null, "e": 48961, "s": 48956, "text": "DBMS" }, { "code": null, "e": 48965, "s": 48961, "text": "SQL" }, { "code": null, "e": 49063, "s": 48965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 49080, "s": 49063, "text": "Deadlock in DBMS" }, { "code": null, "e": 49121, "s": 49080, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 49148, "s": 49121, "text": "KDD Process in Data Mining" }, { "code": null, "e": 49181, "s": 49148, "text": "Conflict Serializability in DBMS" }, { "code": null, "e": 49213, "s": 49181, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 49262, "s": 49213, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 49286, "s": 49262, "text": "Singleton Class in Java" }, { "code": null, "e": 49325, "s": 49286, "text": "Design Patterns | Set 1 (Introduction)" }, { "code": null, "e": 49367, "s": 49325, "text": "Singleton Design Pattern | Implementation" } ]
Python - Convert Flat dictionaries to Nested dictionary - GeeksforGeeks
14 May, 2020 Sometimes, while working with records, we can have problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have application in many domains in which data is used extensively. Lets discuss certain ways in which this task can be performed. Method #1 : Using dict() + key accessThis is one of the way in which this task can be performed. In this, we construct empty dictionary using dict and assign a new level to dictionary using manual brute key access. # Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using key access + dict() # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5} # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2)) # Convert Flat dictionaries to Nested dictionary# Using key access + dict()res = dict()res["level1"] = test_dict1res['level2'] = test_dict2 # printing result print("The nested dictionary is : " + str(res)) The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}} Method #2 : Using zip()This is another way in which this task can be performed. In this we link inner keys to outer keys using zip(). # Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using zip() # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5} # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2)) # Convert Flat dictionaries to Nested dictionary# Using zip()key_dict = ['level1', 'level2']dict_list = [test_dict1, test_dict2]res = dict(zip(key_dict, dict_list)) # printing result print("The nested dictionary is : " + str(res)) The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}} Python dictionary-programs Python-nested-dictionary Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25795, "s": 25767, "text": "\n14 May, 2020" }, { "code": null, "e": 26106, "s": 25795, "text": "Sometimes, while working with records, we can have problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have application in many domains in which data is used extensively. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 26321, "s": 26106, "text": "Method #1 : Using dict() + key accessThis is one of the way in which this task can be performed. In this, we construct empty dictionary using dict and assign a new level to dictionary using manual brute key access." }, { "code": "# Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using key access + dict() # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5} # printing original dictionariesprint(\"The original dictionary 1 is : \" + str(test_dict1))print(\"The original dictionary 2 is : \" + str(test_dict2)) # Convert Flat dictionaries to Nested dictionary# Using key access + dict()res = dict()res[\"level1\"] = test_dict1res['level2'] = test_dict2 # printing result print(\"The nested dictionary is : \" + str(res)) ", "e": 26899, "s": 26321, "text": null }, { "code": null, "e": 27099, "s": 26899, "text": "The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}" }, { "code": null, "e": 27235, "s": 27101, "text": "Method #2 : Using zip()This is another way in which this task can be performed. In this we link inner keys to outer keys using zip()." }, { "code": "# Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using zip() # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5} # printing original dictionariesprint(\"The original dictionary 1 is : \" + str(test_dict1))print(\"The original dictionary 2 is : \" + str(test_dict2)) # Convert Flat dictionaries to Nested dictionary# Using zip()key_dict = ['level1', 'level2']dict_list = [test_dict1, test_dict2]res = dict(zip(key_dict, dict_list)) # printing result print(\"The nested dictionary is : \" + str(res)) ", "e": 27824, "s": 27235, "text": null }, { "code": null, "e": 28024, "s": 27824, "text": "The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}" }, { "code": null, "e": 28051, "s": 28024, "text": "Python dictionary-programs" }, { "code": null, "e": 28076, "s": 28051, "text": "Python-nested-dictionary" }, { "code": null, "e": 28083, "s": 28076, "text": "Python" }, { "code": null, "e": 28099, "s": 28083, "text": "Python Programs" }, { "code": null, "e": 28197, "s": 28099, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28232, "s": 28197, "text": "Read a file line by line in Python" }, { "code": null, "e": 28264, "s": 28232, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28286, "s": 28264, "text": "Enumerate() in Python" }, { "code": null, "e": 28328, "s": 28286, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28358, "s": 28328, "text": "Iterate over a list in Python" }, { "code": null, "e": 28401, "s": 28358, "text": "Python program to convert a list to string" }, { "code": null, "e": 28423, "s": 28401, "text": "Defaultdict in Python" }, { "code": null, "e": 28462, "s": 28423, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28508, "s": 28462, "text": "Python | Split string into list of characters" } ]
Java Program to find the Last Index of a Particular Word in a String - GeeksforGeeks
05 Nov, 2020 To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found. Real-life Example: Consider an example of a book. The book contains pages where pages contain words. Now if a user wants to figure out the occurrence of a word of his own choice then the reader’s head rebound of question does that word to be searched even exist in the book And if yes, starts flipping out the pages prior to remembering the page where it last occurred because there may be chances that the word would repeat after the page which he updated the last and is done reading the book. Here the set of all the words in the book is referred to as ‘String’ and the word to be searched is referred to as ‘word’ itself. The exact place where the word occurred is referred to as ‘index’. Now in Java, there is already an inbuilt method defined in strings over dealing with indexes in it known as indexOf(). It is used in finding out the index of a special character or sub-string itself from a given string. As usual, there are two possibilities, first is when a character or substring is present in the string it returns the index, and if not this function returns ‘-1’ if the character or substring is not present out in the string. -1 is returned in java as in java there is no such concept of negative indexed what is present therein python. Similarly, there is also a predefined inbuilt function defined known as lastIndexOf() which specifies the last occurrence of character or substring present in the string. The method starts working from the last of the string and moves backwards. Now if the ‘fromIndex is specified’ during the function call of lastIndexOf() method, then search for character or substring starts from the ahead of ‘frontIndex’ instead of last of string. int lastIndexOf(int ch) // Returning the last index of occurrence of character in string. int lastIndexOf(int ch, int fromIndex) // Returning the last index looking backwards starting from ‘frontIndex’. int latIndexOf(String str) // Returning the last index of substring named ‘str’ from last of string. int lastIndexOf(String str, int fromIndex) // Returning the last occurrence of substring starting from frontIndex in string. The directory in which inbuilt function is present: java.util.String.lastIndexOf() Return type: Positive Numeric value: Value at which the last occurrence of a character or substring in a string is matched -1 If not matched Approach: Create a class with the name. Declare a variable with a name string and initialize the variable with value as “geeksforgeeks” Now declare another variable with name word and initialize the variable with value as “geeks”. This word is the search word in this scenario. After initializing with the value now we can use the lastIndexOf() method and should pass the string and word as an argument. After following the above steps then compile the program. Once the program is compiled you will get the output. Example 1: Considering where the character or substring is not present in the string then it will return the last index value. Java // Java Program to find the Last // Index of a particular word // in a string // Importing Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // String in which char or // substring to be searched String str = "geeksforgeeks"; // Substring to be searched String word = "geeks"; // Printing last index of char // or substring is found // Printing -1 is not found System.out.println(str.lastIndexOf(word)); }} 8 Example 2: Considering where the character or substring is not present in the string then it will return a ‘-1’ value. Java // Java Program to find the Last// Index of a particular word // in a string // Importing Classes/Filesimport java.util.*;public class GFG { // Main driver method public static void main(String[] args) { // String in which char or // substring to be searched String str = "geeksforgeek"; // Substring to be searched String word = "gfg"; // Printing last index of char // or substring is found // Printing -1 is not found System.out.println(str.lastIndexOf(word)); }} -1 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n05 Nov, 2020" }, { "code": null, "e": 25446, "s": 25237, "text": "To find out the last occurrence of a character or string from a given string across which the substring or character is been searched over and returning the index value of the character or substring is found." }, { "code": null, "e": 25465, "s": 25446, "text": "Real-life Example:" }, { "code": null, "e": 25944, "s": 25465, "text": "Consider an example of a book. The book contains pages where pages contain words. Now if a user wants to figure out the occurrence of a word of his own choice then the reader’s head rebound of question does that word to be searched even exist in the book And if yes, starts flipping out the pages prior to remembering the page where it last occurred because there may be chances that the word would repeat after the page which he updated the last and is done reading the book. " }, { "code": null, "e": 26141, "s": 25944, "text": "Here the set of all the words in the book is referred to as ‘String’ and the word to be searched is referred to as ‘word’ itself. The exact place where the word occurred is referred to as ‘index’." }, { "code": null, "e": 26699, "s": 26141, "text": "Now in Java, there is already an inbuilt method defined in strings over dealing with indexes in it known as indexOf(). It is used in finding out the index of a special character or sub-string itself from a given string. As usual, there are two possibilities, first is when a character or substring is present in the string it returns the index, and if not this function returns ‘-1’ if the character or substring is not present out in the string. -1 is returned in java as in java there is no such concept of negative indexed what is present therein python." }, { "code": null, "e": 27135, "s": 26699, "text": "Similarly, there is also a predefined inbuilt function defined known as lastIndexOf() which specifies the last occurrence of character or substring present in the string. The method starts working from the last of the string and moves backwards. Now if the ‘fromIndex is specified’ during the function call of lastIndexOf() method, then search for character or substring starts from the ahead of ‘frontIndex’ instead of last of string." }, { "code": null, "e": 27227, "s": 27135, "text": "int lastIndexOf(int ch) // Returning the last index of occurrence of character in string. " }, { "code": null, "e": 27342, "s": 27227, "text": "int lastIndexOf(int ch, int fromIndex) // Returning the last index looking backwards starting from ‘frontIndex’. " }, { "code": null, "e": 27445, "s": 27342, "text": "int latIndexOf(String str) // Returning the last index of substring named ‘str’ from last of string. " }, { "code": null, "e": 27570, "s": 27445, "text": "int lastIndexOf(String str, int fromIndex) // Returning the last occurrence of substring starting from frontIndex in string." }, { "code": null, "e": 27622, "s": 27570, "text": "The directory in which inbuilt function is present:" }, { "code": null, "e": 27654, "s": 27622, "text": "java.util.String.lastIndexOf()\n" }, { "code": null, "e": 27667, "s": 27654, "text": "Return type:" }, { "code": null, "e": 27777, "s": 27667, "text": "Positive Numeric value: Value at which the last occurrence of a character or substring in a string is matched" }, { "code": null, "e": 27800, "s": 27777, "text": "-1 If not matched " }, { "code": null, "e": 27810, "s": 27800, "text": "Approach:" }, { "code": null, "e": 27840, "s": 27810, "text": "Create a class with the name." }, { "code": null, "e": 27936, "s": 27840, "text": "Declare a variable with a name string and initialize the variable with value as “geeksforgeeks”" }, { "code": null, "e": 28078, "s": 27936, "text": "Now declare another variable with name word and initialize the variable with value as “geeks”. This word is the search word in this scenario." }, { "code": null, "e": 28204, "s": 28078, "text": "After initializing with the value now we can use the lastIndexOf() method and should pass the string and word as an argument." }, { "code": null, "e": 28262, "s": 28204, "text": "After following the above steps then compile the program." }, { "code": null, "e": 28318, "s": 28262, "text": "Once the program is compiled you will get the output. " }, { "code": null, "e": 28445, "s": 28318, "text": "Example 1: Considering where the character or substring is not present in the string then it will return the last index value." }, { "code": null, "e": 28450, "s": 28445, "text": "Java" }, { "code": "// Java Program to find the Last // Index of a particular word // in a string // Importing Classes/Filesimport java.util.*; public class GFG { // Main driver method public static void main(String[] args) { // String in which char or // substring to be searched String str = \"geeksforgeeks\"; // Substring to be searched String word = \"geeks\"; // Printing last index of char // or substring is found // Printing -1 is not found System.out.println(str.lastIndexOf(word)); }}", "e": 29008, "s": 28450, "text": null }, { "code": null, "e": 29010, "s": 29008, "text": "8" }, { "code": null, "e": 29130, "s": 29010, "text": "Example 2: Considering where the character or substring is not present in the string then it will return a ‘-1’ value. " }, { "code": null, "e": 29135, "s": 29130, "text": "Java" }, { "code": "// Java Program to find the Last// Index of a particular word // in a string // Importing Classes/Filesimport java.util.*;public class GFG { // Main driver method public static void main(String[] args) { // String in which char or // substring to be searched String str = \"geeksforgeek\"; // Substring to be searched String word = \"gfg\"; // Printing last index of char // or substring is found // Printing -1 is not found System.out.println(str.lastIndexOf(word)); }}", "e": 29689, "s": 29135, "text": null }, { "code": null, "e": 29692, "s": 29689, "text": "-1" }, { "code": null, "e": 29697, "s": 29692, "text": "Java" }, { "code": null, "e": 29711, "s": 29697, "text": "Java Programs" }, { "code": null, "e": 29716, "s": 29711, "text": "Java" }, { "code": null, "e": 29814, "s": 29716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29829, "s": 29814, "text": "Stream In Java" }, { "code": null, "e": 29850, "s": 29829, "text": "Constructors in Java" }, { "code": null, "e": 29869, "s": 29850, "text": "Exceptions in Java" }, { "code": null, "e": 29899, "s": 29869, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29945, "s": 29899, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29971, "s": 29945, "text": "Java Programming Examples" }, { "code": null, "e": 30005, "s": 29971, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 30052, "s": 30005, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 30084, "s": 30052, "text": "How to Iterate HashMap in Java?" } ]
Find next greater number with same set of digits in C++
In this problem, we are given an element N. We need to find the next greater number with the same set of digits. We need to find the smallest number with the same digit which is greater than N. Let’s take an example to understand the problem, N = "92534" 92543 A simple solution to the problem to find the next greater element is by the following approach − Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element. Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element. After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number. After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number. Then sort the remaining subarray and return the output. Then sort the remaining subarray and return the output. Program to illustrate the working of our solution, Live Demo #include <iostream> #include <cstring> #include <algorithm> using namespace std; void findNextGreater(char number[], int n) { int i, j; for (i = n-1; i > 0; i--) if (number[i] > number[i-1]) break; if (i==0) { cout<<"Next number is not possible"; return; } int x = number[i-1], smallest = i; for (j = i+1; j < n; j++) if (number[j] > x && number[j] < number[smallest]) smallest = j; char temp = number[smallest]; number[smallest] = number[i-1]; number[i-1] = temp; sort(number + i, number + n); cout<<number; return; } int main(){ char number[] = "92534"; int n = strlen(number); cout<<"The next number with same set of digits is "; findNextGreater(number, n); return 0; } The next number with same set of digits is 92543
[ { "code": null, "e": 1256, "s": 1062, "text": "In this problem, we are given an element N. We need to find the next greater\nnumber with the same set of digits. We need to find the smallest number with the same digit which is greater than N." }, { "code": null, "e": 1305, "s": 1256, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1317, "s": 1305, "text": "N = \"92534\"" }, { "code": null, "e": 1323, "s": 1317, "text": "92543" }, { "code": null, "e": 1420, "s": 1323, "text": "A simple solution to the problem to find the next greater element is by the\nfollowing approach −" }, { "code": null, "e": 1560, "s": 1420, "text": "Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element." }, { "code": null, "e": 1700, "s": 1560, "text": "Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element." }, { "code": null, "e": 1825, "s": 1700, "text": "After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number." }, { "code": null, "e": 1950, "s": 1825, "text": "After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number." }, { "code": null, "e": 2006, "s": 1950, "text": "Then sort the remaining subarray and return the output." }, { "code": null, "e": 2062, "s": 2006, "text": "Then sort the remaining subarray and return the output." }, { "code": null, "e": 2113, "s": 2062, "text": "Program to illustrate the working of our solution," }, { "code": null, "e": 2124, "s": 2113, "text": " Live Demo" }, { "code": null, "e": 2890, "s": 2124, "text": "#include <iostream>\n#include <cstring>\n#include <algorithm>\nusing namespace std;\nvoid findNextGreater(char number[], int n) {\n int i, j;\n for (i = n-1; i > 0; i--)\n if (number[i] > number[i-1])\n break;\n if (i==0) {\n cout<<\"Next number is not possible\";\n return;\n }\n int x = number[i-1], smallest = i;\n for (j = i+1; j < n; j++)\n if (number[j] > x && number[j] < number[smallest])\n smallest = j;\n char temp = number[smallest];\n number[smallest] = number[i-1];\n number[i-1] = temp;\n sort(number + i, number + n);\n cout<<number;\n return;\n}\nint main(){\n char number[] = \"92534\";\n int n = strlen(number);\n cout<<\"The next number with same set of digits is \";\n findNextGreater(number, n);\n return 0;\n}" }, { "code": null, "e": 2939, "s": 2890, "text": "The next number with same set of digits is 92543" } ]