title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to handle multiple input field in react form with a single function?
30 Sep, 2020 There are two types of form, one is uncontrolled form and another one is controlled form. In uncontrolled form values of the input field stored in DOM and whenever we want to use the values we have to reach the DOM and pull out the values of each input field. Now in control, we do not allow to store the value in DOM but values are store as a state of react component and updated dynamically with user interaction. For this, we use the event handler onChange and executes a callback that updates the state values. Now for a single input field, we use one handleChange callback but if the input fields are multiple then we have to create multiple handleChange callbacks to update the state of each input field. Fortunately, this is not the case. JavaScript provides us with ES2015 modern syntax to execute this kind of complicated work in a simple manner. ES2015 introduced the ability to create objects with dynamic keys based on JavaScript expression called as computed property names. We use computed property names to update the state of all the input fields based on the name attribute of inputs. Syntax : const obj = { : value } Example 1: This example shows how to handle multiple form input fields with a single handleChange function. index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js : App component renders single Form component onlyJavascriptJavascriptimport React from 'react'import Form from './Form' //Functional componentconst App = () => { //render single App component return( <Form /> )} export default App App.js : App component renders single Form component only Javascript import React from 'react'import Form from './Form' //Functional componentconst App = () => { //render single App component return( <Form /> )} export default App Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form.JavascriptJavascriptimport React,{ Component } from 'react' class Form extends Component{ constructor(props){ super(props) this.state = { email:'',name:'', age:null, address:'',phoneNo:''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page refresh handleSubmit(event){ const { email, name, age, address, phoneNo } = this.state event.preventDefault() alert(` ____Your Details____\n Email : ${email} Name : ${name} Age : ${age} Address : ${address} Phone No : ${phoneNo} `) } // Method causes to store all the values of the // input field in react state single method handle // input changes of all the input field using ES6 // javascript feature computed property names handleChange(event){ this.setState({ // Computed property names // keys of the objects are computed dynamically [event.target.name] : event.target.value }) } // Return a controlled form i.e. values of the // input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='email'>Email</label> <input name='email' placeholder='Email' value = {this.state.email} onChange={this.handleChange} /> </div> <div> <label htmlFor='name'>Name</label> <input name='name' placeholder='Name' value={this.state.name} onChange={this.handleChange} /> </div> <div> <label htmlFor='age'>Age</label> <input name='age' placeholder='Age' value={this.state.age} onChange={this.handleChange} /> </div> <div> <label htmlFor='address'>Address</label> <input name='address' placeholder='Address' value={this.state.address} onChange={this.handleChange} /> </div> <div> <label htmlFor='phoneNo'>Phone Number</label> <input name='phoneNo' placeholder='Phone No' value={this.state.phoneNo} onChange={this.handleChange} /> </div> <div> <button>Create Account</button> </div> </form> ) }} export default Form Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form. Javascript import React,{ Component } from 'react' class Form extends Component{ constructor(props){ super(props) this.state = { email:'',name:'', age:null, address:'',phoneNo:''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page refresh handleSubmit(event){ const { email, name, age, address, phoneNo } = this.state event.preventDefault() alert(` ____Your Details____\n Email : ${email} Name : ${name} Age : ${age} Address : ${address} Phone No : ${phoneNo} `) } // Method causes to store all the values of the // input field in react state single method handle // input changes of all the input field using ES6 // javascript feature computed property names handleChange(event){ this.setState({ // Computed property names // keys of the objects are computed dynamically [event.target.name] : event.target.value }) } // Return a controlled form i.e. values of the // input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='email'>Email</label> <input name='email' placeholder='Email' value = {this.state.email} onChange={this.handleChange} /> </div> <div> <label htmlFor='name'>Name</label> <input name='name' placeholder='Name' value={this.state.name} onChange={this.handleChange} /> </div> <div> <label htmlFor='age'>Age</label> <input name='age' placeholder='Age' value={this.state.age} onChange={this.handleChange} /> </div> <div> <label htmlFor='address'>Address</label> <input name='address' placeholder='Address' value={this.state.address} onChange={this.handleChange} /> </div> <div> <label htmlFor='phoneNo'>Phone Number</label> <input name='phoneNo' placeholder='Phone No' value={this.state.phoneNo} onChange={this.handleChange} /> </div> <div> <button>Create Account</button> </div> </form> ) }} export default Form Output : Example 2 : index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js: App component renders a single BoxList component onlyJavascriptJavascriptimport React from 'react';import BoxList from './BoxList' const App = () => { //App renders single BoxList component return( <BoxList /> )} export default App App.js: App component renders a single BoxList component only Javascript import React from 'react';import BoxList from './BoxList' const App = () => { //App renders single BoxList component return( <BoxList /> )} export default App BoxList.js: It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of boxes. We map over each box of state ‘boxes’ and for eachbox we render a ‘Box’ component. BoxList component also contains methods create that is responsible to create box based on given properties. BoxComponent also renders ‘NewBoxForm’ that shows a form to the user to enter the height, width, and background color of the box they want to create. BoxList component passes the create a method to NewBoxForm component as a prop to each ‘Box’ component as a prop. These components are then invoked the given methods at right time according to the user interactions with the app.JavascriptJavascriptimport React, { Component } from 'react'import { v4 as uuid } from 'uuid'import NewBoxForm from './NewBoxForm'import Box from './Box' class BoxList extends Component{ constructor(props){ super(props) // Single state boxes initialized with empty array // it contains all the created boxes and their properties this.state = { boxes : [] } this.createBox = this.createBox.bind(this) } // create new box and added it to boxes state createBox(attrs){ const newBox = { ...attrs, id : uuid()} this.setState({ boxes : [...this.state.boxes, newBox] }) } // Map over each box in boxes state and render a // Box component for each passing its property as // props and method is also passed as props which gets // called by the handler callback of Box component renderBoxes(){ return this.state.boxes.map(box => ( <Box key={box.id} attrs={box} /> )) } render(){ return( <div> <h1>Make New Color Boxes!</h1> {/* component to create form and passes create method as */} <NewBoxForm create={this.createBox}/> {this.renderBoxes()} </div> ) }} export default BoxList BoxList.js: It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of boxes. We map over each box of state ‘boxes’ and for eachbox we render a ‘Box’ component. BoxList component also contains methods create that is responsible to create box based on given properties. BoxComponent also renders ‘NewBoxForm’ that shows a form to the user to enter the height, width, and background color of the box they want to create. BoxList component passes the create a method to NewBoxForm component as a prop to each ‘Box’ component as a prop. These components are then invoked the given methods at right time according to the user interactions with the app. Javascript import React, { Component } from 'react'import { v4 as uuid } from 'uuid'import NewBoxForm from './NewBoxForm'import Box from './Box' class BoxList extends Component{ constructor(props){ super(props) // Single state boxes initialized with empty array // it contains all the created boxes and their properties this.state = { boxes : [] } this.createBox = this.createBox.bind(this) } // create new box and added it to boxes state createBox(attrs){ const newBox = { ...attrs, id : uuid()} this.setState({ boxes : [...this.state.boxes, newBox] }) } // Map over each box in boxes state and render a // Box component for each passing its property as // props and method is also passed as props which gets // called by the handler callback of Box component renderBoxes(){ return this.state.boxes.map(box => ( <Box key={box.id} attrs={box} /> )) } render(){ return( <div> <h1>Make New Color Boxes!</h1> {/* component to create form and passes create method as */} <NewBoxForm create={this.createBox}/> {this.renderBoxes()} </div> ) }} export default BoxList NewBoxForm.js: This component is responsible to show the form to users to enter the properties of the box they wanted to create. The form is a controlled form i.e. it stores the values of the input field in states and updates it in real-time according to user interaction with input fields of the form. It invoked handle submit callback after submitting the form which in return invoke the create method of BoxList component passing the form values to create the box.JavascriptJavascriptimport React,{ Component } from 'react' class NewBoxForm extends Component{ constructor(props){ super(props) this.state = { height : 0, width : 0, bc : ''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page // refresh and call create method of BoxList // component to create new box handleSubmit(event){ event.preventDefault() this.props.create(this.state) this.setState({ height : 0, width : 0, bc : ''}) } // Method causes to store all the values of the // input field in react state using single method // handleChanges of all the input field // using ES6 javascript feature computed property names handleChange(event){ this.setState({ [event.target.name] : event.target.value }) } // return a form using which we add box properties // to create Boxes. It is controlled form i.e. values // of the input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='height'>Height</label> <input name='height' placeholder='Height' value = {this.state.height} onChange={this.handleChange} /> </div> <div> <label htmlFor='width'>Width</label> <input name='width' placeholder='Width' value={this.state.width} onChange={this.handleChange} /> </div> <div> <label htmlFor='bc'>Background Color</label> <input name='bc' placeholder='Background Color' value={this.state.bc} onChange={this.handleChange} /> </div> <div> <button>Add a new Box!</button> </div> </form> ) }} export default NewBoxForm NewBoxForm.js: This component is responsible to show the form to users to enter the properties of the box they wanted to create. The form is a controlled form i.e. it stores the values of the input field in states and updates it in real-time according to user interaction with input fields of the form. It invoked handle submit callback after submitting the form which in return invoke the create method of BoxList component passing the form values to create the box. Javascript import React,{ Component } from 'react' class NewBoxForm extends Component{ constructor(props){ super(props) this.state = { height : 0, width : 0, bc : ''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page // refresh and call create method of BoxList // component to create new box handleSubmit(event){ event.preventDefault() this.props.create(this.state) this.setState({ height : 0, width : 0, bc : ''}) } // Method causes to store all the values of the // input field in react state using single method // handleChanges of all the input field // using ES6 javascript feature computed property names handleChange(event){ this.setState({ [event.target.name] : event.target.value }) } // return a form using which we add box properties // to create Boxes. It is controlled form i.e. values // of the input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='height'>Height</label> <input name='height' placeholder='Height' value = {this.state.height} onChange={this.handleChange} /> </div> <div> <label htmlFor='width'>Width</label> <input name='width' placeholder='Width' value={this.state.width} onChange={this.handleChange} /> </div> <div> <label htmlFor='bc'>Background Color</label> <input name='bc' placeholder='Background Color' value={this.state.bc} onChange={this.handleChange} /> </div> <div> <button>Add a new Box!</button> </div> </form> ) }} export default NewBoxForm Box.js: It is responsible to show each box with its proper height, width, color set in the background. JavascriptJavascriptimport React, { Component } from 'react' class Box extends Component { render(){ const { height, width, bc } = this.props.attrs const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc} return( <div style={style} /> ) }} export default Box Box.js: It is responsible to show each box with its proper height, width, color set in the background. Javascript import React, { Component } from 'react' class Box extends Component { render(){ const { height, width, bc } = this.props.attrs const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc} return( <div style={style} /> ) }} export default Box Output : react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2020" }, { "code": null, "e": 909, "s": 52, "text": "There are two types of form, one is uncontrolled form and another one is controlled form. In uncontrolled form values of the input field stored in DOM and whenever we want to use the values we have to reach the DOM and pull out the values of each input field. Now in control, we do not allow to store the value in DOM but values are store as a state of react component and updated dynamically with user interaction. For this, we use the event handler onChange and executes a callback that updates the state values. Now for a single input field, we use one handleChange callback but if the input fields are multiple then we have to create multiple handleChange callbacks to update the state of each input field. Fortunately, this is not the case. JavaScript provides us with ES2015 modern syntax to execute this kind of complicated work in a simple manner." }, { "code": null, "e": 1156, "s": 909, "text": "ES2015 introduced the ability to create objects with dynamic keys based on JavaScript expression called as computed property names. We use computed property names to update the state of all the input fields based on the name attribute of inputs. " }, { "code": null, "e": 1166, "s": 1156, "text": "Syntax : " }, { "code": null, "e": 1194, "s": 1166, "text": "const obj = {\n : value\n}\n" }, { "code": null, "e": 1302, "s": 1194, "text": "Example 1: This example shows how to handle multiple form input fields with a single handleChange function." }, { "code": null, "e": 1471, "s": 1302, "text": "index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))" }, { "code": null, "e": 1481, "s": 1471, "text": "index.js:" }, { "code": null, "e": 1492, "s": 1481, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 1632, "s": 1492, "text": null }, { "code": null, "e": 1880, "s": 1632, "text": "App.js : App component renders single Form component onlyJavascriptJavascriptimport React from 'react'import Form from './Form' //Functional componentconst App = () => { //render single App component return( <Form /> )} export default App" }, { "code": null, "e": 1939, "s": 1880, "text": "App.js : App component renders single Form component only" }, { "code": null, "e": 1950, "s": 1939, "text": "Javascript" }, { "code": "import React from 'react'import Form from './Form' //Functional componentconst App = () => { //render single App component return( <Form /> )} export default App", "e": 2120, "s": 1950, "text": null }, { "code": null, "e": 4750, "s": 2120, "text": "Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form.JavascriptJavascriptimport React,{ Component } from 'react' class Form extends Component{ constructor(props){ super(props) this.state = { email:'',name:'', age:null, address:'',phoneNo:''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page refresh handleSubmit(event){ const { email, name, age, address, phoneNo } = this.state event.preventDefault() alert(` ____Your Details____\\n Email : ${email} Name : ${name} Age : ${age} Address : ${address} Phone No : ${phoneNo} `) } // Method causes to store all the values of the // input field in react state single method handle // input changes of all the input field using ES6 // javascript feature computed property names handleChange(event){ this.setState({ // Computed property names // keys of the objects are computed dynamically [event.target.name] : event.target.value }) } // Return a controlled form i.e. values of the // input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='email'>Email</label> <input name='email' placeholder='Email' value = {this.state.email} onChange={this.handleChange} /> </div> <div> <label htmlFor='name'>Name</label> <input name='name' placeholder='Name' value={this.state.name} onChange={this.handleChange} /> </div> <div> <label htmlFor='age'>Age</label> <input name='age' placeholder='Age' value={this.state.age} onChange={this.handleChange} /> </div> <div> <label htmlFor='address'>Address</label> <input name='address' placeholder='Address' value={this.state.address} onChange={this.handleChange} /> </div> <div> <label htmlFor='phoneNo'>Phone Number</label> <input name='phoneNo' placeholder='Phone No' value={this.state.phoneNo} onChange={this.handleChange} /> </div> <div> <button>Create Account</button> </div> </form> ) }} export default Form" }, { "code": null, "e": 4868, "s": 4750, "text": "Form.js: Form component renders a form and contains all the logic to make it controlled form and submitting the form." }, { "code": null, "e": 4879, "s": 4868, "text": "Javascript" }, { "code": "import React,{ Component } from 'react' class Form extends Component{ constructor(props){ super(props) this.state = { email:'',name:'', age:null, address:'',phoneNo:''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page refresh handleSubmit(event){ const { email, name, age, address, phoneNo } = this.state event.preventDefault() alert(` ____Your Details____\\n Email : ${email} Name : ${name} Age : ${age} Address : ${address} Phone No : ${phoneNo} `) } // Method causes to store all the values of the // input field in react state single method handle // input changes of all the input field using ES6 // javascript feature computed property names handleChange(event){ this.setState({ // Computed property names // keys of the objects are computed dynamically [event.target.name] : event.target.value }) } // Return a controlled form i.e. values of the // input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='email'>Email</label> <input name='email' placeholder='Email' value = {this.state.email} onChange={this.handleChange} /> </div> <div> <label htmlFor='name'>Name</label> <input name='name' placeholder='Name' value={this.state.name} onChange={this.handleChange} /> </div> <div> <label htmlFor='age'>Age</label> <input name='age' placeholder='Age' value={this.state.age} onChange={this.handleChange} /> </div> <div> <label htmlFor='address'>Address</label> <input name='address' placeholder='Address' value={this.state.address} onChange={this.handleChange} /> </div> <div> <label htmlFor='phoneNo'>Phone Number</label> <input name='phoneNo' placeholder='Phone No' value={this.state.phoneNo} onChange={this.handleChange} /> </div> <div> <button>Create Account</button> </div> </form> ) }} export default Form", "e": 7372, "s": 4879, "text": null }, { "code": null, "e": 7381, "s": 7372, "text": "Output :" }, { "code": null, "e": 7394, "s": 7381, "text": "Example 2 : " }, { "code": null, "e": 7563, "s": 7394, "text": "index.js:JavascriptJavascriptimport React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))" }, { "code": null, "e": 7573, "s": 7563, "text": "index.js:" }, { "code": null, "e": 7584, "s": 7573, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 7724, "s": 7584, "text": null }, { "code": null, "e": 7972, "s": 7724, "text": "App.js: App component renders a single BoxList component onlyJavascriptJavascriptimport React from 'react';import BoxList from './BoxList' const App = () => { //App renders single BoxList component return( <BoxList /> )} export default App" }, { "code": null, "e": 8034, "s": 7972, "text": "App.js: App component renders a single BoxList component only" }, { "code": null, "e": 8045, "s": 8034, "text": "Javascript" }, { "code": "import React from 'react';import BoxList from './BoxList' const App = () => { //App renders single BoxList component return( <BoxList /> )} export default App", "e": 8212, "s": 8045, "text": null }, { "code": null, "e": 10109, "s": 8212, "text": "BoxList.js: It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of boxes. We map over each box of state ‘boxes’ and for eachbox we render a ‘Box’ component. BoxList component also contains methods create that is responsible to create box based on given properties. BoxComponent also renders ‘NewBoxForm’ that shows a form to the user to enter the height, width, and background color of the box they want to create. BoxList component passes the create a method to NewBoxForm component as a prop to each ‘Box’ component as a prop. These components are then invoked the given methods at right time according to the user interactions with the app.JavascriptJavascriptimport React, { Component } from 'react'import { v4 as uuid } from 'uuid'import NewBoxForm from './NewBoxForm'import Box from './Box' class BoxList extends Component{ constructor(props){ super(props) // Single state boxes initialized with empty array // it contains all the created boxes and their properties this.state = { boxes : [] } this.createBox = this.createBox.bind(this) } // create new box and added it to boxes state createBox(attrs){ const newBox = { ...attrs, id : uuid()} this.setState({ boxes : [...this.state.boxes, newBox] }) } // Map over each box in boxes state and render a // Box component for each passing its property as // props and method is also passed as props which gets // called by the handler callback of Box component renderBoxes(){ return this.state.boxes.map(box => ( <Box key={box.id} attrs={box} /> )) } render(){ return( <div> <h1>Make New Color Boxes!</h1> {/* component to create form and passes create method as */} <NewBoxForm create={this.createBox}/> {this.renderBoxes()} </div> ) }} export default BoxList" }, { "code": null, "e": 10815, "s": 10109, "text": "BoxList.js: It contains all the behind the logic. It is a stateful component. There is a single state that contains an array of boxes. We map over each box of state ‘boxes’ and for eachbox we render a ‘Box’ component. BoxList component also contains methods create that is responsible to create box based on given properties. BoxComponent also renders ‘NewBoxForm’ that shows a form to the user to enter the height, width, and background color of the box they want to create. BoxList component passes the create a method to NewBoxForm component as a prop to each ‘Box’ component as a prop. These components are then invoked the given methods at right time according to the user interactions with the app." }, { "code": null, "e": 10826, "s": 10815, "text": "Javascript" }, { "code": "import React, { Component } from 'react'import { v4 as uuid } from 'uuid'import NewBoxForm from './NewBoxForm'import Box from './Box' class BoxList extends Component{ constructor(props){ super(props) // Single state boxes initialized with empty array // it contains all the created boxes and their properties this.state = { boxes : [] } this.createBox = this.createBox.bind(this) } // create new box and added it to boxes state createBox(attrs){ const newBox = { ...attrs, id : uuid()} this.setState({ boxes : [...this.state.boxes, newBox] }) } // Map over each box in boxes state and render a // Box component for each passing its property as // props and method is also passed as props which gets // called by the handler callback of Box component renderBoxes(){ return this.state.boxes.map(box => ( <Box key={box.id} attrs={box} /> )) } render(){ return( <div> <h1>Make New Color Boxes!</h1> {/* component to create form and passes create method as */} <NewBoxForm create={this.createBox}/> {this.renderBoxes()} </div> ) }} export default BoxList", "e": 11998, "s": 10826, "text": null }, { "code": null, "e": 14429, "s": 11998, "text": "NewBoxForm.js: This component is responsible to show the form to users to enter the properties of the box they wanted to create. The form is a controlled form i.e. it stores the values of the input field in states and updates it in real-time according to user interaction with input fields of the form. It invoked handle submit callback after submitting the form which in return invoke the create method of BoxList component passing the form values to create the box.JavascriptJavascriptimport React,{ Component } from 'react' class NewBoxForm extends Component{ constructor(props){ super(props) this.state = { height : 0, width : 0, bc : ''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page // refresh and call create method of BoxList // component to create new box handleSubmit(event){ event.preventDefault() this.props.create(this.state) this.setState({ height : 0, width : 0, bc : ''}) } // Method causes to store all the values of the // input field in react state using single method // handleChanges of all the input field // using ES6 javascript feature computed property names handleChange(event){ this.setState({ [event.target.name] : event.target.value }) } // return a form using which we add box properties // to create Boxes. It is controlled form i.e. values // of the input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='height'>Height</label> <input name='height' placeholder='Height' value = {this.state.height} onChange={this.handleChange} /> </div> <div> <label htmlFor='width'>Width</label> <input name='width' placeholder='Width' value={this.state.width} onChange={this.handleChange} /> </div> <div> <label htmlFor='bc'>Background Color</label> <input name='bc' placeholder='Background Color' value={this.state.bc} onChange={this.handleChange} /> </div> <div> <button>Add a new Box!</button> </div> </form> ) }} export default NewBoxForm" }, { "code": null, "e": 14897, "s": 14429, "text": "NewBoxForm.js: This component is responsible to show the form to users to enter the properties of the box they wanted to create. The form is a controlled form i.e. it stores the values of the input field in states and updates it in real-time according to user interaction with input fields of the form. It invoked handle submit callback after submitting the form which in return invoke the create method of BoxList component passing the form values to create the box." }, { "code": null, "e": 14908, "s": 14897, "text": "Javascript" }, { "code": "import React,{ Component } from 'react' class NewBoxForm extends Component{ constructor(props){ super(props) this.state = { height : 0, width : 0, bc : ''} this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } // Form submitting logic, prevent default page // refresh and call create method of BoxList // component to create new box handleSubmit(event){ event.preventDefault() this.props.create(this.state) this.setState({ height : 0, width : 0, bc : ''}) } // Method causes to store all the values of the // input field in react state using single method // handleChanges of all the input field // using ES6 javascript feature computed property names handleChange(event){ this.setState({ [event.target.name] : event.target.value }) } // return a form using which we add box properties // to create Boxes. It is controlled form i.e. values // of the input field not stored in DOM values are exist // in react component itself as state render(){ return( <form onSubmit={this.handleSubmit}> <div> <label htmlFor='height'>Height</label> <input name='height' placeholder='Height' value = {this.state.height} onChange={this.handleChange} /> </div> <div> <label htmlFor='width'>Width</label> <input name='width' placeholder='Width' value={this.state.width} onChange={this.handleChange} /> </div> <div> <label htmlFor='bc'>Background Color</label> <input name='bc' placeholder='Background Color' value={this.state.bc} onChange={this.handleChange} /> </div> <div> <button>Add a new Box!</button> </div> </form> ) }} export default NewBoxForm", "e": 16852, "s": 14908, "text": null }, { "code": null, "e": 17257, "s": 16852, "text": "Box.js: It is responsible to show each box with its proper height, width, color set in the background. JavascriptJavascriptimport React, { Component } from 'react' class Box extends Component { render(){ const { height, width, bc } = this.props.attrs const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc} return( <div style={style} /> ) }} export default Box" }, { "code": null, "e": 17361, "s": 17257, "text": "Box.js: It is responsible to show each box with its proper height, width, color set in the background. " }, { "code": null, "e": 17372, "s": 17361, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class Box extends Component { render(){ const { height, width, bc } = this.props.attrs const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc} return( <div style={style} /> ) }} export default Box", "e": 17654, "s": 17372, "text": null }, { "code": null, "e": 17663, "s": 17654, "text": "Output :" }, { "code": null, "e": 17672, "s": 17663, "text": "react-js" }, { "code": null, "e": 17689, "s": 17672, "text": "Web Technologies" }, { "code": null, "e": 17787, "s": 17689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17820, "s": 17787, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 17882, "s": 17820, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 17943, "s": 17882, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 17993, "s": 17943, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 18036, "s": 17993, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 18076, "s": 18036, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 18100, "s": 18076, "text": "REST API (Introduction)" }, { "code": null, "e": 18133, "s": 18100, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 18193, "s": 18133, "text": "How to set the default value for an HTML <select> element ?" } ]
HTML | <tr> bgcolor Attribute
26 Jun, 2019 The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Syntax: <tr bgcolor= "color_name | hex_number | rgb_number"> Attribute Values: color_name: It sets the background color by using the color name. For example “red”. hex_number: It sets the background color by using the color hex code. For example “#0000ff”. rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” . Example: <!DOCTYPE html><html> <head> <title>HTML tr bgcolor Attribute</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML tr bgcolor Attribute</h2> <table width="500" border="1"> <tr bgcolor="green"> <th>Name</th> <th>Expenses</th> </tr> <tr bgcolor="yellow"> <td>BITTU</td> <td>2500.00</td> </tr> <tr bgcolor="red"> <td>RAKESH</td> <td>1400.00</td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <tr> bgcolor attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type 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": "\n26 Jun, 2019" }, { "code": null, "e": 147, "s": 28, "text": "The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5." }, { "code": null, "e": 155, "s": 147, "text": "Syntax:" }, { "code": null, "e": 208, "s": 155, "text": "<tr bgcolor= \"color_name | hex_number | rgb_number\">" }, { "code": null, "e": 226, "s": 208, "text": "Attribute Values:" }, { "code": null, "e": 311, "s": 226, "text": "color_name: It sets the background color by using the color name. For example “red”." }, { "code": null, "e": 404, "s": 311, "text": "hex_number: It sets the background color by using the color hex code. For example “#0000ff”." }, { "code": null, "e": 500, "s": 404, "text": "rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” ." }, { "code": null, "e": 509, "s": 500, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML tr bgcolor Attribute</title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML tr bgcolor Attribute</h2> <table width=\"500\" border=\"1\"> <tr bgcolor=\"green\"> <th>Name</th> <th>Expenses</th> </tr> <tr bgcolor=\"yellow\"> <td>BITTU</td> <td>2500.00</td> </tr> <tr bgcolor=\"red\"> <td>RAKESH</td> <td>1400.00</td> </tr> </table></body> </html>", "e": 1017, "s": 509, "text": null }, { "code": null, "e": 1025, "s": 1017, "text": "Output:" }, { "code": null, "e": 1116, "s": 1025, "text": "Supported Browsers: The browser supported by HTML <tr> bgcolor attribute are listed below:" }, { "code": null, "e": 1130, "s": 1116, "text": "Google Chrome" }, { "code": null, "e": 1148, "s": 1130, "text": "Internet Explorer" }, { "code": null, "e": 1156, "s": 1148, "text": "Firefox" }, { "code": null, "e": 1163, "s": 1156, "text": "Safari" }, { "code": null, "e": 1169, "s": 1163, "text": "Opera" }, { "code": null, "e": 1185, "s": 1169, "text": "HTML-Attributes" }, { "code": null, "e": 1190, "s": 1185, "text": "HTML" }, { "code": null, "e": 1207, "s": 1190, "text": "Web Technologies" }, { "code": null, "e": 1212, "s": 1207, "text": "HTML" }, { "code": null, "e": 1310, "s": 1212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1358, "s": 1310, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1382, "s": 1358, "text": "REST API (Introduction)" }, { "code": null, "e": 1432, "s": 1382, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1469, "s": 1432, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1497, "s": 1469, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1530, "s": 1497, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1591, "s": 1530, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1634, "s": 1591, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1706, "s": 1634, "text": "Differences between Functional Components and Class Components in React" } ]
Data encryption standard (DES) | Set 1
15 May, 2022 Data encryption standard (DES) has been found vulnerable to very powerful attacks and therefore, the popularity of DES has been found slightly on the decline. DES is a block cipher and encrypts data in blocks of size of 64 bits each, which means 64 bits of plain text go as the input to DES, which produces 64 bits of ciphertext. The same algorithm and key are used for encryption and decryption, with minor differences. The key length is 56 bits. The basic idea is shown in the figure. We have mentioned that DES uses a 56-bit key. Actually, the initial key consists of 64 bits. However, before the DES process even starts, every 8th bit of the key is discarded to produce a 56-bit key. That is bit positions 8, 16, 24, 32, 40, 48, 56, and 64 are discarded. Thus, the discarding of every 8th bit of the key produces a 56-bit key from the original 64-bit key.DES is based on the two fundamental attributes of cryptography: substitution (also called confusion) and transposition (also called diffusion). DES consists of 16 steps, each of which is called a round. Each round performs the steps of substitution and transposition. Let us now discuss the broad-level steps in DES. In the first step, the 64-bit plain text block is handed over to an initial Permutation (IP) function.The initial permutation is performed on plain text.Next, the initial permutation (IP) produces two halves of the permuted block; saying Left Plain Text (LPT) and Right Plain Text (RPT).Now each LPT and RPT go through 16 rounds of the encryption process.In the end, LPT and RPT are rejoined and a Final Permutation (FP) is performed on the combined blockThe result of this process produces 64-bit ciphertext. In the first step, the 64-bit plain text block is handed over to an initial Permutation (IP) function. The initial permutation is performed on plain text. Next, the initial permutation (IP) produces two halves of the permuted block; saying Left Plain Text (LPT) and Right Plain Text (RPT). Now each LPT and RPT go through 16 rounds of the encryption process. In the end, LPT and RPT are rejoined and a Final Permutation (FP) is performed on the combined block The result of this process produces 64-bit ciphertext. Initial Permutation (IP): As we have noted, the initial permutation (IP) happens only once and it happens before the first round. It suggests how the transposition in IP should proceed, as shown in the figure. For example, it says that the IP replaces the first bit of the original plain text block with the 58th bit of the original plain text, the second bit with the 50th bit of the original plain text block, and so on. This is nothing but jugglery of bit positions of the original plain text block. the same rule applies to all the other bit positions shown in the figure. As we have noted after IP is done, the resulting 64-bit permuted text block is divided into two half blocks. Each half-block consists of 32 bits, and each of the 16 rounds, in turn, consists of the broad level steps outlined in the figure. Step-1: Key transformation: We have noted initial 64-bit key is transformed into a 56-bit key by discarding every 8th bit of the initial key. Thus, for each a 56-bit key is available. From this 56-bit key, a different 48-bit Sub Key is generated during each round using a process called key transformation. For this, the 56-bit key is divided into two halves, each of 28 bits. These halves are circularly shifted left by one or two positions, depending on the round. For example, if the round numbers 1, 2, 9, or 16 the shift is done by only one position for other rounds, the circular shift is done by two positions. The number of key bits shifted per round is shown in the figure. After an appropriate shift, 48 of the 56 bits are selected. for selecting 48 of the 56 bits the table is shown in the figure given below. For instance, after the shift, bit number 14 moves to the first position, bit number 17 moves to the second position, and so on. If we observe the table carefully, we will realize that it contains only 48-bit positions. Bit number 18 is discarded (we will not find it in the table), like 7 others, to reduce a 56-bit key to a 48-bit key. Since the key transformation process involves permutation as well as a selection of a 48-bit subset of the original 56-bit key it is called Compression Permutation. Because of this compression permutation technique, a different subset of key bits is used in each round. That makes DES not easy to crack. Step-2: Expansion Permutation: Recall that after the initial permutation, we had two 32-bit plain text areas called Left Plain Text(LPT) and Right Plain Text(RPT). During the expansion permutation, the RPT is expanded from 32 bits to 48 bits. Bits are permuted as well hence called expansion permutation. This happens as the 32-bit RPT is divided into 8 blocks, with each block consisting of 4 bits. Then, each 4-bit block of the previous step is then expanded to a corresponding 6-bit block, i.e., per 4-bit block, 2 more bits are added. This process results in expansion as well as a permutation of the input bit while creating output. The key transformation process compresses the 56-bit key to 48 bits. Then the expansion permutation process expands the 32-bit RPT to 48-bits. Now the 48-bit key is XOR with 48-bit RPT and the resulting output is given to the next step, which is the S-Box substitution. C++ Java Python #include <bits/stdc++.h>using namespace std;string hex2bin(string s){ // hexadecimal to binary conversion unordered_map<char, string> mp; mp['0'] = "0000"; mp['1'] = "0001"; mp['2'] = "0010"; mp['3'] = "0011"; mp['4'] = "0100"; mp['5'] = "0101"; mp['6'] = "0110"; mp['7'] = "0111"; mp['8'] = "1000"; mp['9'] = "1001"; mp['A'] = "1010"; mp['B'] = "1011"; mp['C'] = "1100"; mp['D'] = "1101"; mp['E'] = "1110"; mp['F'] = "1111"; string bin = ""; for (int i = 0; i < s.size(); i++) { bin += mp[s[i]]; } return bin;}string bin2hex(string s){ // binary to hexadecimal conversion unordered_map<string, string> mp; mp["0000"] = "0"; mp["0001"] = "1"; mp["0010"] = "2"; mp["0011"] = "3"; mp["0100"] = "4"; mp["0101"] = "5"; mp["0110"] = "6"; mp["0111"] = "7"; mp["1000"] = "8"; mp["1001"] = "9"; mp["1010"] = "A"; mp["1011"] = "B"; mp["1100"] = "C"; mp["1101"] = "D"; mp["1110"] = "E"; mp["1111"] = "F"; string hex = ""; for (int i = 0; i < s.length(); i += 4) { string ch = ""; ch += s[i]; ch += s[i + 1]; ch += s[i + 2]; ch += s[i + 3]; hex += mp[ch]; } return hex;} string permute(string k, int* arr, int n){ string per = ""; for (int i = 0; i < n; i++) { per += k[arr[i] - 1]; } return per;} string shift_left(string k, int shifts){ string s = ""; for (int i = 0; i < shifts; i++) { for (int j = 1; j < 28; j++) { s += k[j]; } s += k[0]; k = s; s = ""; } return k;} string xor_(string a, string b){ string ans = ""; for (int i = 0; i < a.size(); i++) { if (a[i] == b[i]) { ans += "0"; } else { ans += "1"; } } return ans;}string encrypt(string pt, vector<string> rkb, vector<string> rk){ // Hexadecimal to binary pt = hex2bin(pt); // Initial Permutation Table int initial_perm[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; // Initial Permutation pt = permute(pt, initial_perm, 64); cout << "After initial permutation: " << bin2hex(pt) << endl; // Splitting string left = pt.substr(0, 32); string right = pt.substr(32, 32); cout << "After splitting: L0=" << bin2hex(left) << " R0=" << bin2hex(right) << endl; // Expansion D-box Table int exp_d[48] = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; // S-box Table int s[8][4][16] = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }, { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }, { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }, { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }, { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }, { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }, { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }, { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } }; // Straight Permutation Table int per[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; cout << endl; for (int i = 0; i < 16; i++) { // Expansion D-box string right_expanded = permute(right, exp_d, 48); // XOR RoundKey[i] and right_expanded string x = xor_(rkb[i], right_expanded); // S-boxes string op = ""; for (int i = 0; i < 8; i++) { int row = 2 * int(x[i * 6] - '0') + int(x[i * 6 + 5] - '0'); int col = 8 * int(x[i * 6 + 1] - '0') + 4 * int(x[i * 6 + 2] - '0') + 2 * int(x[i * 6 + 3] - '0') + int(x[i * 6 + 4] - '0'); int val = s[i][row][col]; op += char(val / 8 + '0'); val = val % 8; op += char(val / 4 + '0'); val = val % 4; op += char(val / 2 + '0'); val = val % 2; op += char(val + '0'); } // Straight D-box op = permute(op, per, 32); // XOR left and op x = xor_(op, left); left = x; // Swapper if (i != 15) { swap(left, right); } cout << "Round " << i + 1 << " " << bin2hex(left) << " " << bin2hex(right) << " " << rk[i] << endl; } // Combination string combine = left + right; // Final Permutation Table int final_perm[64] = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; // Final Permutation string cipher = bin2hex(permute(combine, final_perm, 64)); return cipher;}int main(){ // pt is plain text string pt, key; /*cout<<"Enter plain text(in hexadecimal): "; cin>>pt; cout<<"Enter key(in hexadecimal): "; cin>>key;*/ pt = "123456ABCD132536"; key = "AABB09182736CCDD"; // Key Generation // Hex to binary key = hex2bin(key); // Parity bit drop table int keyp[56] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; // getting 56 bit key from 64 bit using the parity bits key = permute(key, keyp, 56); // key without parity // Number of bit shifts int shift_table[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // Key- Compression Table int key_comp[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; // Splitting string left = key.substr(0, 28); string right = key.substr(28, 28); vector<string> rkb; // rkb for RoundKeys in binary vector<string> rk; // rk for RoundKeys in hexadecimal for (int i = 0; i < 16; i++) { // Shifting left = shift_left(left, shift_table[i]); right = shift_left(right, shift_table[i]); // Combining string combine = left + right; // Key Compression string RoundKey = permute(combine, key_comp, 48); rkb.push_back(RoundKey); rk.push_back(bin2hex(RoundKey)); } cout << "\nEncryption:\n\n"; string cipher = encrypt(pt, rkb, rk); cout << "\nCipher Text: " << cipher << endl; cout << "\nDecryption\n\n"; reverse(rkb.begin(), rkb.end()); reverse(rk.begin(), rk.end()); string text = encrypt(cipher, rkb, rk); cout << "\nPlain Text: " << text << endl;} import java.util.*; class Main { private static class DES { // CONSTANTS // Initial Permutation Table int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; // Inverse Initial Permutation Table int[] IP1 = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; // first key-hePermutation Table int[] PC1 = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; // second key-Permutation Table int[] PC2 = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; // Expansion D-box Table int[] EP = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; // Straight Permutation Table int[] P = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; // S-box Table int[][][] sbox = { { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 }, { 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 }, { 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } }, { { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 }, { 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 }, { 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } }, { { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }, { 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 }, { 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 }, { 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } }, { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }, { 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 }, { 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 }, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } }, { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }, { 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 }, { 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 }, { 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } }, { { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }, { 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 }, { 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 }, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } }, { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }, { 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 }, { 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 }, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } }, { { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 }, { 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 }, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } } }; int[] shiftBits = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // hexadecimal to binary conversion String hextoBin(String input) { int n = input.length() * 4; input = Long.toBinaryString( Long.parseUnsignedLong(input, 16)); while (input.length() < n) input = "0" + input; return input; } // binary to hexadecimal conversion String binToHex(String input) { int n = (int)input.length() / 4; input = Long.toHexString( Long.parseUnsignedLong(input, 2)); while (input.length() < n) input = "0" + input; return input; } // per-mutate input hexadecimal // according to specified sequence String permutation(int[] sequence, String input) { String output = ""; input = hextoBin(input); for (int i = 0; i < sequence.length; i++) output += input.charAt(sequence[i] - 1); output = binToHex(output); return output; } // xor 2 hexadecimal strings String xor(String a, String b) { // hexadecimal to decimal(base 10) long t_a = Long.parseUnsignedLong(a, 16); // hexadecimal to decimal(base 10) long t_b = Long.parseUnsignedLong(b, 16); // xor t_a = t_a ^ t_b; // decimal to hexadecimal a = Long.toHexString(t_a); // prepend 0's to maintain length while (a.length() < b.length()) a = "0" + a; return a; } // left Circular Shifting bits String leftCircularShift(String input, int numBits) { int n = input.length() * 4; int perm[] = new int[n]; for (int i = 0; i < n - 1; i++) perm[i] = (i + 2); perm[n - 1] = 1; while (numBits-- > 0) input = permutation(perm, input); return input; } // preparing 16 keys for 16 rounds String[] getKeys(String key) { String keys[] = new String[16]; // first key permutation key = permutation(PC1, key); for (int i = 0; i < 16; i++) { key = leftCircularShift( key.substring(0, 7), shiftBits[i]) + leftCircularShift(key.substring(7, 14), shiftBits[i]); // second key permutation keys[i] = permutation(PC2, key); } return keys; } // s-box lookup String sBox(String input) { String output = ""; input = hextoBin(input); for (int i = 0; i < 48; i += 6) { String temp = input.substring(i, i + 6); int num = i / 6; int row = Integer.parseInt( temp.charAt(0) + "" + temp.charAt(5), 2); int col = Integer.parseInt( temp.substring(1, 5), 2); output += Integer.toHexString( sbox[num][row][col]); } return output; } String round(String input, String key, int num) { // fk String left = input.substring(0, 8); String temp = input.substring(8, 16); String right = temp; // Expansion permutation temp = permutation(EP, temp); // xor temp and round key temp = xor(temp, key); // lookup in s-box table temp = sBox(temp); // Straight D-box temp = permutation(P, temp); // xor left = xor(left, temp); System.out.println("Round " + (num + 1) + " " + right.toUpperCase() + " " + left.toUpperCase() + " " + key.toUpperCase()); // swapper return right + left; } String encrypt(String plainText, String key) { int i; // get round keys String keys[] = getKeys(key); // initial permutation plainText = permutation(IP, plainText); System.out.println( "After initial permutation: " + plainText.toUpperCase()); System.out.println( "After splitting: L0=" + plainText.substring(0, 8).toUpperCase() + " R0=" + plainText.substring(8, 16).toUpperCase() + "\n"); // 16 rounds for (i = 0; i < 16; i++) { plainText = round(plainText, keys[i], i); } // 32-bit swap plainText = plainText.substring(8, 16) + plainText.substring(0, 8); // final permutation plainText = permutation(IP1, plainText); return plainText; } String decrypt(String plainText, String key) { int i; // get round keys String keys[] = getKeys(key); // initial permutation plainText = permutation(IP, plainText); System.out.println( "After initial permutation: " + plainText.toUpperCase()); System.out.println( "After splitting: L0=" + plainText.substring(0, 8).toUpperCase() + " R0=" + plainText.substring(8, 16).toUpperCase() + "\n"); // 16-rounds for (i = 15; i > -1; i--) { plainText = round(plainText, keys[i], 15 - i); } // 32-bit swap plainText = plainText.substring(8, 16) + plainText.substring(0, 8); plainText = permutation(IP1, plainText); return plainText; } } public static void main(String args[]) { String text = "123456ABCD132536"; String key = "AABB09182736CCDD"; DES cipher = new DES(); System.out.println("Encryption:\n"); text = cipher.encrypt(text, key); System.out.println( "\nCipher Text: " + text.toUpperCase() + "\n"); System.out.println("Decryption\n"); text = cipher.decrypt(text, key); System.out.println( "\nPlain Text: " + text.toUpperCase()); }}// code contributed by Abhay Bhat # Hexadecimal to binary conversiondef hex2bin(s): mp = {'0' : "0000", '1' : "0001", '2' : "0010", '3' : "0011", '4' : "0100", '5' : "0101", '6' : "0110", '7' : "0111", '8' : "1000", '9' : "1001", 'A' : "1010", 'B' : "1011", 'C' : "1100", 'D' : "1101", 'E' : "1110", 'F' : "1111" } bin = "" for i in range(len(s)): bin = bin + mp[s[i]] return bin # Binary to hexadecimal conversiondef bin2hex(s): mp = {"0000" : '0', "0001" : '1', "0010" : '2', "0011" : '3', "0100" : '4', "0101" : '5', "0110" : '6', "0111" : '7', "1000" : '8', "1001" : '9', "1010" : 'A', "1011" : 'B', "1100" : 'C', "1101" : 'D', "1110" : 'E', "1111" : 'F' } hex = "" for i in range(0,len(s),4): ch = "" ch = ch + s[i] ch = ch + s[i + 1] ch = ch + s[i + 2] ch = ch + s[i + 3] hex = hex + mp[ch] return hex # Binary to decimal conversiondef bin2dec(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 return decimal # Decimal to binary conversiondef dec2bin(num): res = bin(num).replace("0b", "") if(len(res)%4 != 0): div = len(res) / 4 div = int(div) counter =(4 * (div + 1)) - len(res) for i in range(0, counter): res = '0' + res return res # Permute function to rearrange the bitsdef permute(k, arr, n): permutation = "" for i in range(0, n): permutation = permutation + k[arr[i] - 1] return permutation # shifting the bits towards left by nth shiftsdef shift_left(k, nth_shifts): s = "" for i in range(nth_shifts): for j in range(1,len(k)): s = s + k[j] s = s + k[0] k = s s = "" return k # calculating xow of two strings of binary number a and bdef xor(a, b): ans = "" for i in range(len(a)): if a[i] == b[i]: ans = ans + "0" else: ans = ans + "1" return ans # Table of Position of 64 bits at initial level: Initial Permutation Tableinitial_perm = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] # Expansion D-box Tableexp_d = [32, 1 , 2 , 3 , 4 , 5 , 4 , 5, 6 , 7 , 8 , 9 , 8 , 9 , 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 ] # Straight Permutation Tableper = [ 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ] # S-box Tablesbox = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ]], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ]], [ [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ]], [ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14] ], [ [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ]], [ [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13] ], [ [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12] ], [ [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11] ] ] # Final Permutation Tablefinal_perm = [ 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 ] def encrypt(pt, rkb, rk): pt = hex2bin(pt) # Initial Permutation pt = permute(pt, initial_perm, 64) print("After initial permutation", bin2hex(pt)) # Splitting left = pt[0:32] right = pt[32:64] for i in range(0, 16): # Expansion D-box: Expanding the 32 bits data into 48 bits right_expanded = permute(right, exp_d, 48) # XOR RoundKey[i] and right_expanded xor_x = xor(right_expanded, rkb[i]) # S-boxex: substituting the value from s-box table by calculating row and column sbox_str = "" for j in range(0, 8): row = bin2dec(int(xor_x[j * 6] + xor_x[j * 6 + 5])) col = bin2dec(int(xor_x[j * 6 + 1] + xor_x[j * 6 + 2] + xor_x[j * 6 + 3] + xor_x[j * 6 + 4])) val = sbox[j][row][col] sbox_str = sbox_str + dec2bin(val) # Straight D-box: After substituting rearranging the bits sbox_str = permute(sbox_str, per, 32) # XOR left and sbox_str result = xor(left, sbox_str) left = result # Swapper if(i != 15): left, right = right, left print("Round ", i + 1, " ", bin2hex(left), " ", bin2hex(right), " ", rk[i]) # Combination combine = left + right # Final permutation: final rearranging of bits to get cipher text cipher_text = permute(combine, final_perm, 64) return cipher_text pt = "123456ABCD132536"key = "AABB09182736CCDD" # Key generation# --hex to binarykey = hex2bin(key) # --parity bit drop tablekeyp = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ] # getting 56 bit key from 64 bit using the parity bitskey = permute(key, keyp, 56) # Number of bit shiftsshift_table = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] # Key- Compression Table : Compression of key from 56 bits to 48 bitskey_comp = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ] # Splittingleft = key[0:28] # rkb for RoundKeys in binaryright = key[28:56] # rk for RoundKeys in hexadecimal rkb = []rk = []for i in range(0, 16): # Shifting the bits by nth shifts by checking from shift table left = shift_left(left, shift_table[i]) right = shift_left(right, shift_table[i]) # Combination of left and right string combine_str = left + right # Compression of key from 56 to 48 bits round_key = permute(combine_str, key_comp, 48) rkb.append(round_key) rk.append(bin2hex(round_key)) print("Encryption")cipher_text = bin2hex(encrypt(pt, rkb, rk))print("Cipher Text : ",cipher_text) print("Decryption")rkb_rev = rkb[::-1]rk_rev = rk[::-1]text = bin2hex(encrypt(cipher_text, rkb_rev, rk_rev))print("Plain Text : ",text) # This code is contributed by Aditya Jain Output: Encryption: After initial permutation: 14A7D67818CA18AD After splitting: L0=14A7D678 R0=18CA18AD Round 1 18CA18AD 5A78E394 194CD072DE8C Round 2 5A78E394 4A1210F6 4568581ABCCE Round 3 4A1210F6 B8089591 06EDA4ACF5B5 Round 4 B8089591 236779C2 DA2D032B6EE3 Round 5 236779C2 A15A4B87 69A629FEC913 Round 6 A15A4B87 2E8F9C65 C1948E87475E Round 7 2E8F9C65 A9FC20A3 708AD2DDB3C0 Round 8 A9FC20A3 308BEE97 34F822F0C66D Round 9 308BEE97 10AF9D37 84BB4473DCCC Round 10 10AF9D37 6CA6CB20 02765708B5BF Round 11 6CA6CB20 FF3C485F 6D5560AF7CA5 Round 12 FF3C485F 22A5963B C2C1E96A4BF3 Round 13 22A5963B 387CCDAA 99C31397C91F Round 14 387CCDAA BD2DD2AB 251B8BC717D0 Round 15 BD2DD2AB CF26B472 3330C5D9A36D Round 16 19BA9212 CF26B472 181C5D75C66D Cipher Text: C0B7A8D05F3A829C Decryption After initial permutation: 19BA9212CF26B472 After splitting: L0=19BA9212 R0=CF26B472 Round 1 CF26B472 BD2DD2AB 181C5D75C66D Round 2 BD2DD2AB 387CCDAA 3330C5D9A36D Round 3 387CCDAA 22A5963B 251B8BC717D0 Round 4 22A5963B FF3C485F 99C31397C91F Round 5 FF3C485F 6CA6CB20 C2C1E96A4BF3 Round 6 6CA6CB20 10AF9D37 6D5560AF7CA5 Round 7 10AF9D37 308BEE97 02765708B5BF Round 8 308BEE97 A9FC20A3 84BB4473DCCC Round 9 A9FC20A3 2E8F9C65 34F822F0C66D Round 10 2E8F9C65 A15A4B87 708AD2DDB3C0 Round 11 A15A4B87 236779C2 C1948E87475E Round 12 236779C2 B8089591 69A629FEC913 Round 13 B8089591 4A1210F6 DA2D032B6EE3 Round 14 4A1210F6 5A78E394 06EDA4ACF5B5 Round 15 5A78E394 18CA18AD 4568581ABCCE Round 16 14A7D678 18CA18AD 194CD072DE8C Plain Text: 123456ABCD132536 Refer: Difference between AES and DES ciphers MohitBansal3 AbhayBhat Bond0071 ImAditya anikaseth98 adnanirshad158 gabaa406 Pushpender007 23603vaibhav2021 abhishk01 cryptography Computer Networks GATE CS cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Socket Programming in Python Differences between IPv4 and IPv6 Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 52, "s": 24, "text": "\n15 May, 2022" }, { "code": null, "e": 539, "s": 52, "text": "Data encryption standard (DES) has been found vulnerable to very powerful attacks and therefore, the popularity of DES has been found slightly on the decline. DES is a block cipher and encrypts data in blocks of size of 64 bits each, which means 64 bits of plain text go as the input to DES, which produces 64 bits of ciphertext. The same algorithm and key are used for encryption and decryption, with minor differences. The key length is 56 bits. The basic idea is shown in the figure." }, { "code": null, "e": 812, "s": 539, "text": "We have mentioned that DES uses a 56-bit key. Actually, the initial key consists of 64 bits. However, before the DES process even starts, every 8th bit of the key is discarded to produce a 56-bit key. That is bit positions 8, 16, 24, 32, 40, 48, 56, and 64 are discarded. " }, { "code": null, "e": 1230, "s": 812, "text": "Thus, the discarding of every 8th bit of the key produces a 56-bit key from the original 64-bit key.DES is based on the two fundamental attributes of cryptography: substitution (also called confusion) and transposition (also called diffusion). DES consists of 16 steps, each of which is called a round. Each round performs the steps of substitution and transposition. Let us now discuss the broad-level steps in DES. " }, { "code": null, "e": 1740, "s": 1230, "text": "In the first step, the 64-bit plain text block is handed over to an initial Permutation (IP) function.The initial permutation is performed on plain text.Next, the initial permutation (IP) produces two halves of the permuted block; saying Left Plain Text (LPT) and Right Plain Text (RPT).Now each LPT and RPT go through 16 rounds of the encryption process.In the end, LPT and RPT are rejoined and a Final Permutation (FP) is performed on the combined blockThe result of this process produces 64-bit ciphertext." }, { "code": null, "e": 1843, "s": 1740, "text": "In the first step, the 64-bit plain text block is handed over to an initial Permutation (IP) function." }, { "code": null, "e": 1895, "s": 1843, "text": "The initial permutation is performed on plain text." }, { "code": null, "e": 2030, "s": 1895, "text": "Next, the initial permutation (IP) produces two halves of the permuted block; saying Left Plain Text (LPT) and Right Plain Text (RPT)." }, { "code": null, "e": 2099, "s": 2030, "text": "Now each LPT and RPT go through 16 rounds of the encryption process." }, { "code": null, "e": 2200, "s": 2099, "text": "In the end, LPT and RPT are rejoined and a Final Permutation (FP) is performed on the combined block" }, { "code": null, "e": 2255, "s": 2200, "text": "The result of this process produces 64-bit ciphertext." }, { "code": null, "e": 2678, "s": 2255, "text": "Initial Permutation (IP): As we have noted, the initial permutation (IP) happens only once and it happens before the first round. It suggests how the transposition in IP should proceed, as shown in the figure. For example, it says that the IP replaces the first bit of the original plain text block with the 58th bit of the original plain text, the second bit with the 50th bit of the original plain text block, and so on." }, { "code": null, "e": 2832, "s": 2678, "text": "This is nothing but jugglery of bit positions of the original plain text block. the same rule applies to all the other bit positions shown in the figure." }, { "code": null, "e": 3073, "s": 2832, "text": "As we have noted after IP is done, the resulting 64-bit permuted text block is divided into two half blocks. Each half-block consists of 32 bits, and each of the 16 rounds, in turn, consists of the broad level steps outlined in the figure. " }, { "code": null, "e": 3540, "s": 3073, "text": "Step-1: Key transformation: We have noted initial 64-bit key is transformed into a 56-bit key by discarding every 8th bit of the initial key. Thus, for each a 56-bit key is available. From this 56-bit key, a different 48-bit Sub Key is generated during each round using a process called key transformation. For this, the 56-bit key is divided into two halves, each of 28 bits. These halves are circularly shifted left by one or two positions, depending on the round." }, { "code": null, "e": 3756, "s": 3540, "text": "For example, if the round numbers 1, 2, 9, or 16 the shift is done by only one position for other rounds, the circular shift is done by two positions. The number of key bits shifted per round is shown in the figure." }, { "code": null, "e": 4397, "s": 3756, "text": "After an appropriate shift, 48 of the 56 bits are selected. for selecting 48 of the 56 bits the table is shown in the figure given below. For instance, after the shift, bit number 14 moves to the first position, bit number 17 moves to the second position, and so on. If we observe the table carefully, we will realize that it contains only 48-bit positions. Bit number 18 is discarded (we will not find it in the table), like 7 others, to reduce a 56-bit key to a 48-bit key. Since the key transformation process involves permutation as well as a selection of a 48-bit subset of the original 56-bit key it is called Compression Permutation." }, { "code": null, "e": 4536, "s": 4397, "text": "Because of this compression permutation technique, a different subset of key bits is used in each round. That makes DES not easy to crack." }, { "code": null, "e": 5076, "s": 4536, "text": "Step-2: Expansion Permutation: Recall that after the initial permutation, we had two 32-bit plain text areas called Left Plain Text(LPT) and Right Plain Text(RPT). During the expansion permutation, the RPT is expanded from 32 bits to 48 bits. Bits are permuted as well hence called expansion permutation. This happens as the 32-bit RPT is divided into 8 blocks, with each block consisting of 4 bits. Then, each 4-bit block of the previous step is then expanded to a corresponding 6-bit block, i.e., per 4-bit block, 2 more bits are added. " }, { "code": null, "e": 5445, "s": 5076, "text": "This process results in expansion as well as a permutation of the input bit while creating output. The key transformation process compresses the 56-bit key to 48 bits. Then the expansion permutation process expands the 32-bit RPT to 48-bits. Now the 48-bit key is XOR with 48-bit RPT and the resulting output is given to the next step, which is the S-Box substitution." }, { "code": null, "e": 5449, "s": 5445, "text": "C++" }, { "code": null, "e": 5454, "s": 5449, "text": "Java" }, { "code": null, "e": 5461, "s": 5454, "text": "Python" }, { "code": "#include <bits/stdc++.h>using namespace std;string hex2bin(string s){ // hexadecimal to binary conversion unordered_map<char, string> mp; mp['0'] = \"0000\"; mp['1'] = \"0001\"; mp['2'] = \"0010\"; mp['3'] = \"0011\"; mp['4'] = \"0100\"; mp['5'] = \"0101\"; mp['6'] = \"0110\"; mp['7'] = \"0111\"; mp['8'] = \"1000\"; mp['9'] = \"1001\"; mp['A'] = \"1010\"; mp['B'] = \"1011\"; mp['C'] = \"1100\"; mp['D'] = \"1101\"; mp['E'] = \"1110\"; mp['F'] = \"1111\"; string bin = \"\"; for (int i = 0; i < s.size(); i++) { bin += mp[s[i]]; } return bin;}string bin2hex(string s){ // binary to hexadecimal conversion unordered_map<string, string> mp; mp[\"0000\"] = \"0\"; mp[\"0001\"] = \"1\"; mp[\"0010\"] = \"2\"; mp[\"0011\"] = \"3\"; mp[\"0100\"] = \"4\"; mp[\"0101\"] = \"5\"; mp[\"0110\"] = \"6\"; mp[\"0111\"] = \"7\"; mp[\"1000\"] = \"8\"; mp[\"1001\"] = \"9\"; mp[\"1010\"] = \"A\"; mp[\"1011\"] = \"B\"; mp[\"1100\"] = \"C\"; mp[\"1101\"] = \"D\"; mp[\"1110\"] = \"E\"; mp[\"1111\"] = \"F\"; string hex = \"\"; for (int i = 0; i < s.length(); i += 4) { string ch = \"\"; ch += s[i]; ch += s[i + 1]; ch += s[i + 2]; ch += s[i + 3]; hex += mp[ch]; } return hex;} string permute(string k, int* arr, int n){ string per = \"\"; for (int i = 0; i < n; i++) { per += k[arr[i] - 1]; } return per;} string shift_left(string k, int shifts){ string s = \"\"; for (int i = 0; i < shifts; i++) { for (int j = 1; j < 28; j++) { s += k[j]; } s += k[0]; k = s; s = \"\"; } return k;} string xor_(string a, string b){ string ans = \"\"; for (int i = 0; i < a.size(); i++) { if (a[i] == b[i]) { ans += \"0\"; } else { ans += \"1\"; } } return ans;}string encrypt(string pt, vector<string> rkb, vector<string> rk){ // Hexadecimal to binary pt = hex2bin(pt); // Initial Permutation Table int initial_perm[64] = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; // Initial Permutation pt = permute(pt, initial_perm, 64); cout << \"After initial permutation: \" << bin2hex(pt) << endl; // Splitting string left = pt.substr(0, 32); string right = pt.substr(32, 32); cout << \"After splitting: L0=\" << bin2hex(left) << \" R0=\" << bin2hex(right) << endl; // Expansion D-box Table int exp_d[48] = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; // S-box Table int s[8][4][16] = { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }, { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }, { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }, { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }, { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }, { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }, { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }, { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } }; // Straight Permutation Table int per[32] = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; cout << endl; for (int i = 0; i < 16; i++) { // Expansion D-box string right_expanded = permute(right, exp_d, 48); // XOR RoundKey[i] and right_expanded string x = xor_(rkb[i], right_expanded); // S-boxes string op = \"\"; for (int i = 0; i < 8; i++) { int row = 2 * int(x[i * 6] - '0') + int(x[i * 6 + 5] - '0'); int col = 8 * int(x[i * 6 + 1] - '0') + 4 * int(x[i * 6 + 2] - '0') + 2 * int(x[i * 6 + 3] - '0') + int(x[i * 6 + 4] - '0'); int val = s[i][row][col]; op += char(val / 8 + '0'); val = val % 8; op += char(val / 4 + '0'); val = val % 4; op += char(val / 2 + '0'); val = val % 2; op += char(val + '0'); } // Straight D-box op = permute(op, per, 32); // XOR left and op x = xor_(op, left); left = x; // Swapper if (i != 15) { swap(left, right); } cout << \"Round \" << i + 1 << \" \" << bin2hex(left) << \" \" << bin2hex(right) << \" \" << rk[i] << endl; } // Combination string combine = left + right; // Final Permutation Table int final_perm[64] = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; // Final Permutation string cipher = bin2hex(permute(combine, final_perm, 64)); return cipher;}int main(){ // pt is plain text string pt, key; /*cout<<\"Enter plain text(in hexadecimal): \"; cin>>pt; cout<<\"Enter key(in hexadecimal): \"; cin>>key;*/ pt = \"123456ABCD132536\"; key = \"AABB09182736CCDD\"; // Key Generation // Hex to binary key = hex2bin(key); // Parity bit drop table int keyp[56] = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; // getting 56 bit key from 64 bit using the parity bits key = permute(key, keyp, 56); // key without parity // Number of bit shifts int shift_table[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // Key- Compression Table int key_comp[48] = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; // Splitting string left = key.substr(0, 28); string right = key.substr(28, 28); vector<string> rkb; // rkb for RoundKeys in binary vector<string> rk; // rk for RoundKeys in hexadecimal for (int i = 0; i < 16; i++) { // Shifting left = shift_left(left, shift_table[i]); right = shift_left(right, shift_table[i]); // Combining string combine = left + right; // Key Compression string RoundKey = permute(combine, key_comp, 48); rkb.push_back(RoundKey); rk.push_back(bin2hex(RoundKey)); } cout << \"\\nEncryption:\\n\\n\"; string cipher = encrypt(pt, rkb, rk); cout << \"\\nCipher Text: \" << cipher << endl; cout << \"\\nDecryption\\n\\n\"; reverse(rkb.begin(), rkb.end()); reverse(rk.begin(), rk.end()); string text = encrypt(cipher, rkb, rk); cout << \"\\nPlain Text: \" << text << endl;}", "e": 15509, "s": 5461, "text": null }, { "code": "import java.util.*; class Main { private static class DES { // CONSTANTS // Initial Permutation Table int[] IP = { 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7 }; // Inverse Initial Permutation Table int[] IP1 = { 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 }; // first key-hePermutation Table int[] PC1 = { 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 }; // second key-Permutation Table int[] PC2 = { 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 }; // Expansion D-box Table int[] EP = { 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 }; // Straight Permutation Table int[] P = { 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 }; // S-box Table int[][][] sbox = { { { 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 }, { 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 }, { 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 }, { 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 } }, { { 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 }, { 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 }, { 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 }, { 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 } }, { { 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 }, { 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 }, { 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 }, { 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 } }, { { 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 }, { 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 }, { 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 }, { 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 } }, { { 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 }, { 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 }, { 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 }, { 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 } }, { { 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 }, { 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 }, { 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 }, { 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 } }, { { 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 }, { 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 }, { 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 }, { 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 } }, { { 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 }, { 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 }, { 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 }, { 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 } } }; int[] shiftBits = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 }; // hexadecimal to binary conversion String hextoBin(String input) { int n = input.length() * 4; input = Long.toBinaryString( Long.parseUnsignedLong(input, 16)); while (input.length() < n) input = \"0\" + input; return input; } // binary to hexadecimal conversion String binToHex(String input) { int n = (int)input.length() / 4; input = Long.toHexString( Long.parseUnsignedLong(input, 2)); while (input.length() < n) input = \"0\" + input; return input; } // per-mutate input hexadecimal // according to specified sequence String permutation(int[] sequence, String input) { String output = \"\"; input = hextoBin(input); for (int i = 0; i < sequence.length; i++) output += input.charAt(sequence[i] - 1); output = binToHex(output); return output; } // xor 2 hexadecimal strings String xor(String a, String b) { // hexadecimal to decimal(base 10) long t_a = Long.parseUnsignedLong(a, 16); // hexadecimal to decimal(base 10) long t_b = Long.parseUnsignedLong(b, 16); // xor t_a = t_a ^ t_b; // decimal to hexadecimal a = Long.toHexString(t_a); // prepend 0's to maintain length while (a.length() < b.length()) a = \"0\" + a; return a; } // left Circular Shifting bits String leftCircularShift(String input, int numBits) { int n = input.length() * 4; int perm[] = new int[n]; for (int i = 0; i < n - 1; i++) perm[i] = (i + 2); perm[n - 1] = 1; while (numBits-- > 0) input = permutation(perm, input); return input; } // preparing 16 keys for 16 rounds String[] getKeys(String key) { String keys[] = new String[16]; // first key permutation key = permutation(PC1, key); for (int i = 0; i < 16; i++) { key = leftCircularShift( key.substring(0, 7), shiftBits[i]) + leftCircularShift(key.substring(7, 14), shiftBits[i]); // second key permutation keys[i] = permutation(PC2, key); } return keys; } // s-box lookup String sBox(String input) { String output = \"\"; input = hextoBin(input); for (int i = 0; i < 48; i += 6) { String temp = input.substring(i, i + 6); int num = i / 6; int row = Integer.parseInt( temp.charAt(0) + \"\" + temp.charAt(5), 2); int col = Integer.parseInt( temp.substring(1, 5), 2); output += Integer.toHexString( sbox[num][row][col]); } return output; } String round(String input, String key, int num) { // fk String left = input.substring(0, 8); String temp = input.substring(8, 16); String right = temp; // Expansion permutation temp = permutation(EP, temp); // xor temp and round key temp = xor(temp, key); // lookup in s-box table temp = sBox(temp); // Straight D-box temp = permutation(P, temp); // xor left = xor(left, temp); System.out.println(\"Round \" + (num + 1) + \" \" + right.toUpperCase() + \" \" + left.toUpperCase() + \" \" + key.toUpperCase()); // swapper return right + left; } String encrypt(String plainText, String key) { int i; // get round keys String keys[] = getKeys(key); // initial permutation plainText = permutation(IP, plainText); System.out.println( \"After initial permutation: \" + plainText.toUpperCase()); System.out.println( \"After splitting: L0=\" + plainText.substring(0, 8).toUpperCase() + \" R0=\" + plainText.substring(8, 16).toUpperCase() + \"\\n\"); // 16 rounds for (i = 0; i < 16; i++) { plainText = round(plainText, keys[i], i); } // 32-bit swap plainText = plainText.substring(8, 16) + plainText.substring(0, 8); // final permutation plainText = permutation(IP1, plainText); return plainText; } String decrypt(String plainText, String key) { int i; // get round keys String keys[] = getKeys(key); // initial permutation plainText = permutation(IP, plainText); System.out.println( \"After initial permutation: \" + plainText.toUpperCase()); System.out.println( \"After splitting: L0=\" + plainText.substring(0, 8).toUpperCase() + \" R0=\" + plainText.substring(8, 16).toUpperCase() + \"\\n\"); // 16-rounds for (i = 15; i > -1; i--) { plainText = round(plainText, keys[i], 15 - i); } // 32-bit swap plainText = plainText.substring(8, 16) + plainText.substring(0, 8); plainText = permutation(IP1, plainText); return plainText; } } public static void main(String args[]) { String text = \"123456ABCD132536\"; String key = \"AABB09182736CCDD\"; DES cipher = new DES(); System.out.println(\"Encryption:\\n\"); text = cipher.encrypt(text, key); System.out.println( \"\\nCipher Text: \" + text.toUpperCase() + \"\\n\"); System.out.println(\"Decryption\\n\"); text = cipher.decrypt(text, key); System.out.println( \"\\nPlain Text: \" + text.toUpperCase()); }}// code contributed by Abhay Bhat", "e": 26940, "s": 15509, "text": null }, { "code": "# Hexadecimal to binary conversiondef hex2bin(s): mp = {'0' : \"0000\", '1' : \"0001\", '2' : \"0010\", '3' : \"0011\", '4' : \"0100\", '5' : \"0101\", '6' : \"0110\", '7' : \"0111\", '8' : \"1000\", '9' : \"1001\", 'A' : \"1010\", 'B' : \"1011\", 'C' : \"1100\", 'D' : \"1101\", 'E' : \"1110\", 'F' : \"1111\" } bin = \"\" for i in range(len(s)): bin = bin + mp[s[i]] return bin # Binary to hexadecimal conversiondef bin2hex(s): mp = {\"0000\" : '0', \"0001\" : '1', \"0010\" : '2', \"0011\" : '3', \"0100\" : '4', \"0101\" : '5', \"0110\" : '6', \"0111\" : '7', \"1000\" : '8', \"1001\" : '9', \"1010\" : 'A', \"1011\" : 'B', \"1100\" : 'C', \"1101\" : 'D', \"1110\" : 'E', \"1111\" : 'F' } hex = \"\" for i in range(0,len(s),4): ch = \"\" ch = ch + s[i] ch = ch + s[i + 1] ch = ch + s[i + 2] ch = ch + s[i + 3] hex = hex + mp[ch] return hex # Binary to decimal conversiondef bin2dec(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 return decimal # Decimal to binary conversiondef dec2bin(num): res = bin(num).replace(\"0b\", \"\") if(len(res)%4 != 0): div = len(res) / 4 div = int(div) counter =(4 * (div + 1)) - len(res) for i in range(0, counter): res = '0' + res return res # Permute function to rearrange the bitsdef permute(k, arr, n): permutation = \"\" for i in range(0, n): permutation = permutation + k[arr[i] - 1] return permutation # shifting the bits towards left by nth shiftsdef shift_left(k, nth_shifts): s = \"\" for i in range(nth_shifts): for j in range(1,len(k)): s = s + k[j] s = s + k[0] k = s s = \"\" return k # calculating xow of two strings of binary number a and bdef xor(a, b): ans = \"\" for i in range(len(a)): if a[i] == b[i]: ans = ans + \"0\" else: ans = ans + \"1\" return ans # Table of Position of 64 bits at initial level: Initial Permutation Tableinitial_perm = [58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7] # Expansion D-box Tableexp_d = [32, 1 , 2 , 3 , 4 , 5 , 4 , 5, 6 , 7 , 8 , 9 , 8 , 9 , 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1 ] # Straight Permutation Tableper = [ 16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25 ] # S-box Tablesbox = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7], [ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8], [ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0], [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ]], [[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10], [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5], [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15], [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ]], [ [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8], [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1], [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7], [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ]], [ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15], [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9], [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4], [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14] ], [ [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9], [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6], [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14], [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ]], [ [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11], [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8], [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6], [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13] ], [ [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1], [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6], [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2], [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12] ], [ [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7], [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2], [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8], [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11] ] ] # Final Permutation Tablefinal_perm = [ 40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25 ] def encrypt(pt, rkb, rk): pt = hex2bin(pt) # Initial Permutation pt = permute(pt, initial_perm, 64) print(\"After initial permutation\", bin2hex(pt)) # Splitting left = pt[0:32] right = pt[32:64] for i in range(0, 16): # Expansion D-box: Expanding the 32 bits data into 48 bits right_expanded = permute(right, exp_d, 48) # XOR RoundKey[i] and right_expanded xor_x = xor(right_expanded, rkb[i]) # S-boxex: substituting the value from s-box table by calculating row and column sbox_str = \"\" for j in range(0, 8): row = bin2dec(int(xor_x[j * 6] + xor_x[j * 6 + 5])) col = bin2dec(int(xor_x[j * 6 + 1] + xor_x[j * 6 + 2] + xor_x[j * 6 + 3] + xor_x[j * 6 + 4])) val = sbox[j][row][col] sbox_str = sbox_str + dec2bin(val) # Straight D-box: After substituting rearranging the bits sbox_str = permute(sbox_str, per, 32) # XOR left and sbox_str result = xor(left, sbox_str) left = result # Swapper if(i != 15): left, right = right, left print(\"Round \", i + 1, \" \", bin2hex(left), \" \", bin2hex(right), \" \", rk[i]) # Combination combine = left + right # Final permutation: final rearranging of bits to get cipher text cipher_text = permute(combine, final_perm, 64) return cipher_text pt = \"123456ABCD132536\"key = \"AABB09182736CCDD\" # Key generation# --hex to binarykey = hex2bin(key) # --parity bit drop tablekeyp = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ] # getting 56 bit key from 64 bit using the parity bitskey = permute(key, keyp, 56) # Number of bit shiftsshift_table = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ] # Key- Compression Table : Compression of key from 56 bits to 48 bitskey_comp = [14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ] # Splittingleft = key[0:28] # rkb for RoundKeys in binaryright = key[28:56] # rk for RoundKeys in hexadecimal rkb = []rk = []for i in range(0, 16): # Shifting the bits by nth shifts by checking from shift table left = shift_left(left, shift_table[i]) right = shift_left(right, shift_table[i]) # Combination of left and right string combine_str = left + right # Compression of key from 56 to 48 bits round_key = permute(combine_str, key_comp, 48) rkb.append(round_key) rk.append(bin2hex(round_key)) print(\"Encryption\")cipher_text = bin2hex(encrypt(pt, rkb, rk))print(\"Cipher Text : \",cipher_text) print(\"Decryption\")rkb_rev = rkb[::-1]rk_rev = rk[::-1]text = bin2hex(encrypt(cipher_text, rkb_rev, rk_rev))print(\"Plain Text : \",text) # This code is contributed by Aditya Jain", "e": 35956, "s": 26940, "text": null }, { "code": null, "e": 35965, "s": 35956, "text": "Output: " }, { "code": null, "e": 37486, "s": 35965, "text": "Encryption:\n\nAfter initial permutation: 14A7D67818CA18AD\nAfter splitting: L0=14A7D678 R0=18CA18AD\n\nRound 1 18CA18AD 5A78E394 194CD072DE8C\nRound 2 5A78E394 4A1210F6 4568581ABCCE\nRound 3 4A1210F6 B8089591 06EDA4ACF5B5\nRound 4 B8089591 236779C2 DA2D032B6EE3\nRound 5 236779C2 A15A4B87 69A629FEC913\nRound 6 A15A4B87 2E8F9C65 C1948E87475E\nRound 7 2E8F9C65 A9FC20A3 708AD2DDB3C0\nRound 8 A9FC20A3 308BEE97 34F822F0C66D\nRound 9 308BEE97 10AF9D37 84BB4473DCCC\nRound 10 10AF9D37 6CA6CB20 02765708B5BF\nRound 11 6CA6CB20 FF3C485F 6D5560AF7CA5\nRound 12 FF3C485F 22A5963B C2C1E96A4BF3\nRound 13 22A5963B 387CCDAA 99C31397C91F\nRound 14 387CCDAA BD2DD2AB 251B8BC717D0\nRound 15 BD2DD2AB CF26B472 3330C5D9A36D\nRound 16 19BA9212 CF26B472 181C5D75C66D\n\nCipher Text: C0B7A8D05F3A829C\n\nDecryption\n\nAfter initial permutation: 19BA9212CF26B472\nAfter splitting: L0=19BA9212 R0=CF26B472\n\nRound 1 CF26B472 BD2DD2AB 181C5D75C66D\nRound 2 BD2DD2AB 387CCDAA 3330C5D9A36D\nRound 3 387CCDAA 22A5963B 251B8BC717D0\nRound 4 22A5963B FF3C485F 99C31397C91F\nRound 5 FF3C485F 6CA6CB20 C2C1E96A4BF3\nRound 6 6CA6CB20 10AF9D37 6D5560AF7CA5\nRound 7 10AF9D37 308BEE97 02765708B5BF\nRound 8 308BEE97 A9FC20A3 84BB4473DCCC\nRound 9 A9FC20A3 2E8F9C65 34F822F0C66D\nRound 10 2E8F9C65 A15A4B87 708AD2DDB3C0\nRound 11 A15A4B87 236779C2 C1948E87475E\nRound 12 236779C2 B8089591 69A629FEC913\nRound 13 B8089591 4A1210F6 DA2D032B6EE3\nRound 14 4A1210F6 5A78E394 06EDA4ACF5B5\nRound 15 5A78E394 18CA18AD 4568581ABCCE\nRound 16 14A7D678 18CA18AD 194CD072DE8C\n\nPlain Text: 123456ABCD132536" }, { "code": null, "e": 37533, "s": 37486, "text": "Refer: Difference between AES and DES ciphers " }, { "code": null, "e": 37546, "s": 37533, "text": "MohitBansal3" }, { "code": null, "e": 37556, "s": 37546, "text": "AbhayBhat" }, { "code": null, "e": 37565, "s": 37556, "text": "Bond0071" }, { "code": null, "e": 37574, "s": 37565, "text": "ImAditya" }, { "code": null, "e": 37586, "s": 37574, "text": "anikaseth98" }, { "code": null, "e": 37601, "s": 37586, "text": "adnanirshad158" }, { "code": null, "e": 37610, "s": 37601, "text": "gabaa406" }, { "code": null, "e": 37624, "s": 37610, "text": "Pushpender007" }, { "code": null, "e": 37641, "s": 37624, "text": "23603vaibhav2021" }, { "code": null, "e": 37651, "s": 37641, "text": "abhishk01" }, { "code": null, "e": 37664, "s": 37651, "text": "cryptography" }, { "code": null, "e": 37682, "s": 37664, "text": "Computer Networks" }, { "code": null, "e": 37690, "s": 37682, "text": "GATE CS" }, { "code": null, "e": 37703, "s": 37690, "text": "cryptography" }, { "code": null, "e": 37721, "s": 37703, "text": "Computer Networks" }, { "code": null, "e": 37819, "s": 37721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37848, "s": 37819, "text": "Socket Programming in Python" }, { "code": null, "e": 37882, "s": 37848, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 37912, "s": 37882, "text": "Wireless Application Protocol" }, { "code": null, "e": 37942, "s": 37912, "text": "GSM in Wireless Communication" }, { "code": null, "e": 37968, "s": 37942, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 37992, "s": 37968, "text": "ACID Properties in DBMS" }, { "code": null, "e": 38019, "s": 37992, "text": "Types of Operating Systems" }, { "code": null, "e": 38040, "s": 38019, "text": "Normal Forms in DBMS" }, { "code": null, "e": 38089, "s": 38040, "text": "Page Replacement Algorithms in Operating Systems" } ]
Flutter – Material Banner Widget
22 Sep, 2021 In this article, we will learn about a new feature called Material Banner which is a new feature in flutter and got released in flutter version 2.5.0. A banner displays an important message and asks the user to perform some action. Banner is displayed at top of the screen below appbar. They are persistent, thus allowing users to ignore them or perform some action. Points to Keep in mind: A banner container is rectangular in shape and extends the full widget. This container has a leading icon, text, and action buttons. A banner can contain two text buttons with dismiss action button on the left and confirming action button on right. Now let’s see how the material banner widget is implemented in a flutter app: Step 1: Check the flutter version by going to the terminal and run the command flutter –version. The reason to do this is that the material banner widget is introduced in version 2.5.0 so to use this widget we need the latest version. If your version is below 2.5.0 then go to the terminal and run the command flutter upgrade. Your flutter version will get updated. Step 2: Now let’s see how to use this feature by directly switching to our code editors. Dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key,}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton(onPressed: () => showMaterialBanner(), child: const Text('Material Banner')) ], ), ), ); } // Material Banner implementation showMaterialBanner(){ ScaffoldMessenger.of(context).showMaterialBanner( MaterialBanner( content: const Text('Hello, I am Material Banner!'), contentTextStyle: const TextStyle(color: Colors.black ,fontSize: 30), backgroundColor: Colors.yellow, leadingPadding: const EdgeInsets.only(right: 30), leading: const Icon(Icons.info, size: 32,), actions:[ TextButton(onPressed: () {}, child: const Text('Dismiss')), TextButton(onPressed: (){}, child: const Text('Continue')), ]) ); }} Output: Explanation: To create a banner we have created an elevated button and that elevated button calls the method called showMaterialBanner(). In this showMaterialBanner() method, we have called the material banner using scaffold messanger to use the material banner feature. After calling the feature we had implemented the properties that the material banner contains like – content, background color, leading icon, action buttons, and padding. As we run the program we see that as we click on the Material Banner button we see a material banner on the top in yellow color. Step3: Now if we want to get dismiss our material banner from the top then we had to give functionality to our action button. So in our dismiss action button we gave the property to our onPressed method: hideCurrentMaterialBanner. Complete Source Code: Dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key,}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton(onPressed: () => showMaterialBanner(), child: const Text('Material Banner')) ], ), ), ); } showMaterialBanner(){ ScaffoldMessenger.of(context).showMaterialBanner( MaterialBanner( content: const Text('Hello, I am Material Banner!'), contentTextStyle: const TextStyle(color: Colors.black ,fontSize: 30), backgroundColor: Colors.yellow, leadingPadding: const EdgeInsets.only(right: 30), leading: const Icon(Icons.info, size: 32,), actions:[ TextButton(onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(), child: const Text('Dismiss')), TextButton(onPressed: (){}, child: const Text('Continue')), ]) ); }} Output: Explanation: As we click on the Material Banner button we see a material banner on top. To remove that banner we click on dismiss button and the banner gets dismissed from the top. Blogathon-2021 Flutter UI-components Flutter-widgets Blogathon Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python Modes of DMA Transfer Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 179, "s": 28, "text": "In this article, we will learn about a new feature called Material Banner which is a new feature in flutter and got released in flutter version 2.5.0." }, { "code": null, "e": 395, "s": 179, "text": "A banner displays an important message and asks the user to perform some action. Banner is displayed at top of the screen below appbar. They are persistent, thus allowing users to ignore them or perform some action." }, { "code": null, "e": 419, "s": 395, "text": "Points to Keep in mind:" }, { "code": null, "e": 491, "s": 419, "text": "A banner container is rectangular in shape and extends the full widget." }, { "code": null, "e": 552, "s": 491, "text": "This container has a leading icon, text, and action buttons." }, { "code": null, "e": 668, "s": 552, "text": "A banner can contain two text buttons with dismiss action button on the left and confirming action button on right." }, { "code": null, "e": 747, "s": 668, "text": "Now let’s see how the material banner widget is implemented in a flutter app: " }, { "code": null, "e": 983, "s": 747, "text": "Step 1: Check the flutter version by going to the terminal and run the command flutter –version. The reason to do this is that the material banner widget is introduced in version 2.5.0 so to use this widget we need the latest version. " }, { "code": null, "e": 1114, "s": 983, "text": "If your version is below 2.5.0 then go to the terminal and run the command flutter upgrade. Your flutter version will get updated." }, { "code": null, "e": 1203, "s": 1114, "text": "Step 2: Now let’s see how to use this feature by directly switching to our code editors." }, { "code": null, "e": 1208, "s": 1203, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key,}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton(onPressed: () => showMaterialBanner(), child: const Text('Material Banner')) ], ), ), ); } // Material Banner implementation showMaterialBanner(){ ScaffoldMessenger.of(context).showMaterialBanner( MaterialBanner( content: const Text('Hello, I am Material Banner!'), contentTextStyle: const TextStyle(color: Colors.black ,fontSize: 30), backgroundColor: Colors.yellow, leadingPadding: const EdgeInsets.only(right: 30), leading: const Icon(Icons.info, size: 32,), actions:[ TextButton(onPressed: () {}, child: const Text('Dismiss')), TextButton(onPressed: (){}, child: const Text('Continue')), ]) ); }}", "e": 2976, "s": 1208, "text": null }, { "code": null, "e": 2984, "s": 2976, "text": "Output:" }, { "code": null, "e": 2999, "s": 2984, "text": "Explanation: " }, { "code": null, "e": 3124, "s": 2999, "text": "To create a banner we have created an elevated button and that elevated button calls the method called showMaterialBanner()." }, { "code": null, "e": 3257, "s": 3124, "text": "In this showMaterialBanner() method, we have called the material banner using scaffold messanger to use the material banner feature." }, { "code": null, "e": 3429, "s": 3257, "text": " After calling the feature we had implemented the properties that the material banner contains like – content, background color, leading icon, action buttons, and padding." }, { "code": null, "e": 3559, "s": 3429, "text": "As we run the program we see that as we click on the Material Banner button we see a material banner on the top in yellow color. " }, { "code": null, "e": 3790, "s": 3559, "text": "Step3: Now if we want to get dismiss our material banner from the top then we had to give functionality to our action button. So in our dismiss action button we gave the property to our onPressed method: hideCurrentMaterialBanner." }, { "code": null, "e": 3812, "s": 3790, "text": "Complete Source Code:" }, { "code": null, "e": 3817, "s": 3812, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), home: const MyHomePage(), ); }} class MyHomePage extends StatefulWidget { const MyHomePage({Key? key,}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton(onPressed: () => showMaterialBanner(), child: const Text('Material Banner')) ], ), ), ); } showMaterialBanner(){ ScaffoldMessenger.of(context).showMaterialBanner( MaterialBanner( content: const Text('Hello, I am Material Banner!'), contentTextStyle: const TextStyle(color: Colors.black ,fontSize: 30), backgroundColor: Colors.yellow, leadingPadding: const EdgeInsets.only(right: 30), leading: const Icon(Icons.info, size: 32,), actions:[ TextButton(onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(), child: const Text('Dismiss')), TextButton(onPressed: (){}, child: const Text('Continue')), ]) ); }}", "e": 5606, "s": 3817, "text": null }, { "code": null, "e": 5615, "s": 5606, "text": "Output: " }, { "code": null, "e": 5628, "s": 5615, "text": "Explanation:" }, { "code": null, "e": 5704, "s": 5628, "text": "As we click on the Material Banner button we see a material banner on top. " }, { "code": null, "e": 5797, "s": 5704, "text": "To remove that banner we click on dismiss button and the banner gets dismissed from the top." }, { "code": null, "e": 5812, "s": 5797, "text": "Blogathon-2021" }, { "code": null, "e": 5834, "s": 5812, "text": "Flutter UI-components" }, { "code": null, "e": 5850, "s": 5834, "text": "Flutter-widgets" }, { "code": null, "e": 5860, "s": 5850, "text": "Blogathon" }, { "code": null, "e": 5865, "s": 5860, "text": "Dart" }, { "code": null, "e": 5873, "s": 5865, "text": "Flutter" }, { "code": null, "e": 5971, "s": 5873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6012, "s": 5971, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 6050, "s": 6012, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 6094, "s": 6050, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 6154, "s": 6094, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 6176, "s": 6154, "text": "Modes of DMA Transfer" }, { "code": null, "e": 6208, "s": 6176, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 6236, "s": 6208, "text": "Listview.builder in Flutter" }, { "code": null, "e": 6275, "s": 6236, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 6300, "s": 6275, "text": "Splash Screen in Flutter" } ]
Interfaces and Polymorphism in Java
02 Sep, 2021 Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts. Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name. Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading. Types of polymorphism in Java: Run time polymorphismCompile-time polymorphism Run time polymorphism Compile-time polymorphism Type 1: Run time polymorphism This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java. Example Java // Java Program to Illustrate Run-time polymorphism // Importing I/O classesimport java.io.*; // Class 1 (Parent class)class GFG1 { //name method void name() { System.out.println("This is the GFG1 class"); }} // Class 2 (Child class)// Main class extending parent classpublic class GFG extends GFG1 { // Method 1 void name() { // Print statement System.out.println("This is the GFG class"); } // Method 2 // Main drive method public static void main(String[] args) { // Now creating 2 objects with different references and // calling the Method 1 over the objects // Case 1: GFG1 reference and GFG1 is the object GFG1 ob = new GFG1(); ob.name(); // Case 2: GFG1 reference and GFG is the object GFG1 ob1 = new GFG(); ob1.name(); }} This is the GFG1 class This is the GFG class Output explanation: In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism. Type 2: Compile-time polymorphism Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name. Example: Java // Java Program to Illustrate Run-time polymorphism // Importing required classesimport java.io.*;import java.util.*; // Class 1// Helper classclass First { // Method of this class // Without any parameter void check() { // Print statement if this method is called System.out.println("This is the class First"); }} // Class 2// Main classclass Second extends First { // Method overloading void check(String name) { // Printing the name of the class method having the // parameter System.out.println("This is the class " + name); } // Method 2 // Main driver method public static void main(String args[]) { // Creating object of class 2 Second ob = new Second(); // Calling method over class 2 object ob.check("Second"); // Creating object of class 1 First ob1 = new First(); ob.check(); // Upcasting First ob2 = new Second(); ob.check(); }} This is the class Second This is the class First This is the class First Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java. Real-life Example The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees. Example: Java // Java Program to Demonstrate Concept of interfaces // Interfaceinterface salary { void insertsalary(int salary);} // Class 1// Implementing the salary in the classclass SDE1 implements salary { int salary; @Override public void insertsalary(int salary) { this.salary = salary; } void printSalary() { System.out.println(this.salary); }} // Class 2// Implementing the salary inside the SDE2 classclass SDE2 implements salary { int salary; @Override public void insertsalary(int salary) { this.salary = salary; } void printSalary() { System.out.println(this.salary); }} public class GFG { public static void main(String[] args) { SDE1 ob = new SDE1(); // Insert different salaries ob.insertsalary(100000); ob.printSalary(); SDE2 ob1 = new SDE2(); ob1.insertsalary(200000); ob1.printSalary(); }} 100000 200000 abhishek0719kadiyan arorakashish0911 java-interfaces Java-Object Oriented Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Sep, 2021" }, { "code": null, "e": 546, "s": 54, "text": "Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, interfaces, etc. In this article, we will discuss polymorphism and interface concepts." }, { "code": null, "e": 913, "s": 546, "text": "Polymorphism is that it has many forms that mean one specific defined form is used in many different ways. The simplest real-life example is let’s suppose we have to store the name of the person and the phone number of the person, but there are many situations when a person has two different phone numbers. We have to save the same phone number under the same name." }, { "code": null, "e": 1468, "s": 913, "text": "Let us interpret it with help . So, in java, the problem can be solved using an object-oriented concept, void insertPhone(String name, int phone). So, this method is used to save the phone number of the particular person. Similarly, we can use the same form but a different signature means different parameters to store the alternative phone number of the person’s void insertPhone(String name, int phone1, int phone2). One method has two different forms and performs different operations. This is an example of polymorphism, which is method overloading." }, { "code": null, "e": 1499, "s": 1468, "text": "Types of polymorphism in Java:" }, { "code": null, "e": 1546, "s": 1499, "text": "Run time polymorphismCompile-time polymorphism" }, { "code": null, "e": 1568, "s": 1546, "text": "Run time polymorphism" }, { "code": null, "e": 1594, "s": 1568, "text": "Compile-time polymorphism" }, { "code": null, "e": 1624, "s": 1594, "text": "Type 1: Run time polymorphism" }, { "code": null, "e": 1850, "s": 1624, "text": "This type of polymorphism is resolved by the java virtual machine, not by the java compiler. That’s why this type of polymorphism is called run-time polymorphism. Run time polymorphism occurs during method overriding in java." }, { "code": null, "e": 1859, "s": 1850, "text": "Example " }, { "code": null, "e": 1864, "s": 1859, "text": "Java" }, { "code": "// Java Program to Illustrate Run-time polymorphism // Importing I/O classesimport java.io.*; // Class 1 (Parent class)class GFG1 { //name method void name() { System.out.println(\"This is the GFG1 class\"); }} // Class 2 (Child class)// Main class extending parent classpublic class GFG extends GFG1 { // Method 1 void name() { // Print statement System.out.println(\"This is the GFG class\"); } // Method 2 // Main drive method public static void main(String[] args) { // Now creating 2 objects with different references and // calling the Method 1 over the objects // Case 1: GFG1 reference and GFG1 is the object GFG1 ob = new GFG1(); ob.name(); // Case 2: GFG1 reference and GFG is the object GFG1 ob1 = new GFG(); ob1.name(); }}", "e": 2643, "s": 1864, "text": null }, { "code": null, "e": 2688, "s": 2643, "text": "This is the GFG1 class\nThis is the GFG class" }, { "code": null, "e": 2709, "s": 2688, "text": "Output explanation: " }, { "code": null, "e": 3125, "s": 2709, "text": "In the above example, the same function i.e name is called two times, but in both cases, the output is different. The signatures of these methods are also the same. That’s why compilers cannot be able to identify which should be executed. This is determined only after the object creation and reference of the class, which is performed during run time (Memory management ). That’s why this is run-time polymorphism." }, { "code": null, "e": 3159, "s": 3125, "text": "Type 2: Compile-time polymorphism" }, { "code": null, "e": 3533, "s": 3159, "text": "Method overloading is an example of the compile-time polymorphism method. Overloading means a function having the same name but a different signature. This is compile-time polymorphism because this type of polymorphism is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name." }, { "code": null, "e": 3542, "s": 3533, "text": "Example:" }, { "code": null, "e": 3547, "s": 3542, "text": "Java" }, { "code": "// Java Program to Illustrate Run-time polymorphism // Importing required classesimport java.io.*;import java.util.*; // Class 1// Helper classclass First { // Method of this class // Without any parameter void check() { // Print statement if this method is called System.out.println(\"This is the class First\"); }} // Class 2// Main classclass Second extends First { // Method overloading void check(String name) { // Printing the name of the class method having the // parameter System.out.println(\"This is the class \" + name); } // Method 2 // Main driver method public static void main(String args[]) { // Creating object of class 2 Second ob = new Second(); // Calling method over class 2 object ob.check(\"Second\"); // Creating object of class 1 First ob1 = new First(); ob.check(); // Upcasting First ob2 = new Second(); ob.check(); }}", "e": 4541, "s": 3547, "text": null }, { "code": null, "e": 4614, "s": 4541, "text": "This is the class Second\nThis is the class First\nThis is the class First" }, { "code": null, "e": 5130, "s": 4614, "text": "Interfaces are very similar to classes. They have variables and methods but the interfaces allow only abstract methods(that don’t contain the body of the methods), but what is the difference between the classes and the interfaces? The first advantage is to allow interfaces to implement the multiple inheritances in a particular class. The JAVA language doesn’t support multiple inheritances if we extend multiple classes in the class, but with the help of the interfaces, multiple inheritances are allowed in Java." }, { "code": null, "e": 5148, "s": 5130, "text": "Real-life Example" }, { "code": null, "e": 5658, "s": 5148, "text": "The real-world example of interfaces is that we have multiple classes for different levels of employees working in a particular company and the necessary property of the class is the salary of the employees and this. We must be implemented in every class and. Also, it is different for every employee here. The concept of the interface is used. We simply create an interface containing an abstract salary method and implement it in all the classes and we can easily define different salaries of the employees." }, { "code": null, "e": 5667, "s": 5658, "text": "Example:" }, { "code": null, "e": 5672, "s": 5667, "text": "Java" }, { "code": "// Java Program to Demonstrate Concept of interfaces // Interfaceinterface salary { void insertsalary(int salary);} // Class 1// Implementing the salary in the classclass SDE1 implements salary { int salary; @Override public void insertsalary(int salary) { this.salary = salary; } void printSalary() { System.out.println(this.salary); }} // Class 2// Implementing the salary inside the SDE2 classclass SDE2 implements salary { int salary; @Override public void insertsalary(int salary) { this.salary = salary; } void printSalary() { System.out.println(this.salary); }} public class GFG { public static void main(String[] args) { SDE1 ob = new SDE1(); // Insert different salaries ob.insertsalary(100000); ob.printSalary(); SDE2 ob1 = new SDE2(); ob1.insertsalary(200000); ob1.printSalary(); }}", "e": 6573, "s": 5672, "text": null }, { "code": null, "e": 6587, "s": 6573, "text": "100000\n200000" }, { "code": null, "e": 6607, "s": 6587, "text": "abhishek0719kadiyan" }, { "code": null, "e": 6624, "s": 6607, "text": "arorakashish0911" }, { "code": null, "e": 6640, "s": 6624, "text": "java-interfaces" }, { "code": null, "e": 6661, "s": 6640, "text": "Java-Object Oriented" }, { "code": null, "e": 6668, "s": 6661, "text": "Picked" }, { "code": null, "e": 6673, "s": 6668, "text": "Java" }, { "code": null, "e": 6678, "s": 6673, "text": "Java" }, { "code": null, "e": 6776, "s": 6678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6791, "s": 6776, "text": "Stream In Java" }, { "code": null, "e": 6812, "s": 6791, "text": "Introduction to Java" }, { "code": null, "e": 6833, "s": 6812, "text": "Constructors in Java" }, { "code": null, "e": 6852, "s": 6833, "text": "Exceptions in Java" }, { "code": null, "e": 6869, "s": 6852, "text": "Generics in Java" }, { "code": null, "e": 6899, "s": 6869, "text": "Functional Interfaces in Java" }, { "code": null, "e": 6925, "s": 6899, "text": "Java Programming Examples" }, { "code": null, "e": 6941, "s": 6925, "text": "Strings in Java" }, { "code": null, "e": 6978, "s": 6941, "text": "Differences between JDK, JRE and JVM" } ]
Two Pointers Technique
Difficulty Level : Easy Two pointers is really an easy and effective technique that is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Illustration : A[] = {10, 20, 35, 50, 75, 80} X = =70 i = 0 j = 5 A[i] + A[j] = 10 + 80 = 90 Since A[i] + A[j] > X, j-- i = 0 j = 4 A[i] + A[j] = 10 + 75 = 85 Since A[i] + A[j] > X, j-- i = 0 j = 3 A[i] + A[j] = 10 + 50 = 60 Since A[i] + A[j] < X, i++ i = 1 j = 3 m A[i] + A[j] = 20 + 50 = 70 Thus this signifies that Pair is Found. Let us do discuss the working of two pointer algorithm in brief which is as follows. The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer ‘i’ when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j. Methods: Here we will be proposing a two-pointer algorithm by starting off with the naïve approach only in order to showcase the execution of operations going on in both methods and secondary to justify how two-pointer algorithm optimizes code via time complexities across all dynamic programming languages such as C+, Java, Python, and even JavaScript Naïve Approach using loopsOptimal approach using two pointer algorithm Naïve Approach using loops Optimal approach using two pointer algorithm Implementation: Method 1: Naïve Approach Examples C++ C Java Python3 C# Javascript // C++ Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all libraries#include <bits/stdc++.h> using namespace std; bool isPairSum(int A[], int N, int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return false;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; int arrSize = *(&arr + 1) - arr; sort(arr, arr + arrSize); // Sort the array // Function call cout << isPairSum(arr, arrSize, val); return 0;} // C Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all libraries#include <stdio.h> int isPairSum(int A[], int N, int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} // Driver Codeint main(){ int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf("%d", isPairSum(arr, arrSize, val)); return 0;} // Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Main driver method public static void main(String[] args) { // Declaring and initializing array int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; System.out.println(isPairSum(arr, arr.length, val)); } // Method 2 // To find Pairs in A[0..N-1] with given sum private static int isPairSum(int A[], int N, int X) { // Nested for loops for iterations for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // As equal i and j means same element if (i == j) // continue keyword skips the execution // for following condition continue; // Condition check if pair exists if (A[i] + A[j] == X) return 1; // By now the array is sorted if (A[i] + A[j] > X) // Break keyword to hault the execution break; } } // No pair found with given sum. return 0; }} # Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum # Method def isPairSum(A, N, X): for i in range(N): for j in range(N): # as equal i and j means same element if(i == j): continue # pair exists if (A[i] + A[j] == X): return True # as the array is sorted if (A[i] + A[j] > X): break # No pair found with given sum return 0 # Driver codearr = [2, 3, 5, 8, 9, 10, 11]val = 17 print(isPairSum(arr, len(arr), val)) # This code is contributed by maheshwaripiyush9 // C# Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sumusing System; // Main classclass GFG { // Method 1 // Main driver method public static void Main(String[] args) { // Declaring and initializing array int[] arr = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; Console.Write(isPairSum(arr, arr.Length, val)); } // Method 2 // To find Pairs in A[0..N-1] with given sum private static int isPairSum(int[] A, int N, int X) { // Nested for loops for iterations for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // As equal i and j means same element if (i == j) // continue keyword skips the execution // for following condition continue; // Condition check if pair exists if (A[i] + A[j] == X) return 1; // By now the array is sorted if (A[i] + A[j] > X) // Break keyword to hault the execution break; } } // No pair found with given sum. return 0; }} // This code is contributed by shivanisinghss2110 // JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum <script> // Naive solution to find if there is a// pair in A[0..N-1] with given sum. function isPairSum(A, N, X){ for (var i = 0; i < N-1; i++) { for (var j = i+1; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return 1; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} var arr=[ 2, 3, 5, 8, 9, 10, 11 ]; // value to search var val = 17; // size of the array var arrSize = 7; // Function call document.write(isPairSum(arr, arrSize, val)); </script> 1 Time Complexity: O(n2). Auxiliary Space: O(1) Method 2: Two Pointers Technique Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X. Examples C++ C Java Python3 C# Javascript // C++ Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing required libraries #include <iostream>#include <algorithm> using namespace std; // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Driver codeint main(){ // array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = *(&arr + 1) - arr; // array should be sorted before using two-pointer technique sort(arr, arr+7); // Function call cout << (bool)isPairSum(arr, arrSize, val); return 0;} // C Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing I/O libraries #include <stdio.h> // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // Represents first pointer int i = 0; // Represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Main method int main(){ // Array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // Custom value to be searched int val = 17; // size of the array int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf("%d", isPairSum(arr, arrSize, val)); return 0;} // Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing all utility classesimport java.io.*; // Main classclass GFG { // Two pointer technique based solution to find // if there is a pair in A[0..N-1] with a given sum. public static int isPairSum(int A[], int N, int X) { // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0; } // Driver code public static void main(String[] args) { // array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = arr.length; // Function call System.out.println(isPairSum(arr, arrSize, val)); }} # Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum# Using Two-pointers Technique # Method def isPairSum(A, N, X): # represents first pointer i = 0 # represents second pointer j = N - 1 while(i < j): # If we find a pair if (A[i] + A[j] == X): return True # If sum of elements at current # pointers is less, we move towards # higher values by doing i += 1 elif(A[i] + A[j] < X): i += 1 # If sum of elements at current # pointers is more, we move towards # lower values by doing j -= 1 else: j -= 1 return 0 # array declarationarr = [2, 3, 5, 8, 9, 10, 11] # value to searchval = 17 print(isPairSum(arr, len(arr), val)) # This code is contributed by maheshwaripiyush9. // C# Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing all utility classesusing System; // Main classclass GFG { // Two pointer technique based solution to find // if there is a pair in A[0..N-1] with a given sum. public static int isPairSum(int []A, int N, int X) { // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0; } // Driver code public static void Main(String[] args) { // array declaration int []arr = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = arr.Length; // Function call Console.Write(isPairSum(arr, arrSize, val)); }} // This code is contributed by shivanisinghss2110 // JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique <script>// Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.function isPairSum(A, N, X){ // represents first pointer var i = 0; // represents second pointer var j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return true; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return false;} // Driver code // array declaration var arr = [ 2, 3, 5, 8, 9, 10, 11 ]; // value to search var val = 17; // size of the array var arrSize =7; // Function call document.write(isPairSum(arr, arrSize, val)); // This Code is Contributed by Harshit Srivastava </script> 1 Time Complexity: O(n log n) (As sort function is used) Auxiliary Space: O(1) More problems based on two pointer technique. Find the closest pair from two sorted arrays Find the pair in array whose sum is closest to x Find all triplets with zero sum Find a triplet that sum to a given value Find a triplet such that sum of two equals to third element Find four elements that sum to a given value AkshdeepRAJAWAT raviteja2110 homer_simpson maheswaripiyush9 srivastavaharshit848 akshitsaxenaa09 roshsoftdev simmytarika5 souravseal99 shivanisinghss2110 sriramprasanth19 haishand abdirahmanahmed49 sagartomar9927 sarrransh aviralsheoran2002 codewithmini two-pointer-algorithm Arrays Searching Technical Scripter two-pointer-algorithm Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 24, "s": 0, "text": "Difficulty Level :\nEasy" }, { "code": null, "e": 301, "s": 24, "text": "Two pointers is really an easy and effective technique that is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X." }, { "code": null, "e": 317, "s": 301, "text": "Illustration : " }, { "code": null, "e": 638, "s": 317, "text": "A[] = {10, 20, 35, 50, 75, 80}\nX = =70\ni = 0\nj = 5\n\nA[i] + A[j] = 10 + 80 = 90\nSince A[i] + A[j] > X, j--\ni = 0\nj = 4\n\nA[i] + A[j] = 10 + 75 = 85\nSince A[i] + A[j] > X, j--\ni = 0\nj = 3\n\nA[i] + A[j] = 10 + 50 = 60\nSince A[i] + A[j] < X, i++\ni = 1\nj = 3\nm\nA[i] + A[j] = 20 + 50 = 70\nThus this signifies that Pair is Found." }, { "code": null, "e": 1067, "s": 638, "text": "Let us do discuss the working of two pointer algorithm in brief which is as follows. The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer ‘i’ when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j." }, { "code": null, "e": 1076, "s": 1067, "text": "Methods:" }, { "code": null, "e": 1421, "s": 1076, "text": "Here we will be proposing a two-pointer algorithm by starting off with the naïve approach only in order to showcase the execution of operations going on in both methods and secondary to justify how two-pointer algorithm optimizes code via time complexities across all dynamic programming languages such as C+, Java, Python, and even JavaScript" }, { "code": null, "e": 1493, "s": 1421, "text": "Naïve Approach using loopsOptimal approach using two pointer algorithm" }, { "code": null, "e": 1521, "s": 1493, "text": "Naïve Approach using loops" }, { "code": null, "e": 1566, "s": 1521, "text": "Optimal approach using two pointer algorithm" }, { "code": null, "e": 1582, "s": 1566, "text": "Implementation:" }, { "code": null, "e": 1609, "s": 1582, "text": "Method 1: Naïve Approach " }, { "code": null, "e": 1619, "s": 1609, "text": "Examples " }, { "code": null, "e": 1623, "s": 1619, "text": "C++" }, { "code": null, "e": 1625, "s": 1623, "text": "C" }, { "code": null, "e": 1630, "s": 1625, "text": "Java" }, { "code": null, "e": 1638, "s": 1630, "text": "Python3" }, { "code": null, "e": 1641, "s": 1638, "text": "C#" }, { "code": null, "e": 1652, "s": 1641, "text": "Javascript" }, { "code": "// C++ Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all libraries#include <bits/stdc++.h> using namespace std; bool isPairSum(int A[], int N, int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return false;} // Driver codeint main(){ int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; int arrSize = *(&arr + 1) - arr; sort(arr, arr + arrSize); // Sort the array // Function call cout << isPairSum(arr, arrSize, val); return 0;}", "e": 2532, "s": 1652, "text": null }, { "code": "// C Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all libraries#include <stdio.h> int isPairSum(int A[], int N, int X){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return true; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} // Driver Codeint main(){ int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf(\"%d\", isPairSum(arr, arrSize, val)); return 0;}", "e": 3349, "s": 2532, "text": null }, { "code": "// Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum // Importing all input output classesimport java.io.*; // Main classclass GFG { // Method 1 // Main driver method public static void main(String[] args) { // Declaring and initializing array int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; System.out.println(isPairSum(arr, arr.length, val)); } // Method 2 // To find Pairs in A[0..N-1] with given sum private static int isPairSum(int A[], int N, int X) { // Nested for loops for iterations for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // As equal i and j means same element if (i == j) // continue keyword skips the execution // for following condition continue; // Condition check if pair exists if (A[i] + A[j] == X) return 1; // By now the array is sorted if (A[i] + A[j] > X) // Break keyword to hault the execution break; } } // No pair found with given sum. return 0; }}", "e": 4641, "s": 3349, "text": null }, { "code": "# Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum # Method def isPairSum(A, N, X): for i in range(N): for j in range(N): # as equal i and j means same element if(i == j): continue # pair exists if (A[i] + A[j] == X): return True # as the array is sorted if (A[i] + A[j] > X): break # No pair found with given sum return 0 # Driver codearr = [2, 3, 5, 8, 9, 10, 11]val = 17 print(isPairSum(arr, len(arr), val)) # This code is contributed by maheshwaripiyush9", "e": 5296, "s": 4641, "text": null }, { "code": "// C# Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sumusing System; // Main classclass GFG { // Method 1 // Main driver method public static void Main(String[] args) { // Declaring and initializing array int[] arr = { 2, 3, 5, 8, 9, 10, 11 }; int val = 17; Console.Write(isPairSum(arr, arr.Length, val)); } // Method 2 // To find Pairs in A[0..N-1] with given sum private static int isPairSum(int[] A, int N, int X) { // Nested for loops for iterations for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { // As equal i and j means same element if (i == j) // continue keyword skips the execution // for following condition continue; // Condition check if pair exists if (A[i] + A[j] == X) return 1; // By now the array is sorted if (A[i] + A[j] > X) // Break keyword to hault the execution break; } } // No pair found with given sum. return 0; }} // This code is contributed by shivanisinghss2110", "e": 6595, "s": 5296, "text": null }, { "code": "// JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum <script> // Naive solution to find if there is a// pair in A[0..N-1] with given sum. function isPairSum(A, N, X){ for (var i = 0; i < N-1; i++) { for (var j = i+1; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return 1; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0;} var arr=[ 2, 3, 5, 8, 9, 10, 11 ]; // value to search var val = 17; // size of the array var arrSize = 7; // Function call document.write(isPairSum(arr, arrSize, val)); </script>", "e": 7576, "s": 6595, "text": null }, { "code": null, "e": 7578, "s": 7576, "text": "1" }, { "code": null, "e": 7603, "s": 7578, "text": "Time Complexity: O(n2)." }, { "code": null, "e": 7625, "s": 7603, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7658, "s": 7625, "text": "Method 2: Two Pointers Technique" }, { "code": null, "e": 8111, "s": 7658, "text": "Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X. " }, { "code": null, "e": 8120, "s": 8111, "text": "Examples" }, { "code": null, "e": 8124, "s": 8120, "text": "C++" }, { "code": null, "e": 8126, "s": 8124, "text": "C" }, { "code": null, "e": 8131, "s": 8126, "text": "Java" }, { "code": null, "e": 8139, "s": 8131, "text": "Python3" }, { "code": null, "e": 8142, "s": 8139, "text": "C#" }, { "code": null, "e": 8153, "s": 8142, "text": "Javascript" }, { "code": "// C++ Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing required libraries #include <iostream>#include <algorithm> using namespace std; // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Driver codeint main(){ // array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = *(&arr + 1) - arr; // array should be sorted before using two-pointer technique sort(arr, arr+7); // Function call cout << (bool)isPairSum(arr, arrSize, val); return 0;}", "e": 9442, "s": 8153, "text": null }, { "code": "// C Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing I/O libraries #include <stdio.h> // Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.int isPairSum(int A[], int N, int X){ // Represents first pointer int i = 0; // Represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0;} // Main method int main(){ // Array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // Custom value to be searched int val = 17; // size of the array int arrSize = sizeof(arr) / sizeof(arr[0]); // Function call printf(\"%d\", isPairSum(arr, arrSize, val)); return 0;}", "e": 10611, "s": 9442, "text": null }, { "code": "// Java Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing all utility classesimport java.io.*; // Main classclass GFG { // Two pointer technique based solution to find // if there is a pair in A[0..N-1] with a given sum. public static int isPairSum(int A[], int N, int X) { // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0; } // Driver code public static void main(String[] args) { // array declaration int arr[] = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = arr.length; // Function call System.out.println(isPairSum(arr, arrSize, val)); }}", "e": 11974, "s": 10611, "text": null }, { "code": "# Python Program Illustrating Naive Approach to# Find if There is a Pair in A[0..N-1] with Given Sum# Using Two-pointers Technique # Method def isPairSum(A, N, X): # represents first pointer i = 0 # represents second pointer j = N - 1 while(i < j): # If we find a pair if (A[i] + A[j] == X): return True # If sum of elements at current # pointers is less, we move towards # higher values by doing i += 1 elif(A[i] + A[j] < X): i += 1 # If sum of elements at current # pointers is more, we move towards # lower values by doing j -= 1 else: j -= 1 return 0 # array declarationarr = [2, 3, 5, 8, 9, 10, 11] # value to searchval = 17 print(isPairSum(arr, len(arr), val)) # This code is contributed by maheshwaripiyush9.", "e": 12834, "s": 11974, "text": null }, { "code": "// C# Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique // Importing all utility classesusing System; // Main classclass GFG { // Two pointer technique based solution to find // if there is a pair in A[0..N-1] with a given sum. public static int isPairSum(int []A, int N, int X) { // represents first pointer int i = 0; // represents second pointer int j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return 1; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return 0; } // Driver code public static void Main(String[] args) { // array declaration int []arr = { 2, 3, 5, 8, 9, 10, 11 }; // value to search int val = 17; // size of the array int arrSize = arr.Length; // Function call Console.Write(isPairSum(arr, arrSize, val)); }} // This code is contributed by shivanisinghss2110", "e": 14237, "s": 12834, "text": null }, { "code": "// JavaScript Program Illustrating Naive Approach to// Find if There is a Pair in A[0..N-1] with Given Sum// Using Two-pointers Technique <script>// Two pointer technique based solution to find// if there is a pair in A[0..N-1] with a given sum.function isPairSum(A, N, X){ // represents first pointer var i = 0; // represents second pointer var j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return true; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return false;} // Driver code // array declaration var arr = [ 2, 3, 5, 8, 9, 10, 11 ]; // value to search var val = 17; // size of the array var arrSize =7; // Function call document.write(isPairSum(arr, arrSize, val)); // This Code is Contributed by Harshit Srivastava </script>", "e": 15384, "s": 14237, "text": null }, { "code": null, "e": 15386, "s": 15384, "text": "1" }, { "code": null, "e": 15442, "s": 15386, "text": "Time Complexity: O(n log n) (As sort function is used)" }, { "code": null, "e": 15464, "s": 15442, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 15511, "s": 15464, "text": "More problems based on two pointer technique. " }, { "code": null, "e": 15556, "s": 15511, "text": "Find the closest pair from two sorted arrays" }, { "code": null, "e": 15605, "s": 15556, "text": "Find the pair in array whose sum is closest to x" }, { "code": null, "e": 15637, "s": 15605, "text": "Find all triplets with zero sum" }, { "code": null, "e": 15678, "s": 15637, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 15738, "s": 15678, "text": "Find a triplet such that sum of two equals to third element" }, { "code": null, "e": 15783, "s": 15738, "text": "Find four elements that sum to a given value" }, { "code": null, "e": 15799, "s": 15783, "text": "AkshdeepRAJAWAT" }, { "code": null, "e": 15812, "s": 15799, "text": "raviteja2110" }, { "code": null, "e": 15826, "s": 15812, "text": "homer_simpson" }, { "code": null, "e": 15843, "s": 15826, "text": "maheswaripiyush9" }, { "code": null, "e": 15864, "s": 15843, "text": "srivastavaharshit848" }, { "code": null, "e": 15880, "s": 15864, "text": "akshitsaxenaa09" }, { "code": null, "e": 15892, "s": 15880, "text": "roshsoftdev" }, { "code": null, "e": 15905, "s": 15892, "text": "simmytarika5" }, { "code": null, "e": 15918, "s": 15905, "text": "souravseal99" }, { "code": null, "e": 15937, "s": 15918, "text": "shivanisinghss2110" }, { "code": null, "e": 15954, "s": 15937, "text": "sriramprasanth19" }, { "code": null, "e": 15963, "s": 15954, "text": "haishand" }, { "code": null, "e": 15981, "s": 15963, "text": "abdirahmanahmed49" }, { "code": null, "e": 15996, "s": 15981, "text": "sagartomar9927" }, { "code": null, "e": 16006, "s": 15996, "text": "sarrransh" }, { "code": null, "e": 16024, "s": 16006, "text": "aviralsheoran2002" }, { "code": null, "e": 16037, "s": 16024, "text": "codewithmini" }, { "code": null, "e": 16059, "s": 16037, "text": "two-pointer-algorithm" }, { "code": null, "e": 16066, "s": 16059, "text": "Arrays" }, { "code": null, "e": 16076, "s": 16066, "text": "Searching" }, { "code": null, "e": 16095, "s": 16076, "text": "Technical Scripter" }, { "code": null, "e": 16117, "s": 16095, "text": "two-pointer-algorithm" }, { "code": null, "e": 16124, "s": 16117, "text": "Arrays" }, { "code": null, "e": 16134, "s": 16124, "text": "Searching" }, { "code": null, "e": 16232, "s": 16134, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16247, "s": 16232, "text": "Arrays in Java" }, { "code": null, "e": 16293, "s": 16247, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 16361, "s": 16293, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 16405, "s": 16361, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 16437, "s": 16405, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 16451, "s": 16437, "text": "Binary Search" }, { "code": null, "e": 16519, "s": 16451, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 16533, "s": 16519, "text": "Linear Search" }, { "code": null, "e": 16581, "s": 16533, "text": "Search an element in a sorted and rotated array" } ]
What is ObjectId in MongoDB
01 Nov, 2020 Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document. An ObjectID is a 12-byte Field Of BSON type The first 4 bytes representing the Unix Timestamp of the document The next 3 bytes are the machine Id on which the MongoDB server is running. The next 2 bytes are of process id The last Field is 3 bytes used for increment the objectid. Format of ObjectId: ObjectId(<hexadecimal>) ObjectId accepts one parameter which is optional Hexadecimal ObjectId in String. We can give our own ObjectId to the document but it must be unique. *db.<collectionname>.insertOne({"_id":"231231"}) Example: Database : gfg Collection: student_gfg Methods of ObjectId: str: Returns the hexadecimal string format of the ObjectIdObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date.ObjectId.valueOf(): It return the hexadecimal format of a given String Literal.ObjectId.toString(): This method returns ObjectId in String format in javascript representation. str: Returns the hexadecimal string format of the ObjectId ObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date. ObjectId.valueOf(): It return the hexadecimal format of a given String Literal. ObjectId.toString(): This method returns ObjectId in String format in javascript representation. 1.Creating ObjectId: To generate new ObjectId of particular document. newObjectId = ObjectId() Output: ObjectId(“5f92cbf10cf217478ba93561”) 2.Timestamp of the ObjectID: It returns the timestamp information of the object as a Date in ISO format. var id =new ObjectId(); id.getTimestamp() Output: ISODate(“2020-10-23T12:32:42Z”) 3.Converting ObjectId to string: ObjectId can be converted into string format. new ObjectId().str Output: 5f92cdce0cf217478ba93563 Technical Scripter 2020 MongoDB Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Nov, 2020" }, { "code": null, "e": 332, "s": 52, "text": "Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document." }, { "code": null, "e": 376, "s": 332, "text": "An ObjectID is a 12-byte Field Of BSON type" }, { "code": null, "e": 442, "s": 376, "text": "The first 4 bytes representing the Unix Timestamp of the document" }, { "code": null, "e": 518, "s": 442, "text": "The next 3 bytes are the machine Id on which the MongoDB server is running." }, { "code": null, "e": 553, "s": 518, "text": "The next 2 bytes are of process id" }, { "code": null, "e": 612, "s": 553, "text": "The last Field is 3 bytes used for increment the objectid." }, { "code": null, "e": 632, "s": 612, "text": "Format of ObjectId:" }, { "code": null, "e": 657, "s": 632, "text": "ObjectId(<hexadecimal>)\n" }, { "code": null, "e": 738, "s": 657, "text": "ObjectId accepts one parameter which is optional Hexadecimal ObjectId in String." }, { "code": null, "e": 806, "s": 738, "text": "We can give our own ObjectId to the document but it must be unique." }, { "code": null, "e": 856, "s": 806, "text": "*db.<collectionname>.insertOne({\"_id\":\"231231\"})\n" }, { "code": null, "e": 865, "s": 856, "text": "Example:" }, { "code": null, "e": 880, "s": 865, "text": "Database : gfg" }, { "code": null, "e": 904, "s": 880, "text": "Collection: student_gfg" }, { "code": null, "e": 925, "s": 904, "text": "Methods of ObjectId:" }, { "code": null, "e": 1242, "s": 925, "text": "str: Returns the hexadecimal string format of the ObjectIdObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date.ObjectId.valueOf(): It return the hexadecimal format of a given String Literal.ObjectId.toString(): This method returns ObjectId in String format in javascript representation." }, { "code": null, "e": 1301, "s": 1242, "text": "str: Returns the hexadecimal string format of the ObjectId" }, { "code": null, "e": 1385, "s": 1301, "text": "ObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date." }, { "code": null, "e": 1465, "s": 1385, "text": "ObjectId.valueOf(): It return the hexadecimal format of a given String Literal." }, { "code": null, "e": 1562, "s": 1465, "text": "ObjectId.toString(): This method returns ObjectId in String format in javascript representation." }, { "code": null, "e": 1632, "s": 1562, "text": "1.Creating ObjectId: To generate new ObjectId of particular document." }, { "code": null, "e": 1657, "s": 1632, "text": "newObjectId = ObjectId()" }, { "code": null, "e": 1665, "s": 1657, "text": "Output:" }, { "code": null, "e": 1702, "s": 1665, "text": "ObjectId(“5f92cbf10cf217478ba93561”)" }, { "code": null, "e": 1807, "s": 1702, "text": "2.Timestamp of the ObjectID: It returns the timestamp information of the object as a Date in ISO format." }, { "code": null, "e": 1835, "s": 1807, "text": "var id =new ObjectId(); " }, { "code": null, "e": 1854, "s": 1835, "text": " id.getTimestamp()" }, { "code": null, "e": 1862, "s": 1854, "text": "Output:" }, { "code": null, "e": 1894, "s": 1862, "text": "ISODate(“2020-10-23T12:32:42Z”)" }, { "code": null, "e": 1973, "s": 1894, "text": "3.Converting ObjectId to string: ObjectId can be converted into string format." }, { "code": null, "e": 1993, "s": 1973, "text": " new ObjectId().str" }, { "code": null, "e": 2001, "s": 1993, "text": "Output:" }, { "code": null, "e": 2026, "s": 2001, "text": "5f92cdce0cf217478ba93563" }, { "code": null, "e": 2050, "s": 2026, "text": "Technical Scripter 2020" }, { "code": null, "e": 2058, "s": 2050, "text": "MongoDB" }, { "code": null, "e": 2077, "s": 2058, "text": "Technical Scripter" } ]
Even Fibonacci Numbers Sum | Practice | GeeksforGeeks
Given a number N find the sum of all the even valued terms in the Fibonacci sequence less than or equal to N. The first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,... (Even numbers are highlighted). Example 1: Input: N = 8 Output: 10 Explanation: There are two even fibonacci numbers less than equal to 8, 8 and 2 and 8 + 2 = 10 Example 2: Input: N = 89 Output: 44 Explanation: There are three even fibonacci numbers less than equal to 89, 8, 2 and 34 8 + 2 + 34 = 44 Your Task: You don't need to read input or print anything. Your task is to complete the function evenFibSum() which takes an integer N as input parameters and returns the sum of all the Fibonacci number less than equal to N. Expected Time Complexity: O(N) Expected Space Complexity: O(1) Constraints: 1 <= N <= 106 0 dasilashubham392 weeks ago Easy Java Solution ---→ class Solution{ static long evenFibSum(long N){ // code here long a=1; long b=1; long c=1; long sum=0; long mod=1000000007; while(c<=N){ c=(a+b)%mod; if(N>=c && c%2==0){ sum+=c; } a=b; b=c; } return sum; } }; +1 pketul22127 months ago Total Time Taken: 0.1 class Solution{ static long evenFibSum(long N){ long sum = 2, a = 1, b = 2, temp = 0; while(N > temp) { temp = a + b; a = b; b = temp; if(N > temp && temp % 2 == 0) sum += temp; } return sum; } } 0 saivishnu1289 months ago class Solution{public: long long evenFibSum(int N){ int s=0,a=0,b=1,c=a+b; while(c<=N) { c=a+b; a=b; b=c; if(c%2==0&&c<=N) { s=s+c; } } return s; // code here }}; 0 ANKIT SINHA11 months agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading... ANKIT SINHA https://uploads.disquscdn.c... 0 Dharmendra Kumar2 years agoexecution time: 0.01 long long a=1,b=0; int sum=0; for(int i=1;i<=N;i++){ if(a%2==0) sum = sum + a; a=a+b; b=a-b; if(a>N) break; } return sum;Reply Open ExternallyShow 0 RepliesLoading... Dharmendra Kumar execution time: 0.01 long long a=1,b=0; int sum=0; for(int i=1;i<=N;i++){ if(a%2==0) sum = sum + a; a=a+b; b=a-b; if(a>N) break; } return sum; 0 Lakhvinder Singh2 years agoc++ 0.01#include <iostream>using namespace std;typedef long long ll;int main() {ll f3 = 1,f2 = 1,f1 = 0;ll dp[1000001] = {0};int i = 1;while(i<=1000000){ if(f3<=i) { if(f3%2==0) { dp[i] = dp[i-1]+f3; } else { dp[i] = dp[i-1]; } f3 = f2+f1; f1 = f2; f2 = f3; } else { dp[i] = dp[i-1]; } i++;}int t;cin>>t;while(t--){ int n; cin>>n; cout<<dp[n]<<endl; }="" return="" 0;="" }="" <="" code="">Reply Open ExternallyShow 0 RepliesLoading... Lakhvinder Singh c++ 0.01#include <iostream>using namespace std;typedef long long ll;int main() {ll f3 = 1,f2 = 1,f1 = 0;ll dp[1000001] = {0};int i = 1;while(i<=1000000){ if(f3<=i) { if(f3%2==0) { dp[i] = dp[i-1]+f3; } else { dp[i] = dp[i-1]; } f3 = f2+f1; f1 = f2; f2 = f3; } else { dp[i] = dp[i-1]; } i++;}int t;cin>>t;while(t--){ int n; cin>>n; cout<<dp[n]<<endl; }="" return="" 0;="" }="" <="" code=""> 0 Jainav2 years agoWould like to know about a better solution to this than:#include <iostream>using namespace std;int main() {//codeint t;cin>>t;while(t--){ int n; cin>>n; unsigned int a = 1, b = 1,c=0; while(n>=a+b){ c = c+a+b; a = a+2*b; b = 2*a-b; } cout<<c<<endl; }="" return="" 0;="" }="">Reply Open ExternallyShow 0 RepliesLoading... Jainav Would like to know about a better solution to this than:#include <iostream>using namespace std; int main() {//codeint t;cin>>t;while(t--){ int n; cin>>n; unsigned int a = 1, b = 1,c=0; while(n>=a+b){ c = c+a+b; a = a+2*b; b = 2*a-b; } cout<<c<<endl; }="" return="" 0;="" }=""> 0 Harsh K2 years ago#include <bits stdc++.h="">using namespace std;typedef long long ll;int main() {//codeint t;cin>>t;while(t--){ int n;cin>>n; ll dp[n]; dp[0]=1; dp[1]=1; unsigned long long ans=0; for(int i=2;i<n;i++) {="" dp[i]="dp[i-1]+dp[i-2];" if(dp[i]%2="=0" &&="" dp[i]<="n)" ans+="dp[i];" if(dp[i]="">n) break; } cout<<ans<<endl; }="" return="" 0;="" }="">Reply Open ExternallyShow 0 RepliesLoading... Harsh K #include <bits stdc++.h="">using namespace std; typedef long long ll; int main() {//codeint t;cin>>t;while(t--){ int n;cin>>n; ll dp[n]; dp[0]=1; dp[1]=1; unsigned long long ans=0; for(int i=2;i<n;i++) {="" dp[i]="dp[i-1]+dp[i-2];" if(dp[i]%2="=0" &&="" dp[i]<="n)" ans+="dp[i];" if(dp[i]="">n) break; } cout<<ans<<endl; }="" return="" 0;="" }=""> 0 Soumya Sekhar2 years agofor the 2nd case:the sum must be greater than 400But in question it is given 188 which is less than 400Reply Open ExternallyShow 1 RepliesLoading... Soumya Sekhar for the 2nd case:the sum must be greater than 400But in question it is given 188 which is less than 400 0 Abhinay Lakhera2 years agotry this one....long long int t;cin>>t;while(t--){ long long int n; cin>>n; long long int x[n]; long long int s=0; for(long long int i=1;i<=n;i++) { x[1]=1; x[2]=1; if(i>2) x[i]=x[i-1]+x[i-2]; if(x[i]%2==0&&x[i]<=n) s=s+x[i]; if(x[i]>n) { break; } } cout<<s<<endl; }="" return="" 0;="">Reply Open ExternallyShow 0 RepliesLoading... Abhinay Lakhera try this one.... long long int t;cin>>t;while(t--){ long long int n; cin>>n; long long int x[n]; long long int s=0; for(long long int i=1;i<=n;i++) { x[1]=1; x[2]=1; if(i>2) x[i]=x[i-1]+x[i-2]; if(x[i]%2==0&&x[i]<=n) s=s+x[i]; if(x[i]>n) { break; } } cout<<s<<endl; }="" return="" 0;=""> We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 480, "s": 238, "text": "Given a number N find the sum of all the even valued terms in the Fibonacci sequence less than or equal to N.\nThe first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,... (Even numbers are highlighted).\n " }, { "code": null, "e": 491, "s": 480, "text": "Example 1:" }, { "code": null, "e": 612, "s": 491, "text": "Input:\nN = 8\nOutput:\n10\nExplanation:\nThere are two even \nfibonacci numbers less\nthan equal to 8, 8 and 2 \nand 8 + 2 = 10" }, { "code": null, "e": 623, "s": 612, "text": "Example 2:" }, { "code": null, "e": 752, "s": 623, "text": "Input:\nN = 89\nOutput:\n44\nExplanation:\nThere are three even\nfibonacci numbers less than\nequal to 89, 8, 2 and 34 \n8 + 2 + 34 = 44" }, { "code": null, "e": 980, "s": 752, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function evenFibSum() which takes an integer N as input parameters and returns the sum of all the Fibonacci number less than equal to N.\n " }, { "code": null, "e": 1045, "s": 980, "text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 1072, "s": 1045, "text": "Constraints:\n1 <= N <= 106" }, { "code": null, "e": 1074, "s": 1072, "text": "0" }, { "code": null, "e": 1101, "s": 1074, "text": "dasilashubham392 weeks ago" }, { "code": null, "e": 1125, "s": 1101, "text": "Easy Java Solution ---→" }, { "code": null, "e": 1463, "s": 1125, "text": "class Solution{ static long evenFibSum(long N){ // code here long a=1; long b=1; long c=1; long sum=0; long mod=1000000007; while(c<=N){ c=(a+b)%mod; if(N>=c && c%2==0){ sum+=c; } a=b; b=c; } return sum; } };" }, { "code": null, "e": 1466, "s": 1463, "text": "+1" }, { "code": null, "e": 1489, "s": 1466, "text": "pketul22127 months ago" }, { "code": null, "e": 1511, "s": 1489, "text": "Total Time Taken: 0.1" }, { "code": null, "e": 1852, "s": 1511, "text": "class Solution{\n static long evenFibSum(long N){\n \n long sum = 2, a = 1, b = 2, temp = 0;\n \n while(N > temp) {\n temp = a + b;\n a = b;\n b = temp;\n \n if(N > temp && temp % 2 == 0)\n sum += temp;\n }\n \n return sum;\n } \n}" }, { "code": null, "e": 1854, "s": 1852, "text": "0" }, { "code": null, "e": 1879, "s": 1854, "text": "saivishnu1289 months ago" }, { "code": null, "e": 2156, "s": 1879, "text": "class Solution{public: long long evenFibSum(int N){ int s=0,a=0,b=1,c=a+b; while(c<=N) { c=a+b; a=b; b=c; if(c%2==0&&c<=N) { s=s+c; } } return s; // code here }};" }, { "code": null, "e": 2158, "s": 2156, "text": "0" }, { "code": null, "e": 2258, "s": 2158, "text": "ANKIT SINHA11 months agohttps://uploads.disquscdn.c...Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 2270, "s": 2258, "text": "ANKIT SINHA" }, { "code": null, "e": 2301, "s": 2270, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 2303, "s": 2301, "text": "0" }, { "code": null, "e": 2600, "s": 2303, "text": "Dharmendra Kumar2 years agoexecution time: 0.01 long long a=1,b=0; int sum=0; for(int i=1;i<=N;i++){ if(a%2==0) sum = sum + a; a=a+b; b=a-b; if(a>N) break; } return sum;Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 2617, "s": 2600, "text": "Dharmendra Kumar" }, { "code": null, "e": 2638, "s": 2617, "text": "execution time: 0.01" }, { "code": null, "e": 2843, "s": 2638, "text": " long long a=1,b=0; int sum=0; for(int i=1;i<=N;i++){ if(a%2==0) sum = sum + a; a=a+b; b=a-b; if(a>N) break; } return sum;" }, { "code": null, "e": 2845, "s": 2843, "text": "0" }, { "code": null, "e": 3429, "s": 2845, "text": "Lakhvinder Singh2 years agoc++ 0.01#include <iostream>using namespace std;typedef long long ll;int main() {ll f3 = 1,f2 = 1,f1 = 0;ll dp[1000001] = {0};int i = 1;while(i<=1000000){ if(f3<=i) { if(f3%2==0) { dp[i] = dp[i-1]+f3; } else { dp[i] = dp[i-1]; } f3 = f2+f1; f1 = f2; f2 = f3; } else { dp[i] = dp[i-1]; } i++;}int t;cin>>t;while(t--){ int n; cin>>n; cout<<dp[n]<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 3446, "s": 3429, "text": "Lakhvinder Singh" }, { "code": null, "e": 3958, "s": 3446, "text": "c++ 0.01#include <iostream>using namespace std;typedef long long ll;int main() {ll f3 = 1,f2 = 1,f1 = 0;ll dp[1000001] = {0};int i = 1;while(i<=1000000){ if(f3<=i) { if(f3%2==0) { dp[i] = dp[i-1]+f3; } else { dp[i] = dp[i-1]; } f3 = f2+f1; f1 = f2; f2 = f3; } else { dp[i] = dp[i-1]; } i++;}int t;cin>>t;while(t--){ int n; cin>>n; cout<<dp[n]<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\" <=\"\" code=\"\">" }, { "code": null, "e": 3960, "s": 3958, "text": "0" }, { "code": null, "e": 4346, "s": 3960, "text": "Jainav2 years agoWould like to know about a better solution to this than:#include <iostream>using namespace std;int main() {//codeint t;cin>>t;while(t--){ int n; cin>>n; unsigned int a = 1, b = 1,c=0; while(n>=a+b){ c = c+a+b; a = a+2*b; b = 2*a-b; } cout<<c<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 4353, "s": 4346, "text": "Jainav" }, { "code": null, "e": 4449, "s": 4353, "text": "Would like to know about a better solution to this than:#include <iostream>using namespace std;" }, { "code": null, "e": 4678, "s": 4449, "text": "int main() {//codeint t;cin>>t;while(t--){ int n; cin>>n; unsigned int a = 1, b = 1,c=0; while(n>=a+b){ c = c+a+b; a = a+2*b; b = 2*a-b; } cout<<c<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 4680, "s": 4678, "text": "0" }, { "code": null, "e": 5119, "s": 4680, "text": "Harsh K2 years ago#include <bits stdc++.h=\"\">using namespace std;typedef long long ll;int main() {//codeint t;cin>>t;while(t--){ int n;cin>>n; ll dp[n]; dp[0]=1; dp[1]=1; unsigned long long ans=0; for(int i=2;i<n;i++) {=\"\" dp[i]=\"dp[i-1]+dp[i-2];\" if(dp[i]%2=\"=0\" &&=\"\" dp[i]<=\"n)\" ans+=\"dp[i];\" if(dp[i]=\"\">n) break; } cout<<ans<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 5127, "s": 5119, "text": "Harsh K" }, { "code": null, "e": 5175, "s": 5127, "text": "#include <bits stdc++.h=\"\">using namespace std;" }, { "code": null, "e": 5197, "s": 5175, "text": "typedef long long ll;" }, { "code": null, "e": 5505, "s": 5197, "text": "int main() {//codeint t;cin>>t;while(t--){ int n;cin>>n; ll dp[n]; dp[0]=1; dp[1]=1; unsigned long long ans=0; for(int i=2;i<n;i++) {=\"\" dp[i]=\"dp[i-1]+dp[i-2];\" if(dp[i]%2=\"=0\" &&=\"\" dp[i]<=\"n)\" ans+=\"dp[i];\" if(dp[i]=\"\">n) break; } cout<<ans<<endl; }=\"\" return=\"\" 0;=\"\" }=\"\">" }, { "code": null, "e": 5507, "s": 5505, "text": "0" }, { "code": null, "e": 5680, "s": 5507, "text": "Soumya Sekhar2 years agofor the 2nd case:the sum must be greater than 400But in question it is given 188 which is less than 400Reply Open ExternallyShow 1 RepliesLoading..." }, { "code": null, "e": 5694, "s": 5680, "text": "Soumya Sekhar" }, { "code": null, "e": 5798, "s": 5694, "text": "for the 2nd case:the sum must be greater than 400But in question it is given 188 which is less than 400" }, { "code": null, "e": 5800, "s": 5798, "text": "0" }, { "code": null, "e": 6271, "s": 5800, "text": "Abhinay Lakhera2 years agotry this one....long long int t;cin>>t;while(t--){ long long int n; cin>>n; long long int x[n]; long long int s=0; for(long long int i=1;i<=n;i++) { x[1]=1; x[2]=1; if(i>2) x[i]=x[i-1]+x[i-2]; if(x[i]%2==0&&x[i]<=n) s=s+x[i]; if(x[i]>n) { break; } } cout<<s<<endl; }=\"\" return=\"\" 0;=\"\">Reply Open ExternallyShow 0 RepliesLoading..." }, { "code": null, "e": 6287, "s": 6271, "text": "Abhinay Lakhera" }, { "code": null, "e": 6304, "s": 6287, "text": "try this one...." }, { "code": null, "e": 6688, "s": 6304, "text": "long long int t;cin>>t;while(t--){ long long int n; cin>>n; long long int x[n]; long long int s=0; for(long long int i=1;i<=n;i++) { x[1]=1; x[2]=1; if(i>2) x[i]=x[i-1]+x[i-2]; if(x[i]%2==0&&x[i]<=n) s=s+x[i]; if(x[i]>n) { break; } } cout<<s<<endl; }=\"\" return=\"\" 0;=\"\">" }, { "code": null, "e": 6834, "s": 6688, "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": 6870, "s": 6834, "text": " Login to access your submissions. " }, { "code": null, "e": 6880, "s": 6870, "text": "\nProblem\n" }, { "code": null, "e": 6890, "s": 6880, "text": "\nContest\n" }, { "code": null, "e": 6953, "s": 6890, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7138, "s": 6953, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7422, "s": 7138, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7568, "s": 7422, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7645, "s": 7568, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7686, "s": 7645, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7714, "s": 7686, "text": "Disable browser extensions." }, { "code": null, "e": 7785, "s": 7714, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7972, "s": 7785, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
How to use componentWillMount() in React Hooks?
09 Feb, 2021 The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a hook based component. To use the functionality of the class-based methods, React hooks provides the alternative like useEffect Hook for componentDidMount, componentDidUpdate, and componentWillUnmount combined but for componentWillMount(), no such hook is provided even in the official React Docs. ComponentWillMount() will go to be deprecated in the future releases of the React as per this issue. It is suggested to use ComponentDidMount() or useEffect hook as its alternative but you can still use ComponentWillMount() by calling it as UNSAFE_ComponentWillMount(). ComponentWillMount() is generally used to show a loader when the component is being loaded or when the data from the server is being fetched but once it will get completely deprecated then we can use SuspenseAPI as a better alternative. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app functiondemo Step 2: After creating your project folder i.e. functiondemo, move to it using the following command: cd functiondemo Project Structure: It will look like the following. Project Structure Example: In this example, we are going to build an application that logs the message when the component is rendered in the DOM tree. App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Using componentWillMount() Method: Javascript import React from 'react'; class ComponentOne extends React.Component { UNSAFE_componentWillMount() { console.log('Component is mounted in the DOM'); } render() { return <h1>Hello Geeks!</h1>; }} class App extends React.Component { render() { return ( <div> <ComponentOne /> </div> ); }} export default App; Alternative Using useLayoutEffect() Method: Javascript import React, { useLayoutEffect } from 'react'; const ComponentOne = () => { // Defining the useLayoutEffect hook useLayoutEffect(() => { console.log('Component is mounted in the DOM'); }, []); return <h1>Hello Geeks!</h1>;}; const App = () => { return ( <div> <ComponentOne /> </div> );}; export default App; Note: You can define your own styling in the App.css file. Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Output Picked React-Questions ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? How to Use Bootstrap with React? React-Router Hooks How to navigate on path by button click in react router ? How to check the version of ReactJS ? Destructuring of Props in ReactJS
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Feb, 2021" }, { "code": null, "e": 285, "s": 53, "text": "The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle" }, { "code": null, "e": 697, "s": 285, "text": "You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a hook based component. To use the functionality of the class-based methods, React hooks provides the alternative like useEffect Hook for componentDidMount, componentDidUpdate, and componentWillUnmount combined but for componentWillMount(), no such hook is provided even in the official React Docs." }, { "code": null, "e": 967, "s": 697, "text": "ComponentWillMount() will go to be deprecated in the future releases of the React as per this issue. It is suggested to use ComponentDidMount() or useEffect hook as its alternative but you can still use ComponentWillMount() by calling it as UNSAFE_ComponentWillMount()." }, { "code": null, "e": 1204, "s": 967, "text": "ComponentWillMount() is generally used to show a loader when the component is being loaded or when the data from the server is being fetched but once it will get completely deprecated then we can use SuspenseAPI as a better alternative." }, { "code": null, "e": 1232, "s": 1204, "text": "Creating React Application:" }, { "code": null, "e": 1296, "s": 1232, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1330, "s": 1296, "text": "npx create-react-app functiondemo" }, { "code": null, "e": 1432, "s": 1330, "text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:" }, { "code": null, "e": 1448, "s": 1432, "text": "cd functiondemo" }, { "code": null, "e": 1500, "s": 1448, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1518, "s": 1500, "text": "Project Structure" }, { "code": null, "e": 1651, "s": 1518, "text": "Example: In this example, we are going to build an application that logs the message when the component is rendered in the DOM tree." }, { "code": null, "e": 1780, "s": 1651, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 1815, "s": 1780, "text": "Using componentWillMount() Method:" }, { "code": null, "e": 1826, "s": 1815, "text": "Javascript" }, { "code": "import React from 'react'; class ComponentOne extends React.Component { UNSAFE_componentWillMount() { console.log('Component is mounted in the DOM'); } render() { return <h1>Hello Geeks!</h1>; }} class App extends React.Component { render() { return ( <div> <ComponentOne /> </div> ); }} export default App;", "e": 2172, "s": 1826, "text": null }, { "code": null, "e": 2216, "s": 2172, "text": "Alternative Using useLayoutEffect() Method:" }, { "code": null, "e": 2227, "s": 2216, "text": "Javascript" }, { "code": "import React, { useLayoutEffect } from 'react'; const ComponentOne = () => { // Defining the useLayoutEffect hook useLayoutEffect(() => { console.log('Component is mounted in the DOM'); }, []); return <h1>Hello Geeks!</h1>;}; const App = () => { return ( <div> <ComponentOne /> </div> );}; export default App;", "e": 2562, "s": 2227, "text": null }, { "code": null, "e": 2621, "s": 2562, "text": "Note: You can define your own styling in the App.css file." }, { "code": null, "e": 2734, "s": 2621, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2744, "s": 2734, "text": "npm start" }, { "code": null, "e": 2753, "s": 2744, "text": "Output: " }, { "code": null, "e": 2760, "s": 2753, "text": "Output" }, { "code": null, "e": 2767, "s": 2760, "text": "Picked" }, { "code": null, "e": 2783, "s": 2767, "text": "React-Questions" }, { "code": null, "e": 2791, "s": 2783, "text": "ReactJS" }, { "code": null, "e": 2889, "s": 2791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2927, "s": 2889, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2954, "s": 2927, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2993, "s": 2954, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 3045, "s": 2993, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 3084, "s": 3045, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 3117, "s": 3084, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 3136, "s": 3117, "text": "React-Router Hooks" }, { "code": null, "e": 3194, "s": 3136, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 3232, "s": 3194, "text": "How to check the version of ReactJS ?" } ]
PHP | mime_content_type() function
15 Jul, 2019 The mime_content_type() function is an inbuilt function in PHP which is used to get the MIME content-type of a file. Syntax: string mime_content_type( $file ) Parameters: This function accepts single parameter $file which specifies the path of the file which MIME details to be find. Return Value: This function returns the MIME content type or False on failure. Below programs illustrate the mime_content_type() function in PHP: Program 1:Original Image: <?php // PHP program to illustrate mime_content_type function echo mime_content_type('gfg.png') . "</br>";?> Output: image/png Program 2:Original Image: <?php // PHP program to illustrate // mime_content_type function // Providing and print result of different kind of files echo mime_content_type('/home/rajvir/Desktop/gfg.png') . "</br>";echo mime_content_type('/home/rajvir/Desktop/gfg_Article.html') . "</br>";echo mime_content_type('/home/rajvir/Downloads/gfg.gif') . "</br>";echo mime_content_type('/home/rajvir/Desktop/gfg_contribute.txt') . "</br>";echo mime_content_type('/home/rajvir/Downloads/geeks.ppt') . "</br>";echo mime_content_type('/home/rajvir/Downloads/geeks.pdf') . "</br>"; ?> Output: image/png text/plain image/gif text/plain application/vnd.ms-powerpoint application/pdf Reference: http://php.net/manual/en/function.mime-content-type.php ManasChhabra2 PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to get parameters from a URL string in PHP? Download file from URL using PHP Split a comma delimited string into an array in PHP 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": "\n15 Jul, 2019" }, { "code": null, "e": 145, "s": 28, "text": "The mime_content_type() function is an inbuilt function in PHP which is used to get the MIME content-type of a file." }, { "code": null, "e": 153, "s": 145, "text": "Syntax:" }, { "code": null, "e": 187, "s": 153, "text": "string mime_content_type( $file )" }, { "code": null, "e": 312, "s": 187, "text": "Parameters: This function accepts single parameter $file which specifies the path of the file which MIME details to be find." }, { "code": null, "e": 391, "s": 312, "text": "Return Value: This function returns the MIME content type or False on failure." }, { "code": null, "e": 458, "s": 391, "text": "Below programs illustrate the mime_content_type() function in PHP:" }, { "code": null, "e": 484, "s": 458, "text": "Program 1:Original Image:" }, { "code": "<?php // PHP program to illustrate mime_content_type function echo mime_content_type('gfg.png') . \"</br>\";?>", "e": 595, "s": 484, "text": null }, { "code": null, "e": 603, "s": 595, "text": "Output:" }, { "code": null, "e": 614, "s": 603, "text": "image/png\n" }, { "code": null, "e": 640, "s": 614, "text": "Program 2:Original Image:" }, { "code": "<?php // PHP program to illustrate // mime_content_type function // Providing and print result of different kind of files echo mime_content_type('/home/rajvir/Desktop/gfg.png') . \"</br>\";echo mime_content_type('/home/rajvir/Desktop/gfg_Article.html') . \"</br>\";echo mime_content_type('/home/rajvir/Downloads/gfg.gif') . \"</br>\";echo mime_content_type('/home/rajvir/Desktop/gfg_contribute.txt') . \"</br>\";echo mime_content_type('/home/rajvir/Downloads/geeks.ppt') . \"</br>\";echo mime_content_type('/home/rajvir/Downloads/geeks.pdf') . \"</br>\"; ?>", "e": 1189, "s": 640, "text": null }, { "code": null, "e": 1197, "s": 1189, "text": "Output:" }, { "code": null, "e": 1286, "s": 1197, "text": "image/png\ntext/plain\nimage/gif\ntext/plain\napplication/vnd.ms-powerpoint\napplication/pdf\n" }, { "code": null, "e": 1353, "s": 1286, "text": "Reference: http://php.net/manual/en/function.mime-content-type.php" }, { "code": null, "e": 1367, "s": 1353, "text": "ManasChhabra2" }, { "code": null, "e": 1380, "s": 1367, "text": "PHP-function" }, { "code": null, "e": 1384, "s": 1380, "text": "PHP" }, { "code": null, "e": 1401, "s": 1384, "text": "Web Technologies" }, { "code": null, "e": 1405, "s": 1401, "text": "PHP" }, { "code": null, "e": 1503, "s": 1405, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1543, "s": 1503, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 1588, "s": 1543, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 1636, "s": 1588, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 1669, "s": 1636, "text": "Download file from URL using PHP" }, { "code": null, "e": 1721, "s": 1669, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 1754, "s": 1721, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1816, "s": 1754, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1877, "s": 1816, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1927, "s": 1877, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
time.sleep() in Python
08 Oct, 2021 Python time sleep() function suspends execution for the given number of seconds. Sometimes, there is a need to halt the flow of the program so that several other executions can take place or simply due to the utility required. sleep() can come handy in such a situation which provides an accurate and flexible way to halt the flow of code for any period of time. This function discusses the insight of this function. Syntax : sleep(sec) Parameters : sec : Number of seconds for which the code is required to be stopped. Returns : VOID. Python3 # Python code to demonstrate# working of sleep() import time # printing the start timeprint("The time of code execution begin is : ", end="")print(time.ctime()) # using sleep() to hault the code executiontime.sleep(6) # printing the end timeprint("The time of code execution end is : ", end="")print(time.ctime()) Output: The time of code execution begin is : Mon Apr 9 20:57:10 2018 The time of code execution end is : Mon Apr 9 20:57:16 2018 Application : There are many applications that sleep() is used for. Be its execution of the background thread which is repeated at regular intervals, this can be implemented with the help of sleep(). Another popular application is using sleep() to print the words letter by letter for a good user interface. The latter is represented from the code below. Python3 # Python code to demonstrate# application of sleep() import time # initializing stringstrn = "GeeksforGeeks" # printing geeksforgeeks after delay# of each characterfor i in range(0, len(strn)): print(strn[i], end="") time.sleep(2) Output: GeeksForGeeks Note : Visible effect of sleep() can be seen in the local editor. Python3 # importing time packageimport time # creating a time delay of 5 secondstime.sleep(5) # creating and Initializing a listmyList = ['Jai', 'Shree', 'RAM', 5, 'August', 2020] # the list will be displayed after the# delay of 5 secondsprint(myList) Output: After the delay of 5 seconds, we will get the output as: ['Jai', 'Shree', 'RAM', 5, 'August', 2020] Python3 # importing time packageimport time # creating a time delay of 4 secondstime.sleep(4) # creating and Initializing a tuplemytuple = ('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne') # the tuple will be displayed after the delay of 4 secondsprint(mytuple) Output: After the delay of 4 seconds, we will get the output as: ('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne') Python3 # importing time packageimport time # creating and Initializing a listLanguages = ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] # creating a time delay of 5 secondstime.sleep(5) # the list will be displayed after the delay of 5 secondsprint(Languages) for lan in Languages: # creating a time delay of 13 seconds time.sleep(13) # After every 13 seconds an item of list will be displayed print(lan) Output: After the delay of 5 seconds, the list will be displayed as: ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] Then after every 13 seconds, the items of the list will be displayed as: Java C++ Python Javascript C# C Kotlin Python3 # importing time packageimport time # creating and Initializing a listcricketers = ['Anil Kumble', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne'] # time delay of 7 seconds is created# after every 7 seconds item of list gets displayedcricketers = [(time.sleep(7), print(cric)) for cric in cricketers] Output: After every 7 seconds, the items of the list will be displayed as: Anil Kumble Sachin Tendulkar Sunil Gavaskar Rahul Dravid Mahendra Singh Dhoni Dennis Lillee Muttiah Muralitharan Shane Warne Python3 # importing time packageimport time # creating and Initializing a listLanguages = ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] # creating a time delay of 3 minutestime.sleep(3 * 60) # the list will be displayed after the delay# of 3 minutesprint(Languages) Output: After the delay of 3 minutes, the list will be displayed as: ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] vanshgaur14866 rajeev0719singh kumar_satyam Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Oct, 2021" }, { "code": null, "e": 135, "s": 53, "text": "Python time sleep() function suspends execution for the given number of seconds. " }, { "code": null, "e": 471, "s": 135, "text": "Sometimes, there is a need to halt the flow of the program so that several other executions can take place or simply due to the utility required. sleep() can come handy in such a situation which provides an accurate and flexible way to halt the flow of code for any period of time. This function discusses the insight of this function." }, { "code": null, "e": 491, "s": 471, "text": "Syntax : sleep(sec)" }, { "code": null, "e": 505, "s": 491, "text": "Parameters : " }, { "code": null, "e": 575, "s": 505, "text": "sec : Number of seconds for which the code is required to be stopped." }, { "code": null, "e": 592, "s": 575, "text": "Returns : VOID. " }, { "code": null, "e": 600, "s": 592, "text": "Python3" }, { "code": "# Python code to demonstrate# working of sleep() import time # printing the start timeprint(\"The time of code execution begin is : \", end=\"\")print(time.ctime()) # using sleep() to hault the code executiontime.sleep(6) # printing the end timeprint(\"The time of code execution end is : \", end=\"\")print(time.ctime())", "e": 914, "s": 600, "text": null }, { "code": null, "e": 923, "s": 914, "text": "Output: " }, { "code": null, "e": 1047, "s": 923, "text": "The time of code execution begin is : Mon Apr 9 20:57:10 2018\nThe time of code execution end is : Mon Apr 9 20:57:16 2018" }, { "code": null, "e": 1062, "s": 1047, "text": "Application : " }, { "code": null, "e": 1403, "s": 1062, "text": "There are many applications that sleep() is used for. Be its execution of the background thread which is repeated at regular intervals, this can be implemented with the help of sleep(). Another popular application is using sleep() to print the words letter by letter for a good user interface. The latter is represented from the code below." }, { "code": null, "e": 1411, "s": 1403, "text": "Python3" }, { "code": "# Python code to demonstrate# application of sleep() import time # initializing stringstrn = \"GeeksforGeeks\" # printing geeksforgeeks after delay# of each characterfor i in range(0, len(strn)): print(strn[i], end=\"\") time.sleep(2)", "e": 1648, "s": 1411, "text": null }, { "code": null, "e": 1656, "s": 1648, "text": "Output:" }, { "code": null, "e": 1670, "s": 1656, "text": "GeeksForGeeks" }, { "code": null, "e": 1736, "s": 1670, "text": "Note : Visible effect of sleep() can be seen in the local editor." }, { "code": null, "e": 1744, "s": 1736, "text": "Python3" }, { "code": "# importing time packageimport time # creating a time delay of 5 secondstime.sleep(5) # creating and Initializing a listmyList = ['Jai', 'Shree', 'RAM', 5, 'August', 2020] # the list will be displayed after the# delay of 5 secondsprint(myList)", "e": 1988, "s": 1744, "text": null }, { "code": null, "e": 1996, "s": 1988, "text": "Output:" }, { "code": null, "e": 2053, "s": 1996, "text": "After the delay of 5 seconds, we will get the output as:" }, { "code": null, "e": 2096, "s": 2053, "text": "['Jai', 'Shree', 'RAM', 5, 'August', 2020]" }, { "code": null, "e": 2104, "s": 2096, "text": "Python3" }, { "code": "# importing time packageimport time # creating a time delay of 4 secondstime.sleep(4) # creating and Initializing a tuplemytuple = ('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne') # the tuple will be displayed after the delay of 4 secondsprint(mytuple)", "e": 2477, "s": 2104, "text": null }, { "code": null, "e": 2485, "s": 2477, "text": "Output:" }, { "code": null, "e": 2542, "s": 2485, "text": "After the delay of 4 seconds, we will get the output as:" }, { "code": null, "e": 2691, "s": 2542, "text": "('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid',\n'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne')" }, { "code": null, "e": 2699, "s": 2691, "text": "Python3" }, { "code": "# importing time packageimport time # creating and Initializing a listLanguages = ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] # creating a time delay of 5 secondstime.sleep(5) # the list will be displayed after the delay of 5 secondsprint(Languages) for lan in Languages: # creating a time delay of 13 seconds time.sleep(13) # After every 13 seconds an item of list will be displayed print(lan)", "e": 3133, "s": 2699, "text": null }, { "code": null, "e": 3141, "s": 3133, "text": "Output:" }, { "code": null, "e": 3202, "s": 3141, "text": "After the delay of 5 seconds, the list will be displayed as:" }, { "code": null, "e": 3263, "s": 3202, "text": "['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin']" }, { "code": null, "e": 3336, "s": 3263, "text": "Then after every 13 seconds, the items of the list will be displayed as:" }, { "code": null, "e": 3375, "s": 3336, "text": "Java\nC++\nPython\nJavascript\nC#\nC\nKotlin" }, { "code": null, "e": 3383, "s": 3375, "text": "Python3" }, { "code": "# importing time packageimport time # creating and Initializing a listcricketers = ['Anil Kumble', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne'] # time delay of 7 seconds is created# after every 7 seconds item of list gets displayedcricketers = [(time.sleep(7), print(cric)) for cric in cricketers]", "e": 3796, "s": 3383, "text": null }, { "code": null, "e": 3804, "s": 3796, "text": "Output:" }, { "code": null, "e": 3872, "s": 3804, "text": "After every 7 seconds, the items of the list will be displayed as:" }, { "code": null, "e": 3997, "s": 3872, "text": "Anil Kumble\nSachin Tendulkar\nSunil Gavaskar\nRahul Dravid\nMahendra Singh Dhoni\nDennis Lillee\nMuttiah Muralitharan\nShane Warne" }, { "code": null, "e": 4005, "s": 3997, "text": "Python3" }, { "code": "# importing time packageimport time # creating and Initializing a listLanguages = ['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin'] # creating a time delay of 3 minutestime.sleep(3 * 60) # the list will be displayed after the delay# of 3 minutesprint(Languages)", "e": 4290, "s": 4005, "text": null }, { "code": null, "e": 4298, "s": 4290, "text": "Output:" }, { "code": null, "e": 4359, "s": 4298, "text": "After the delay of 3 minutes, the list will be displayed as:" }, { "code": null, "e": 4420, "s": 4359, "text": "['Java', 'C++', 'Python', 'Javascript', 'C#', 'C', 'Kotlin']" }, { "code": null, "e": 4435, "s": 4420, "text": "vanshgaur14866" }, { "code": null, "e": 4451, "s": 4435, "text": "rajeev0719singh" }, { "code": null, "e": 4464, "s": 4451, "text": "kumar_satyam" }, { "code": null, "e": 4490, "s": 4464, "text": "Python-Built-in-functions" }, { "code": null, "e": 4497, "s": 4490, "text": "Python" }, { "code": null, "e": 4595, "s": 4497, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4613, "s": 4595, "text": "Python Dictionary" }, { "code": null, "e": 4655, "s": 4613, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4677, "s": 4655, "text": "Enumerate() in Python" }, { "code": null, "e": 4712, "s": 4677, "text": "Read a file line by line in Python" }, { "code": null, "e": 4744, "s": 4712, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4773, "s": 4744, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4800, "s": 4773, "text": "Python Classes and Objects" }, { "code": null, "e": 4830, "s": 4800, "text": "Iterate over a list in Python" }, { "code": null, "e": 4851, "s": 4830, "text": "Python OOPs Concepts" } ]
Java - String hashCode() Method
This method returns a hash code for this string. The hash code for a String object is computed as − s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.) Here is the syntax of this method − public int hashCode() Here is the detail of parameters − This is a default method and this will not accept any parameters. This method returns a hash code value for this object. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.println("Hashcode for Str :" + Str.hashCode() ); } } This will produce the following result − Hashcode for Str :1186874997
[ { "code": null, "e": 2611, "s": 2511, "text": "This method returns a hash code for this string. The hash code for a String object is computed as −" }, { "code": null, "e": 2663, "s": 2611, "text": "s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]\n" }, { "code": null, "e": 2841, "s": 2663, "text": "Using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)" }, { "code": null, "e": 2877, "s": 2841, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2900, "s": 2877, "text": "public int hashCode()\n" }, { "code": null, "e": 2935, "s": 2900, "text": "Here is the detail of parameters −" }, { "code": null, "e": 3001, "s": 2935, "text": "This is a default method and this will not accept any parameters." }, { "code": null, "e": 3056, "s": 3001, "text": "This method returns a hash code value for this object." }, { "code": null, "e": 3276, "s": 3056, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n System.out.println(\"Hashcode for Str :\" + Str.hashCode() );\n }\n}" }, { "code": null, "e": 3317, "s": 3276, "text": "This will produce the following result −" } ]
wxPython - StaticText Class
Another important element in a GUI interface is a label, a read-only text of one or more lines. It is usually placed on the frame either as an identifier of another widget or as an informative string. In wxPython, wx.StaticText class object presents a control holding such read-only text. It can be termed as a passive control since it doesn’t produce any event. Wx.StaticText class constructor requires the following usual parameters − Wx.StaticText(parent, id, label, position, size, style) Predefined style enumerators are − The following methods of wx.StaticText class are also useful − SetLabel() Sets label of object programmatically GetLabel() Returns object’s label SetForeGroundColour() Sets color of label’s text SetBackGroundColour() Sets label’s background Wrap() Wraps label’s text if it can not be accommodated within size. The above features of StaticText class are demonstrated in the following example. Three StaticText objects are placed in a vertical box sizer. The first object has multi-line text which is center aligned. The second label’s text is set to wrap around beyond 200 pixels. The third label shows ellipsis (...) in the middle of the text. In order to set the label’s font, a font object is first created. Wx.Font(pointsize, fontfamily, fontstyle, fontweight) Fontfamily parameter takes the following values − wx.FONTFAMILY_DEFAULT Chooses a default font wx.FONTFAMILY_DECORATIVE Chooses a decorative font wx.FONTFAMILY_ROMAN Chooses a formal, serif font wx.FONTFAMILY_SCRIPT Chooses a handwriting font wx.FONTFAMILY_SWISS Chooses a sans-serif font wx.FONTFAMILY_MODERN Chooses a fixed pitch font wx.FONTFAMILY_TELETYPE Chooses a teletype (monospaced) font FontStyle parameter enumerations are − Wx.FONTSTYLE_NORMAL The font is drawn without slant wx.FONTSTYLE_ITALIC The font is slanted in italic style wx.FONTSTYLE_SLANT The font is slanted, but in roman style FontWeight parameters are − Wx.FONTWEIGHT_NORMAL Normal font wx.FONTWEIGHT_LIGHT Light font wx.FONTWEIGHT_BOLD Bold font The complete code listing is − import wx class Mywin(wx.Frame): def __init__(self, parent, title): super(Mywin, self).__init__(parent, title = title,size = (600,200)) panel = wx.Panel(self) box = wx.BoxSizer(wx.VERTICAL) lbl = wx.StaticText(panel,-1,style = wx.ALIGN_CENTER) txt1 = "Python GUI development" txt2 = "using wxPython" txt3 = " Python port of wxWidget " txt = txt1+"\n"+txt2+"\n"+txt3 font = wx.Font(18, wx.ROMAN, wx.ITALIC, wx.NORMAL) lbl.SetFont(font) lbl.SetLabel(txt) box.Add(lbl,0,wx.ALIGN_CENTER) lblwrap = wx.StaticText(panel,-1,style = wx.ALIGN_RIGHT) txt = txt1+txt2+txt3 lblwrap.SetLabel(txt) lblwrap.Wrap(200) box.Add(lblwrap,0,wx.ALIGN_LEFT) lbl1 = wx.StaticText(panel,-1, style = wx.ALIGN_LEFT | wx.ST_ELLIPSIZE_MIDDLE) lbl1.SetLabel(txt) lbl1.SetForegroundColour((255,0,0)) lbl1.SetBackgroundColour((0,0,0)) font = self.GetFont() font.SetPointSize(20) lbl1.SetFont(font) box.Add(lbl1,0,wx.ALIGN_LEFT) panel.SetSizer(box) self.Centre() self.Show() app = wx.App() Mywin(None, 'StaticText demo') app.MainLoop() The above code produces the following output −
[ { "code": null, "e": 2217, "s": 2016, "text": "Another important element in a GUI interface is a label, a read-only text of one or more lines. It is usually placed on the frame either as an identifier of another widget or as an informative string." }, { "code": null, "e": 2453, "s": 2217, "text": "In wxPython, wx.StaticText class object presents a control holding such read-only text. It can be termed as a passive control since it doesn’t produce any event. Wx.StaticText class constructor requires the following usual parameters −" }, { "code": null, "e": 2510, "s": 2453, "text": "Wx.StaticText(parent, id, label, position, size, style)\n" }, { "code": null, "e": 2545, "s": 2510, "text": "Predefined style enumerators are −" }, { "code": null, "e": 2608, "s": 2545, "text": "The following methods of wx.StaticText class are also useful −" }, { "code": null, "e": 2619, "s": 2608, "text": "SetLabel()" }, { "code": null, "e": 2657, "s": 2619, "text": "Sets label of object programmatically" }, { "code": null, "e": 2668, "s": 2657, "text": "GetLabel()" }, { "code": null, "e": 2691, "s": 2668, "text": "Returns object’s label" }, { "code": null, "e": 2713, "s": 2691, "text": "SetForeGroundColour()" }, { "code": null, "e": 2740, "s": 2713, "text": "Sets color of label’s text" }, { "code": null, "e": 2762, "s": 2740, "text": "SetBackGroundColour()" }, { "code": null, "e": 2786, "s": 2762, "text": "Sets label’s background" }, { "code": null, "e": 2793, "s": 2786, "text": "Wrap()" }, { "code": null, "e": 2855, "s": 2793, "text": "Wraps label’s text if it can not be accommodated within size." }, { "code": null, "e": 2998, "s": 2855, "text": "The above features of StaticText class are demonstrated in the following example. Three StaticText objects are placed in a vertical box sizer." }, { "code": null, "e": 3189, "s": 2998, "text": "The first object has multi-line text which is center aligned. The second label’s text is set to wrap around beyond 200 pixels. The third label shows ellipsis (...) in the middle of the text." }, { "code": null, "e": 3255, "s": 3189, "text": "In order to set the label’s font, a font object is first created." }, { "code": null, "e": 3310, "s": 3255, "text": "Wx.Font(pointsize, fontfamily, fontstyle, fontweight)\n" }, { "code": null, "e": 3360, "s": 3310, "text": "Fontfamily parameter takes the following values −" }, { "code": null, "e": 3382, "s": 3360, "text": "wx.FONTFAMILY_DEFAULT" }, { "code": null, "e": 3405, "s": 3382, "text": "Chooses a default font" }, { "code": null, "e": 3430, "s": 3405, "text": "wx.FONTFAMILY_DECORATIVE" }, { "code": null, "e": 3456, "s": 3430, "text": "Chooses a decorative font" }, { "code": null, "e": 3476, "s": 3456, "text": "wx.FONTFAMILY_ROMAN" }, { "code": null, "e": 3505, "s": 3476, "text": "Chooses a formal, serif font" }, { "code": null, "e": 3526, "s": 3505, "text": "wx.FONTFAMILY_SCRIPT" }, { "code": null, "e": 3553, "s": 3526, "text": "Chooses a handwriting font" }, { "code": null, "e": 3573, "s": 3553, "text": "wx.FONTFAMILY_SWISS" }, { "code": null, "e": 3599, "s": 3573, "text": "Chooses a sans-serif font" }, { "code": null, "e": 3620, "s": 3599, "text": "wx.FONTFAMILY_MODERN" }, { "code": null, "e": 3647, "s": 3620, "text": "Chooses a fixed pitch font" }, { "code": null, "e": 3670, "s": 3647, "text": "wx.FONTFAMILY_TELETYPE" }, { "code": null, "e": 3707, "s": 3670, "text": "Chooses a teletype (monospaced) font" }, { "code": null, "e": 3746, "s": 3707, "text": "FontStyle parameter enumerations are −" }, { "code": null, "e": 3766, "s": 3746, "text": "Wx.FONTSTYLE_NORMAL" }, { "code": null, "e": 3798, "s": 3766, "text": "The font is drawn without slant" }, { "code": null, "e": 3818, "s": 3798, "text": "wx.FONTSTYLE_ITALIC" }, { "code": null, "e": 3854, "s": 3818, "text": "The font is slanted in italic style" }, { "code": null, "e": 3873, "s": 3854, "text": "wx.FONTSTYLE_SLANT" }, { "code": null, "e": 3913, "s": 3873, "text": "The font is slanted, but in roman style" }, { "code": null, "e": 3941, "s": 3913, "text": "FontWeight parameters are −" }, { "code": null, "e": 3962, "s": 3941, "text": "Wx.FONTWEIGHT_NORMAL" }, { "code": null, "e": 3974, "s": 3962, "text": "Normal font" }, { "code": null, "e": 3994, "s": 3974, "text": "wx.FONTWEIGHT_LIGHT" }, { "code": null, "e": 4005, "s": 3994, "text": "Light font" }, { "code": null, "e": 4024, "s": 4005, "text": "wx.FONTWEIGHT_BOLD" }, { "code": null, "e": 4034, "s": 4024, "text": "Bold font" }, { "code": null, "e": 4065, "s": 4034, "text": "The complete code listing is −" }, { "code": null, "e": 5298, "s": 4065, "text": "import wx \n \nclass Mywin(wx.Frame): \n def __init__(self, parent, title): \n super(Mywin, self).__init__(parent, title = title,size = (600,200))\n panel = wx.Panel(self) \n box = wx.BoxSizer(wx.VERTICAL) \n lbl = wx.StaticText(panel,-1,style = wx.ALIGN_CENTER) \n\t\t\n txt1 = \"Python GUI development\" \n txt2 = \"using wxPython\" \n txt3 = \" Python port of wxWidget \" \n txt = txt1+\"\\n\"+txt2+\"\\n\"+txt3 \n\t\t\n font = wx.Font(18, wx.ROMAN, wx.ITALIC, wx.NORMAL) \n lbl.SetFont(font) \n lbl.SetLabel(txt) \n\t\t\n box.Add(lbl,0,wx.ALIGN_CENTER) \n lblwrap = wx.StaticText(panel,-1,style = wx.ALIGN_RIGHT) \n txt = txt1+txt2+txt3 \n\t\t\n lblwrap.SetLabel(txt) \n lblwrap.Wrap(200) \n box.Add(lblwrap,0,wx.ALIGN_LEFT) \n\t\t\n lbl1 = wx.StaticText(panel,-1, style = wx.ALIGN_LEFT | wx.ST_ELLIPSIZE_MIDDLE) \n lbl1.SetLabel(txt) \n lbl1.SetForegroundColour((255,0,0)) \n lbl1.SetBackgroundColour((0,0,0)) \n\t\t\n font = self.GetFont() \n font.SetPointSize(20) \n lbl1.SetFont(font) \n\t\t\n box.Add(lbl1,0,wx.ALIGN_LEFT) \n panel.SetSizer(box) \n self.Centre() \n self.Show() \n\t\t\napp = wx.App() \nMywin(None, 'StaticText demo') \napp.MainLoop()" } ]
Microsoft Interview Experience | Set 55 (For Software Engineer 2)
12 Feb, 2018 Skype round 1: (10 min)Print a tree in zigzag order. For Example for the given input tree:- 1 2 3 4 5 6 7 The output would be:- 1 3 2 4 5 6 7 Code for the logic in any language that you are comfortable in. Skype Round 2: (10 min)Find if two given strings are anagrams of each other or not.Anagrams example: LISTEN and SILENT.Code for the same. Test cases for the code. (Positive and negative) They called me to Hyderabad for an F2F immediately after Skpe rounds, (I managed to postpone it to the next week). Face2Face Round 1: (45 min) Question 1:Given a character array which each position is filled with either a single digit numbers or a comma,Array of 22 characters:-Write a code to reply true if we find a set of three set of numbers separated by a comma such thatX , Y, Z and Z = X + YIn the array above 77+22 = 99 so return true.Code for the same with negative test cases. Question 2:If in a given Doubly Circular Linked List a couple of next pointers are corrupted, give the logic to rectify them all. Face2Face Round 2: (1 hour)Given a number in an int variable, write a code print its value in words, covering all possible corner cases.Ex → 34567 = thirty four thousand five hundred and sixty seven.Negative test cases for the same. Face2Face Round 3: (1 hour 15 min)Question 1:Given a scheduler arrangement with some jobs having unique job ids and every job id has a number of tasks with unique task ids for that job.Example:- Job id : 500 Task id : 700 Task id : 300 Task id : 350 Job id : 600 Task id : 400 Task id : 350 Task id : 600 Job id : 1000 Task id : 800 Task id : 100 Job id : 200 Task id : 650 Write a Code for listing the job ids + task id combination in round robin fashion.Example:- Job id : 500 Task id : 700 Job id : 600 Task id : 400 Job id : 1000 Task id : 800 Job id : 200 Task id : 650 Job id : 500 Task id : 300 Job id : 600 Task id : 350 Job id : 1000 Task id : 100 Job id : 500 Task id : 350 Job id : 600 Task id : 600 Choose any data structure of the input (array of structures or linked lists or queue).Design Test cases for the same.Question 2:Given a BST, create a Doubly Linked List from the same in place.Tree node -> left pointer = DLL node -> previous pointerTree node -> right pointer = DLL node -> next pointer Face2Face Round 4: (with the Director) (1 hour approx)He asked typical HR questions likeWhy Microsoft?Where do you yourself 10n years from now? Blah blah. Question 1:Given a mess of 3 balls (colored red blue and white) write an algorithm + program with the most efficient way to sort them color wise. (Dutch National Flag Problem) Question 2:Given a string print the string with alternate occurrences of any character dropped. Example:- input string → It is a long day Dear. Output string → tisalongdyDea. Modification:- Consider alphabets with both cases as same occurrence. Output string → Itsalongdy ea. Position was software Engineer 2. MSFT does not have SDE and SDET anymore, All roles shall be SE from now on. Thank you geeks for geeks. This site is a Marvel for job aspirants. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Microsoft Interview Experiences Strings Microsoft Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Feb, 2018" }, { "code": null, "e": 144, "s": 52, "text": "Skype round 1: (10 min)Print a tree in zigzag order. For Example for the given input tree:-" }, { "code": null, "e": 216, "s": 144, "text": " 1\n 2 3\n 4 5 6 7 " }, { "code": null, "e": 238, "s": 216, "text": "The output would be:-" }, { "code": null, "e": 253, "s": 238, "text": "1\n3 2\n4 5 6 7 " }, { "code": null, "e": 317, "s": 253, "text": "Code for the logic in any language that you are comfortable in." }, { "code": null, "e": 504, "s": 317, "text": "Skype Round 2: (10 min)Find if two given strings are anagrams of each other or not.Anagrams example: LISTEN and SILENT.Code for the same. Test cases for the code. (Positive and negative)" }, { "code": null, "e": 619, "s": 504, "text": "They called me to Hyderabad for an F2F immediately after Skpe rounds, (I managed to postpone it to the next week)." }, { "code": null, "e": 647, "s": 619, "text": "Face2Face Round 1: (45 min)" }, { "code": null, "e": 991, "s": 647, "text": "Question 1:Given a character array which each position is filled with either a single digit numbers or a comma,Array of 22 characters:-Write a code to reply true if we find a set of three set of numbers separated by a comma such thatX , Y, Z and Z = X + YIn the array above 77+22 = 99 so return true.Code for the same with negative test cases." }, { "code": null, "e": 1121, "s": 991, "text": "Question 2:If in a given Doubly Circular Linked List a couple of next pointers are corrupted, give the logic to rectify them all." }, { "code": null, "e": 1354, "s": 1121, "text": "Face2Face Round 2: (1 hour)Given a number in an int variable, write a code print its value in words, covering all possible corner cases.Ex → 34567 = thirty four thousand five hundred and sixty seven.Negative test cases for the same." }, { "code": null, "e": 1549, "s": 1354, "text": "Face2Face Round 3: (1 hour 15 min)Question 1:Given a scheduler arrangement with some jobs having unique job ids and every job id has a number of tasks with unique task ids for that job.Example:-" }, { "code": null, "e": 1774, "s": 1549, "text": " Job id : 500 Task id : 700\n Task id : 300\n Task id : 350\n Job id : 600 Task id : 400\n Task id : 350\n Task id : 600\n Job id : 1000 Task id : 800\n Task id : 100\n Job id : 200 Task id : 650" }, { "code": null, "e": 1866, "s": 1774, "text": "Write a Code for listing the job ids + task id combination in round robin fashion.Example:-" }, { "code": null, "e": 2138, "s": 1866, "text": "Job id : 500 Task id : 700\nJob id : 600 Task id : 400\nJob id : 1000 Task id : 800\nJob id : 200 Task id : 650\nJob id : 500 Task id : 300\nJob id : 600 Task id : 350\nJob id : 1000 Task id : 100\nJob id : 500 Task id : 350\nJob id : 600 Task id : 600" }, { "code": null, "e": 2440, "s": 2138, "text": "Choose any data structure of the input (array of structures or linked lists or queue).Design Test cases for the same.Question 2:Given a BST, create a Doubly Linked List from the same in place.Tree node -> left pointer = DLL node -> previous pointerTree node -> right pointer = DLL node -> next pointer" }, { "code": null, "e": 2595, "s": 2440, "text": "Face2Face Round 4: (with the Director) (1 hour approx)He asked typical HR questions likeWhy Microsoft?Where do you yourself 10n years from now? Blah blah." }, { "code": null, "e": 2771, "s": 2595, "text": "Question 1:Given a mess of 3 balls (colored red blue and white) write an algorithm + program with the most efficient way to sort them color wise. (Dutch National Flag Problem)" }, { "code": null, "e": 2867, "s": 2771, "text": "Question 2:Given a string print the string with alternate occurrences of any character dropped." }, { "code": null, "e": 2958, "s": 2867, "text": "Example:- input string → It is a long day Dear.\n Output string → tisalongdyDea. " }, { "code": null, "e": 3028, "s": 2958, "text": "Modification:- Consider alphabets with both cases as same occurrence." }, { "code": null, "e": 3066, "s": 3028, "text": " Output string → Itsalongdy ea." }, { "code": null, "e": 3176, "s": 3066, "text": "Position was software Engineer 2. MSFT does not have SDE and SDET anymore, All roles shall be SE from now on." }, { "code": null, "e": 3244, "s": 3176, "text": "Thank you geeks for geeks. This site is a Marvel for job aspirants." }, { "code": null, "e": 3465, "s": 3244, "text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3475, "s": 3465, "text": "Microsoft" }, { "code": null, "e": 3497, "s": 3475, "text": "Interview Experiences" }, { "code": null, "e": 3505, "s": 3497, "text": "Strings" }, { "code": null, "e": 3515, "s": 3505, "text": "Microsoft" }, { "code": null, "e": 3523, "s": 3515, "text": "Strings" } ]
Matplotlib.pyplot.hsv() in Python
19 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 hsv() function in pyplot module of matplotlib library is used to set the colormap to “hsv”.Syntax: matplotlib.pyplot.hsv() Below examples illustrate the matplotlib.pyplot.hsv() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat') plt.hsv() plt.title('matplotlib.pyplot.hsv() function Example', fontweight ="bold") plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent) plt.hsv() plt.title('matplotlib.pyplot.hsv() function\Example', fontweight ="bold") plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 223, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 326, "s": 223, "text": "The hsv() function in pyplot module of matplotlib library is used to set the colormap to “hsv”.Syntax:" }, { "code": null, "e": 351, "s": 326, "text": "matplotlib.pyplot.hsv()\n" }, { "code": null, "e": 436, "s": 351, "text": "Below examples illustrate the matplotlib.pyplot.hsv() function in matplotlib.pyplot:" }, { "code": null, "e": 448, "s": 436, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad) angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten() triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1), y[triang.triangles].mean(axis = 1)) < radm) tpc = plt.tripcolor(triang, z, shading ='flat') plt.hsv() plt.title('matplotlib.pyplot.hsv() function Example', fontweight =\"bold\") plt.show()", "e": 1265, "s": 448, "text": null }, { "code": null, "e": 1273, "s": 1265, "text": "Output:" }, { "code": null, "e": 1285, "s": 1273, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear', extent = extent) plt.hsv() plt.title('matplotlib.pyplot.hsv() function\\Example', fontweight =\"bold\") plt.show()", "e": 2038, "s": 1285, "text": null }, { "code": null, "e": 2046, "s": 2038, "text": "Output:" }, { "code": null, "e": 2064, "s": 2046, "text": "Python-matplotlib" }, { "code": null, "e": 2071, "s": 2064, "text": "Python" }, { "code": null, "e": 2169, "s": 2071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2187, "s": 2169, "text": "Python Dictionary" }, { "code": null, "e": 2229, "s": 2187, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2251, "s": 2229, "text": "Enumerate() in Python" }, { "code": null, "e": 2286, "s": 2251, "text": "Read a file line by line in Python" }, { "code": null, "e": 2312, "s": 2286, "text": "Python String | replace()" }, { "code": null, "e": 2344, "s": 2312, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2371, "s": 2344, "text": "Python Classes and Objects" }, { "code": null, "e": 2401, "s": 2371, "text": "Iterate over a list in Python" }, { "code": null, "e": 2422, "s": 2401, "text": "Python OOPs Concepts" } ]
How to check whether the day is a weekday or not using Pandas in Python?
29 Aug, 2020 Python is a very popular language because it is suitable for almost any type of data science task. And Pandas is one of the popular python-based data analysis toolkits and also provides pandas.bdate_range() function to return a fixed frequency DatetimeIndex. This function Returns a fixed frequency DatetimeIndex, with the business day(Mon to Fri) as the default frequency. Syntax: pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs) Parameters : start : string or datetime-like, default None. end : string or datetime-like, default None. periods : integer, default None. freq : string or DateOffset, default ‘B’ (business daily). tz : string or None. normalize : bool, default False name : str, default None weekmask : str or None, default None holidays : list-like or None, default None Approach : Import the Pandas module Create a Parameter function that returns a boolean value Check the given date is returning boolean with pd.bdate_range() inside function Check if boolean is False then the date belongs to a weekday if boolean is true then is not weekday Below is the implementation. Python3 # importing Pandas moduleimport pandas as pd # Creating a Functiondef check_weekday(date): # computing the parameter date # with len function res=len(pd.bdate_range(date,date)) if res == 0 : print("This is weekend") else: print("This is your working day") # user inputdate = "2020-08-17"check_weekday(date) date = "2020-08-16"check_weekday(date) Output : This is your working day This is weekend Python pandas-datetime Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 402, "s": 28, "text": "Python is a very popular language because it is suitable for almost any type of data science task. And Pandas is one of the popular python-based data analysis toolkits and also provides pandas.bdate_range() function to return a fixed frequency DatetimeIndex. This function Returns a fixed frequency DatetimeIndex, with the business day(Mon to Fri) as the default frequency." }, { "code": null, "e": 564, "s": 402, "text": "Syntax: pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs)" }, { "code": null, "e": 577, "s": 564, "text": "Parameters :" }, { "code": null, "e": 624, "s": 577, "text": "start : string or datetime-like, default None." }, { "code": null, "e": 669, "s": 624, "text": "end : string or datetime-like, default None." }, { "code": null, "e": 702, "s": 669, "text": "periods : integer, default None." }, { "code": null, "e": 762, "s": 702, "text": "freq : string or DateOffset, default ‘B’ (business daily)." }, { "code": null, "e": 783, "s": 762, "text": "tz : string or None." }, { "code": null, "e": 815, "s": 783, "text": "normalize : bool, default False" }, { "code": null, "e": 840, "s": 815, "text": "name : str, default None" }, { "code": null, "e": 877, "s": 840, "text": "weekmask : str or None, default None" }, { "code": null, "e": 920, "s": 877, "text": "holidays : list-like or None, default None" }, { "code": null, "e": 932, "s": 920, "text": "Approach : " }, { "code": null, "e": 957, "s": 932, "text": "Import the Pandas module" }, { "code": null, "e": 1014, "s": 957, "text": "Create a Parameter function that returns a boolean value" }, { "code": null, "e": 1094, "s": 1014, "text": "Check the given date is returning boolean with pd.bdate_range() inside function" }, { "code": null, "e": 1194, "s": 1094, "text": "Check if boolean is False then the date belongs to a weekday if boolean is true then is not weekday" }, { "code": null, "e": 1223, "s": 1194, "text": "Below is the implementation." }, { "code": null, "e": 1231, "s": 1223, "text": "Python3" }, { "code": "# importing Pandas moduleimport pandas as pd # Creating a Functiondef check_weekday(date): # computing the parameter date # with len function res=len(pd.bdate_range(date,date)) if res == 0 : print(\"This is weekend\") else: print(\"This is your working day\") # user inputdate = \"2020-08-17\"check_weekday(date) date = \"2020-08-16\"check_weekday(date)", "e": 1622, "s": 1231, "text": null }, { "code": null, "e": 1631, "s": 1622, "text": "Output :" }, { "code": null, "e": 1672, "s": 1631, "text": "This is your working day\nThis is weekend" }, { "code": null, "e": 1695, "s": 1672, "text": "Python pandas-datetime" }, { "code": null, "e": 1709, "s": 1695, "text": "Python-pandas" }, { "code": null, "e": 1716, "s": 1709, "text": "Python" }, { "code": null, "e": 1814, "s": 1716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1846, "s": 1814, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1873, "s": 1846, "text": "Python Classes and Objects" }, { "code": null, "e": 1894, "s": 1873, "text": "Python OOPs Concepts" }, { "code": null, "e": 1917, "s": 1894, "text": "Introduction To PYTHON" }, { "code": null, "e": 1973, "s": 1917, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2004, "s": 1973, "text": "Python | os.path.join() method" }, { "code": null, "e": 2046, "s": 2004, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2088, "s": 2046, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2127, "s": 2088, "text": "Python | Get unique values from a list" } ]
How to Train a Classification Model with TensorFlow in 10 Minutes | by Dario Radečić | Towards Data Science
Deep learning is everywhere. From sales forecasting to segmenting skin diseases on image data — there’s nothing deep learning algorithms can’t do, given quality data. If deep learning and TensorFlow are new to you, you’re in the right place. This article will show you the entire process of building a classification model on tabular data. You’ll go from data gathering and preparation to training and evaluating neural network models in just one sitting. Let’s start. You’ll need TensorFlow 2+, Numpy, Pandas, Matplotlib, and Scikit-Learn installed to follow along. Don’t feel like reading? Watch my video instead: Jump to a section: · DATASET USED· DATA PREPARATION AND EXPLORATION ∘ Basic preparation ∘ Converting to a binary classification problem ∘ Train/test split ∘ Data scaling· TRAINING A CLASSIFICATION MODEL WITH TENSORFLOW ∘ Defining a neural network architecture ∘ Visualizing model performance ∘ Making predictions ∘ Model evaluation on test data You can download the source code on GitHub. Let’s avoid unnecessary headaches and stick to simple datasets. The wine quality dataset from Kaggle will be good enough for today: The dataset is mostly clean, but isn’t designed for binary classification by default (good/bad wine). Instead, the wines are rated on a scale. We’ll address that later. Download it and extract the CSV somewhere on your machine, and open up JupyterLab. You’re free to use any other IDE, but all the screenshots below will be from Jupyter. The first step is to import Numpy and Pandas, and then to import the dataset. The following snippet does that and also prints a random sample of five rows: import numpy as npimport pandas as pd df = pd.read_csv('data/winequalityN.csv')df.sample(5) Here’s how the dataset looks like: It’s mostly clean, but there’s still some work to do. The dataset has some missing values, but the number isn’t significant, as there are 6497 rows in total: Run the following code to get rid of them: df = df.dropna() The only non-numerical feature is type. It can be either white (4870 rows) or red (1593) rows. The following snippet converts this feature to a binary one called is_white_wine, where the value is 1 if type is white and 0 otherwise: df['is_white_wine'] = [ 1 if typ == 'white' else 0 for typ in df['type']]df.drop('type', axis=1, inplace=True) All features are numeric now, and there’s only one thing left to do — make the target variable (quality) binary. The wines are graded from 3 to 9, assuming higher is better. Here are the value counts: To keep things extra simple, we’ll convert it into a binary variable. We’ll classify any wine with a grade of 6 and above as good (1), and all other wines as bad (0). Here’s the code: df['is_good_wine'] = [ 1 if quality >= 6 else 0 for quality in df['quality']]df.drop('quality', axis=1, inplace=True)df.head() And here’s how the dataset looks like now: You now have 4091 good wines and 2372 bad wines. The classes are imbalanced, but we can work with that. Let’s split the dataset into training and testing sets next. We’ll stick to a standard 80:20 split. Here’s the code: from sklearn.model_selection import train_test_splitX = df.drop('is_good_wine', axis=1)y = df['is_good_wine']X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) You now have 5170 rows in the training set and 1293 rows in the testing set. It should be enough to train a somewhat decent neural network model. Let’s scale the data before we start the training. Features like sulphates and citric acid have values close to zero, while total sulfur dioxide is in hundreds. You’ll confuse the neural network if you leave them as such, as it will think a feature on a higher scale is more important. That’s where scaling comes into play. We’ll use StandardScaler from Scikit-Learn to fit and transform the training data and to apply the transformation to the testing data: from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test) Here’s how the first three scaled rows look like: The value range is much tighter now, so a neural network should do a better job. Let’s train the model and see if we can get something decent. You’ll need to keep a couple of things in mind when training a binary classification model: Output layer structure — You’ll want to have one neuron activated with a sigmoid function. This will output a probability you can then assign to either a good wine (P > 0.5) or a bad wine (P <= 0.5). Loss function — Binary cross-entropy is the one to go with. Don’t mistake it for categorical cross-entropy. Class balance — Are the classes in the target variable balanced? In other words, do you have roughly the same number of good and bad wines? If not, accuracy might not be the best evaluation metric. We’ll also use precision and recall. Let’s define a neural network architecture next, having the above three points in mind. I’ve chosen this architecture entirely at random, so feel free to adjust it. The model goes from 12 input features to the first hidden layer of 128 neurons, followed by two additional hidden layers of 256 neurons. There’s a 1-neuron output layer at the end. Hidden layers use ReLU as the activation function, and the output layer uses Sigmoid. Here’s the code: import tensorflow as tftf.random.set_seed(42)model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(lr=0.03), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy'), tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall') ])history = model.fit(X_train_scaled, y_train, epochs=100) This will initiate the training process. A single epoch takes around 1 second on my machine (M1 MBP): We kept track of loss, accuracy, precision, and recall during training, and saved them to history. We can now visualize these metrics to get a sense of how the model is doing. Let’s start by importing Matplotlib and tweaking the default styles a bit. The following code snippet will make the plot larger and remove the top and right spines: import matplotlib.pyplot as pltfrom matplotlib import rcParamsrcParams['figure.figsize'] = (18, 8)rcParams['axes.spines.top'] = FalsercParams['axes.spines.right'] = False The plot will have multiple lines — for loss, accuracy, precision, and recall. They all share the X-axis, which represents the epoch number (np.arange(1, 101)). We should see loss decreasing, and every other metric increasing: plt.plot( np.arange(1, 101), history.history['loss'], label='Loss')plt.plot( np.arange(1, 101), history.history['accuracy'], label='Accuracy')plt.plot( np.arange(1, 101), history.history['precision'], label='Precision')plt.plot( np.arange(1, 101), history.history['recall'], label='Recall')plt.title('Evaluation metrics', size=20)plt.xlabel('Epoch', size=14)plt.legend(); Let’s take a look: Accuracy, precision, and recall increase slightly as we train the model, while loss decreases. All have occasional spikes, which would hopefully wear off if you were to train the model longer. According to the chart, you could train the model for more epochs, as there’s no sign of plateau. But are we overfitting? Let’s answer that next. You can now use the predict() function to get prediction probabilities on the scaled test data: predictions = model.predict(X_test_scaled) Here’s how they look like: You’ll have to convert them to classes before evaluation. The logic is simple — if the probability is greater than 0.5 we assign 1 (good wine), and 0 (bad wine) otherwise: prediction_classes = [ 1 if prob > 0.5 else 0 for prob in np.ravel(predictions)] Here’s how the first 20 look like: That’s all we need — let’s evaluate the model next. Let’s start with the confusion matrix: from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test, prediction_classes)) There are more false negatives (214) than false positives (99), so the recall value on the test set will be lower than precision. The following snippet prints accuracy, precision, and recall on the test set: from sklearn.metrics import accuracy_score, precision_score, recall_scoreprint(f'Accuracy: {accuracy_score(y_test, prediction_classes):.2f}')print(f'Precision: {precision_score(y_test, prediction_classes):.2f}')print(f'Recall: {recall_score(y_test, prediction_classes):.2f}') All values are somewhat lower when compared to train set evaluation: Accuracy: 0.82 Precision: 0.88 Recall: 0.83 The model is overfitting slightly, but it’s still decent work for a couple of minutes. We’ll go over the optimization in the following article. And that does it — you now know how to train a simple neural network for binary classification. The dataset we used today was relatively clean, and required almost zero preparation work. Don’t get used to that feeling. There’s a lot we can improve. For example, you could add additional layers to the network, increase the number of neurons, choose different activation functions, select a different optimizer, add dropout layers, and much more. The possibilities are almost endless, so it all boils down to experimentation. The following article will cover optimization — you’ll learn how to find the optimal learning rate and neural network architecture automatically, so stay tuned if you want to learn more. Thanks for reading. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Sign up for my newsletter Subscribe on YouTube Connect on LinkedIn
[ { "code": null, "e": 339, "s": 172, "text": "Deep learning is everywhere. From sales forecasting to segmenting skin diseases on image data — there’s nothing deep learning algorithms can’t do, given quality data." }, { "code": null, "e": 641, "s": 339, "text": "If deep learning and TensorFlow are new to you, you’re in the right place. This article will show you the entire process of building a classification model on tabular data. You’ll go from data gathering and preparation to training and evaluating neural network models in just one sitting. Let’s start." }, { "code": null, "e": 739, "s": 641, "text": "You’ll need TensorFlow 2+, Numpy, Pandas, Matplotlib, and Scikit-Learn installed to follow along." }, { "code": null, "e": 788, "s": 739, "text": "Don’t feel like reading? Watch my video instead:" }, { "code": null, "e": 807, "s": 788, "text": "Jump to a section:" }, { "code": null, "e": 1141, "s": 807, "text": "· DATASET USED· DATA PREPARATION AND EXPLORATION ∘ Basic preparation ∘ Converting to a binary classification problem ∘ Train/test split ∘ Data scaling· TRAINING A CLASSIFICATION MODEL WITH TENSORFLOW ∘ Defining a neural network architecture ∘ Visualizing model performance ∘ Making predictions ∘ Model evaluation on test data" }, { "code": null, "e": 1185, "s": 1141, "text": "You can download the source code on GitHub." }, { "code": null, "e": 1317, "s": 1185, "text": "Let’s avoid unnecessary headaches and stick to simple datasets. The wine quality dataset from Kaggle will be good enough for today:" }, { "code": null, "e": 1486, "s": 1317, "text": "The dataset is mostly clean, but isn’t designed for binary classification by default (good/bad wine). Instead, the wines are rated on a scale. We’ll address that later." }, { "code": null, "e": 1655, "s": 1486, "text": "Download it and extract the CSV somewhere on your machine, and open up JupyterLab. You’re free to use any other IDE, but all the screenshots below will be from Jupyter." }, { "code": null, "e": 1811, "s": 1655, "text": "The first step is to import Numpy and Pandas, and then to import the dataset. The following snippet does that and also prints a random sample of five rows:" }, { "code": null, "e": 1903, "s": 1811, "text": "import numpy as npimport pandas as pd df = pd.read_csv('data/winequalityN.csv')df.sample(5)" }, { "code": null, "e": 1938, "s": 1903, "text": "Here’s how the dataset looks like:" }, { "code": null, "e": 1992, "s": 1938, "text": "It’s mostly clean, but there’s still some work to do." }, { "code": null, "e": 2096, "s": 1992, "text": "The dataset has some missing values, but the number isn’t significant, as there are 6497 rows in total:" }, { "code": null, "e": 2139, "s": 2096, "text": "Run the following code to get rid of them:" }, { "code": null, "e": 2156, "s": 2139, "text": "df = df.dropna()" }, { "code": null, "e": 2388, "s": 2156, "text": "The only non-numerical feature is type. It can be either white (4870 rows) or red (1593) rows. The following snippet converts this feature to a binary one called is_white_wine, where the value is 1 if type is white and 0 otherwise:" }, { "code": null, "e": 2502, "s": 2388, "text": "df['is_white_wine'] = [ 1 if typ == 'white' else 0 for typ in df['type']]df.drop('type', axis=1, inplace=True)" }, { "code": null, "e": 2615, "s": 2502, "text": "All features are numeric now, and there’s only one thing left to do — make the target variable (quality) binary." }, { "code": null, "e": 2703, "s": 2615, "text": "The wines are graded from 3 to 9, assuming higher is better. Here are the value counts:" }, { "code": null, "e": 2887, "s": 2703, "text": "To keep things extra simple, we’ll convert it into a binary variable. We’ll classify any wine with a grade of 6 and above as good (1), and all other wines as bad (0). Here’s the code:" }, { "code": null, "e": 3017, "s": 2887, "text": "df['is_good_wine'] = [ 1 if quality >= 6 else 0 for quality in df['quality']]df.drop('quality', axis=1, inplace=True)df.head()" }, { "code": null, "e": 3060, "s": 3017, "text": "And here’s how the dataset looks like now:" }, { "code": null, "e": 3225, "s": 3060, "text": "You now have 4091 good wines and 2372 bad wines. The classes are imbalanced, but we can work with that. Let’s split the dataset into training and testing sets next." }, { "code": null, "e": 3281, "s": 3225, "text": "We’ll stick to a standard 80:20 split. Here’s the code:" }, { "code": null, "e": 3488, "s": 3281, "text": "from sklearn.model_selection import train_test_splitX = df.drop('is_good_wine', axis=1)y = df['is_good_wine']X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42)" }, { "code": null, "e": 3685, "s": 3488, "text": "You now have 5170 rows in the training set and 1293 rows in the testing set. It should be enough to train a somewhat decent neural network model. Let’s scale the data before we start the training." }, { "code": null, "e": 3920, "s": 3685, "text": "Features like sulphates and citric acid have values close to zero, while total sulfur dioxide is in hundreds. You’ll confuse the neural network if you leave them as such, as it will think a feature on a higher scale is more important." }, { "code": null, "e": 4093, "s": 3920, "text": "That’s where scaling comes into play. We’ll use StandardScaler from Scikit-Learn to fit and transform the training data and to apply the transformation to the testing data:" }, { "code": null, "e": 4253, "s": 4093, "text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train_scaled = scaler.fit_transform(X_train)X_test_scaled = scaler.transform(X_test)" }, { "code": null, "e": 4303, "s": 4253, "text": "Here’s how the first three scaled rows look like:" }, { "code": null, "e": 4446, "s": 4303, "text": "The value range is much tighter now, so a neural network should do a better job. Let’s train the model and see if we can get something decent." }, { "code": null, "e": 4538, "s": 4446, "text": "You’ll need to keep a couple of things in mind when training a binary classification model:" }, { "code": null, "e": 4738, "s": 4538, "text": "Output layer structure — You’ll want to have one neuron activated with a sigmoid function. This will output a probability you can then assign to either a good wine (P > 0.5) or a bad wine (P <= 0.5)." }, { "code": null, "e": 4846, "s": 4738, "text": "Loss function — Binary cross-entropy is the one to go with. Don’t mistake it for categorical cross-entropy." }, { "code": null, "e": 5081, "s": 4846, "text": "Class balance — Are the classes in the target variable balanced? In other words, do you have roughly the same number of good and bad wines? If not, accuracy might not be the best evaluation metric. We’ll also use precision and recall." }, { "code": null, "e": 5169, "s": 5081, "text": "Let’s define a neural network architecture next, having the above three points in mind." }, { "code": null, "e": 5513, "s": 5169, "text": "I’ve chosen this architecture entirely at random, so feel free to adjust it. The model goes from 12 input features to the first hidden layer of 128 neurons, followed by two additional hidden layers of 256 neurons. There’s a 1-neuron output layer at the end. Hidden layers use ReLU as the activation function, and the output layer uses Sigmoid." }, { "code": null, "e": 5530, "s": 5513, "text": "Here’s the code:" }, { "code": null, "e": 6145, "s": 5530, "text": "import tensorflow as tftf.random.set_seed(42)model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])model.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(lr=0.03), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy'), tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall') ])history = model.fit(X_train_scaled, y_train, epochs=100)" }, { "code": null, "e": 6247, "s": 6145, "text": "This will initiate the training process. A single epoch takes around 1 second on my machine (M1 MBP):" }, { "code": null, "e": 6423, "s": 6247, "text": "We kept track of loss, accuracy, precision, and recall during training, and saved them to history. We can now visualize these metrics to get a sense of how the model is doing." }, { "code": null, "e": 6588, "s": 6423, "text": "Let’s start by importing Matplotlib and tweaking the default styles a bit. The following code snippet will make the plot larger and remove the top and right spines:" }, { "code": null, "e": 6759, "s": 6588, "text": "import matplotlib.pyplot as pltfrom matplotlib import rcParamsrcParams['figure.figsize'] = (18, 8)rcParams['axes.spines.top'] = FalsercParams['axes.spines.right'] = False" }, { "code": null, "e": 6986, "s": 6759, "text": "The plot will have multiple lines — for loss, accuracy, precision, and recall. They all share the X-axis, which represents the epoch number (np.arange(1, 101)). We should see loss decreasing, and every other metric increasing:" }, { "code": null, "e": 7386, "s": 6986, "text": "plt.plot( np.arange(1, 101), history.history['loss'], label='Loss')plt.plot( np.arange(1, 101), history.history['accuracy'], label='Accuracy')plt.plot( np.arange(1, 101), history.history['precision'], label='Precision')plt.plot( np.arange(1, 101), history.history['recall'], label='Recall')plt.title('Evaluation metrics', size=20)plt.xlabel('Epoch', size=14)plt.legend();" }, { "code": null, "e": 7405, "s": 7386, "text": "Let’s take a look:" }, { "code": null, "e": 7598, "s": 7405, "text": "Accuracy, precision, and recall increase slightly as we train the model, while loss decreases. All have occasional spikes, which would hopefully wear off if you were to train the model longer." }, { "code": null, "e": 7696, "s": 7598, "text": "According to the chart, you could train the model for more epochs, as there’s no sign of plateau." }, { "code": null, "e": 7744, "s": 7696, "text": "But are we overfitting? Let’s answer that next." }, { "code": null, "e": 7840, "s": 7744, "text": "You can now use the predict() function to get prediction probabilities on the scaled test data:" }, { "code": null, "e": 7883, "s": 7840, "text": "predictions = model.predict(X_test_scaled)" }, { "code": null, "e": 7910, "s": 7883, "text": "Here’s how they look like:" }, { "code": null, "e": 8082, "s": 7910, "text": "You’ll have to convert them to classes before evaluation. The logic is simple — if the probability is greater than 0.5 we assign 1 (good wine), and 0 (bad wine) otherwise:" }, { "code": null, "e": 8166, "s": 8082, "text": "prediction_classes = [ 1 if prob > 0.5 else 0 for prob in np.ravel(predictions)]" }, { "code": null, "e": 8201, "s": 8166, "text": "Here’s how the first 20 look like:" }, { "code": null, "e": 8253, "s": 8201, "text": "That’s all we need — let’s evaluate the model next." }, { "code": null, "e": 8292, "s": 8253, "text": "Let’s start with the confusion matrix:" }, { "code": null, "e": 8388, "s": 8292, "text": "from sklearn.metrics import confusion_matrixprint(confusion_matrix(y_test, prediction_classes))" }, { "code": null, "e": 8518, "s": 8388, "text": "There are more false negatives (214) than false positives (99), so the recall value on the test set will be lower than precision." }, { "code": null, "e": 8596, "s": 8518, "text": "The following snippet prints accuracy, precision, and recall on the test set:" }, { "code": null, "e": 8872, "s": 8596, "text": "from sklearn.metrics import accuracy_score, precision_score, recall_scoreprint(f'Accuracy: {accuracy_score(y_test, prediction_classes):.2f}')print(f'Precision: {precision_score(y_test, prediction_classes):.2f}')print(f'Recall: {recall_score(y_test, prediction_classes):.2f}')" }, { "code": null, "e": 8941, "s": 8872, "text": "All values are somewhat lower when compared to train set evaluation:" }, { "code": null, "e": 8956, "s": 8941, "text": "Accuracy: 0.82" }, { "code": null, "e": 8972, "s": 8956, "text": "Precision: 0.88" }, { "code": null, "e": 8985, "s": 8972, "text": "Recall: 0.83" }, { "code": null, "e": 9129, "s": 8985, "text": "The model is overfitting slightly, but it’s still decent work for a couple of minutes. We’ll go over the optimization in the following article." }, { "code": null, "e": 9348, "s": 9129, "text": "And that does it — you now know how to train a simple neural network for binary classification. The dataset we used today was relatively clean, and required almost zero preparation work. Don’t get used to that feeling." }, { "code": null, "e": 9654, "s": 9348, "text": "There’s a lot we can improve. For example, you could add additional layers to the network, increase the number of neurons, choose different activation functions, select a different optimizer, add dropout layers, and much more. The possibilities are almost endless, so it all boils down to experimentation." }, { "code": null, "e": 9841, "s": 9654, "text": "The following article will cover optimization — you’ll learn how to find the optimal learning rate and neural network architecture automatically, so stay tuned if you want to learn more." }, { "code": null, "e": 9861, "s": 9841, "text": "Thanks for reading." }, { "code": null, "e": 10044, "s": 9861, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 10055, "s": 10044, "text": "medium.com" }, { "code": null, "e": 10081, "s": 10055, "text": "Sign up for my newsletter" }, { "code": null, "e": 10102, "s": 10081, "text": "Subscribe on YouTube" } ]
Batch Script - toInt
A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished. @echo off set var = 13145 set /A var=%var% + 5 echo %var% The above command produces the following output. 13150 Apart from this, strings have the following implementations which are available. Batch scripts have the following commands which are used to carry out string manipulation in strings. %variable:~num_chars_to_skip% %variable:~num_chars_to_skip,num_chars_to_keep% This can include negative numbers − %variable:~num_chars_to_skip, -num_chars_to_keep% %variable:~-num_chars_to_skip,num_chars_to_keep% %variable:~-num_chars_to_skip,-num_chars_to_keep% Let us discuss the possible string operations that can be performed by using the above commands. Print Add Notes Bookmark this page
[ { "code": null, "e": 2374, "s": 2169, "text": "A variable which has been set as string using the set variable can be converted to an integer using the /A switch which is using the set variable. The following example shows how this can be accomplished." }, { "code": null, "e": 2432, "s": 2374, "text": "@echo off\nset var = 13145\nset /A var=%var% + 5\necho %var%" }, { "code": null, "e": 2481, "s": 2432, "text": "The above command produces the following output." }, { "code": null, "e": 2488, "s": 2481, "text": "13150\n" }, { "code": null, "e": 2671, "s": 2488, "text": "Apart from this, strings have the following implementations which are available. Batch scripts have the following commands which are used to carry out string manipulation in strings." }, { "code": null, "e": 2751, "s": 2671, "text": "%variable:~num_chars_to_skip% \n%variable:~num_chars_to_skip,num_chars_to_keep%\n" }, { "code": null, "e": 2787, "s": 2751, "text": "This can include negative numbers −" }, { "code": null, "e": 2937, "s": 2787, "text": "%variable:~num_chars_to_skip, -num_chars_to_keep%\n%variable:~-num_chars_to_skip,num_chars_to_keep%\n%variable:~-num_chars_to_skip,-num_chars_to_keep%\n" }, { "code": null, "e": 3034, "s": 2937, "text": "Let us discuss the possible string operations that can be performed by using the above commands." }, { "code": null, "e": 3041, "s": 3034, "text": " Print" }, { "code": null, "e": 3052, "s": 3041, "text": " Add Notes" } ]
Maximum height when coins are arranged in a triangle
21 Jun, 2022 We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins.Examples: Input : N = 7 Output : 3 Maximum height will be 3, putting 1, 2 and then 3 coins. It is not possible to use 1 coin left. Input : N = 12 Output : 4 Maximum height will be 4, putting 1, 2, 3 and 4 coins, it is not possible to make height as 5, because that will require 15 coins. This problem can be solved by finding a relation between height of the triangle and number of coins. Let maximum height is H, then total sum of coin should be less than N, Sum of coins for height H <= N H*(H + 1)/2 <= N H*H + H – 2*N <= 0 Now by Quadratic formula (ignoring negative root) Maximum H can be (-1 + √(1 + 8N)) / 2 Now we just need to find the square root of (1 + 8N) for which we can use Babylonian method of finding square root Below code is implemented on above stated concept, CPP Java Python3 C# PHP Javascript // C++ program to find maximum height of arranged// coin triangle#include <bits/stdc++.h>using namespace std; /* Returns the square root of n. Note that the function */float squareRoot(float n){ /* We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n/x; } return x;} // Method to find maximum height of arrangement of coinsint findMaximumHeight(int N){ // calculating portion inside the square root int n = 1 + 8*N; int maxH = (-1 + squareRoot(n)) / 2; return maxH;} // Driver code to test above methodint main(){ int N = 12; cout << findMaximumHeight(N) << endl; return 0;} // Java program to find maximum height// of arranged coin triangleclass GFG{ /* Returns the square root of n. Note that the function */ static float squareRoot(float n) { /* We are using n itself as initial approximation.This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level float e = 0.000001f; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Method to find maximum height // of arrangement of coins static int findMaximumHeight(int N) { // calculating portion inside // the square root int n = 1 + 8*N; int maxH = (int)(-1 + squareRoot(n)) / 2; return maxH; } // Driver code public static void main (String[] args) { int N = 12; System.out.print(findMaximumHeight(N)); }} // This code is contributed by Anant Agarwal. # Python3 program to find# maximum height of arranged# coin triangle # Returns the square root of n.# Note that the functiondef squareRoot(n): # We are using n itself as # initial approximation # This can definitely be improved x = n y = 1 e = 0.000001 # e decides the accuracy level while (x - y > e): x = (x + y) / 2 y = n/x return x # Method to find maximum height# of arrangement of coinsdef findMaximumHeight(N): # calculating portion inside the square root n = 1 + 8*N maxH = (-1 + squareRoot(n)) / 2 return int(maxH) # Driver code to test above methodN = 12print(findMaximumHeight(N)) # This code is contributed by# Smitha Dinesh Semwal // C# program to find maximum height// of arranged coin triangleusing System; class GFG{ /* Returns the square root of n. Note that the function */ static float squareRoot(float n) { /* We are using n itself as initial approximation.This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level float e = 0.000001f; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } static int findMaximumHeight(int N) { // calculating portion inside // the square root int n = 1 + 8*N; int maxH = (int)(-1 + squareRoot(n)) / 2; return maxH; } /* program to test above function */ public static void Main() { int N = 12; Console.Write(findMaximumHeight(N)); }} // This code is contributed by _omg <?php// PHP program to find maximum height// of arranged coin triangle /* Returns the square root of n. Notethat the function */function squareRoot( $n){ /* We are using n itself as initial approximation This can definitely be improved */ $x = $n; $y = 1; /* e decides the accuracy level*/ $e = 0.000001; while ($x - $y > $e) { $x = ($x + $y) / 2; $y = $n/$x; } return $x;} // Method to find maximum height of// arrangement of coinsfunction findMaximumHeight( $N){ // calculating portion inside // the square root $n = 1 + 8 * $N; $maxH = (-1 + squareRoot($n)) / 2; return floor($maxH);} // Driver code to test above method$N = 12;echo findMaximumHeight($N) ; // This code is contributed by anuj_67.?> <script> // Javascript program to find maximum height// of arranged coin triangle /* Returns the square root of n. Note that the function */ function squareRoot(n) { /* We are using n itself as initial approximation.This can definitely be improved */ let x = n; let y = 1; // e decides the accuracy level let e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Method to find maximum height // of arrangement of coins function findMaximumHeight(N) { // calculating portion inside // the square root let n = 1 + 8*N; let maxH = (-1 + squareRoot(n)) / 2; return Math.round(maxH); } // Driver Codelet N = 12;document.write(findMaximumHeight(N)); // This code is contributed by avijitmondal1998.</script> Output: 4 Time complexity: O(sqrt(n)) Auxiliary space: O(1) This article is contributed by Utkarsh Trivedi. 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. vt_m avijitmondal1998 shaheeneallamaiqbal mailaruyashaswi triangle Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Rotation of a point about another point in C++ Maximum Manhattan distance between a distinct pair from N coordinates C++ Program to Illustrate Trigonometric functions Total area of two overlapping rectangles Largest area possible after removal of a series of horizontal & vertical bars Program to find line passing through 2 Points Count ways to partition a string such that both parts have equal distinct characters Orientation of 3 ordered points Maximum distance between two points in coordinate plane using Rotating Caliper's Method Equation of circle when three points on the circle are given
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Jun, 2022" }, { "code": null, "e": 274, "s": 53, "text": "We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins.Examples: " }, { "code": null, "e": 556, "s": 274, "text": "Input : N = 7\nOutput : 3\nMaximum height will be 3, putting 1, 2 and\nthen 3 coins. It is not possible to use 1 \ncoin left.\n\nInput : N = 12\nOutput : 4\nMaximum height will be 4, putting 1, 2, 3 and \n4 coins, it is not possible to make height as 5, \nbecause that will require 15 coins." }, { "code": null, "e": 732, "s": 558, "text": "This problem can be solved by finding a relation between height of the triangle and number of coins. Let maximum height is H, then total sum of coin should be less than N, " }, { "code": null, "e": 1027, "s": 732, "text": "Sum of coins for height H <= N\n H*(H + 1)/2 <= N\n H*H + H – 2*N <= 0\nNow by Quadratic formula \n(ignoring negative root)\n\nMaximum H can be (-1 + √(1 + 8N)) / 2 \n\nNow we just need to find the square root of (1 + 8N) for\nwhich we can use Babylonian method of finding square root" }, { "code": null, "e": 1080, "s": 1027, "text": "Below code is implemented on above stated concept, " }, { "code": null, "e": 1084, "s": 1080, "text": "CPP" }, { "code": null, "e": 1089, "s": 1084, "text": "Java" }, { "code": null, "e": 1097, "s": 1089, "text": "Python3" }, { "code": null, "e": 1100, "s": 1097, "text": "C#" }, { "code": null, "e": 1104, "s": 1100, "text": "PHP" }, { "code": null, "e": 1115, "s": 1104, "text": "Javascript" }, { "code": "// C++ program to find maximum height of arranged// coin triangle#include <bits/stdc++.h>using namespace std; /* Returns the square root of n. Note that the function */float squareRoot(float n){ /* We are using n itself as initial approximation This can definitely be improved */ float x = n; float y = 1; float e = 0.000001; /* e decides the accuracy level*/ while (x - y > e) { x = (x + y) / 2; y = n/x; } return x;} // Method to find maximum height of arrangement of coinsint findMaximumHeight(int N){ // calculating portion inside the square root int n = 1 + 8*N; int maxH = (-1 + squareRoot(n)) / 2; return maxH;} // Driver code to test above methodint main(){ int N = 12; cout << findMaximumHeight(N) << endl; return 0;}", "e": 1911, "s": 1115, "text": null }, { "code": "// Java program to find maximum height// of arranged coin triangleclass GFG{ /* Returns the square root of n. Note that the function */ static float squareRoot(float n) { /* We are using n itself as initial approximation.This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level float e = 0.000001f; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Method to find maximum height // of arrangement of coins static int findMaximumHeight(int N) { // calculating portion inside // the square root int n = 1 + 8*N; int maxH = (int)(-1 + squareRoot(n)) / 2; return maxH; } // Driver code public static void main (String[] args) { int N = 12; System.out.print(findMaximumHeight(N)); }} // This code is contributed by Anant Agarwal.", "e": 2946, "s": 1911, "text": null }, { "code": "# Python3 program to find# maximum height of arranged# coin triangle # Returns the square root of n.# Note that the functiondef squareRoot(n): # We are using n itself as # initial approximation # This can definitely be improved x = n y = 1 e = 0.000001 # e decides the accuracy level while (x - y > e): x = (x + y) / 2 y = n/x return x # Method to find maximum height# of arrangement of coinsdef findMaximumHeight(N): # calculating portion inside the square root n = 1 + 8*N maxH = (-1 + squareRoot(n)) / 2 return int(maxH) # Driver code to test above methodN = 12print(findMaximumHeight(N)) # This code is contributed by# Smitha Dinesh Semwal", "e": 3663, "s": 2946, "text": null }, { "code": "// C# program to find maximum height// of arranged coin triangleusing System; class GFG{ /* Returns the square root of n. Note that the function */ static float squareRoot(float n) { /* We are using n itself as initial approximation.This can definitely be improved */ float x = n; float y = 1; // e decides the accuracy level float e = 0.000001f; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } static int findMaximumHeight(int N) { // calculating portion inside // the square root int n = 1 + 8*N; int maxH = (int)(-1 + squareRoot(n)) / 2; return maxH; } /* program to test above function */ public static void Main() { int N = 12; Console.Write(findMaximumHeight(N)); }} // This code is contributed by _omg", "e": 4579, "s": 3663, "text": null }, { "code": "<?php// PHP program to find maximum height// of arranged coin triangle /* Returns the square root of n. Notethat the function */function squareRoot( $n){ /* We are using n itself as initial approximation This can definitely be improved */ $x = $n; $y = 1; /* e decides the accuracy level*/ $e = 0.000001; while ($x - $y > $e) { $x = ($x + $y) / 2; $y = $n/$x; } return $x;} // Method to find maximum height of// arrangement of coinsfunction findMaximumHeight( $N){ // calculating portion inside // the square root $n = 1 + 8 * $N; $maxH = (-1 + squareRoot($n)) / 2; return floor($maxH);} // Driver code to test above method$N = 12;echo findMaximumHeight($N) ; // This code is contributed by anuj_67.?>", "e": 5350, "s": 4579, "text": null }, { "code": "<script> // Javascript program to find maximum height// of arranged coin triangle /* Returns the square root of n. Note that the function */ function squareRoot(n) { /* We are using n itself as initial approximation.This can definitely be improved */ let x = n; let y = 1; // e decides the accuracy level let e = 0.000001; while (x - y > e) { x = (x + y) / 2; y = n / x; } return x; } // Method to find maximum height // of arrangement of coins function findMaximumHeight(N) { // calculating portion inside // the square root let n = 1 + 8*N; let maxH = (-1 + squareRoot(n)) / 2; return Math.round(maxH); } // Driver Codelet N = 12;document.write(findMaximumHeight(N)); // This code is contributed by avijitmondal1998.</script>", "e": 6311, "s": 5350, "text": null }, { "code": null, "e": 6321, "s": 6311, "text": "Output: " }, { "code": null, "e": 6323, "s": 6321, "text": "4" }, { "code": null, "e": 6351, "s": 6323, "text": "Time complexity: O(sqrt(n))" }, { "code": null, "e": 6373, "s": 6351, "text": "Auxiliary space: O(1)" }, { "code": null, "e": 6797, "s": 6373, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6802, "s": 6797, "text": "vt_m" }, { "code": null, "e": 6819, "s": 6802, "text": "avijitmondal1998" }, { "code": null, "e": 6839, "s": 6819, "text": "shaheeneallamaiqbal" }, { "code": null, "e": 6855, "s": 6839, "text": "mailaruyashaswi" }, { "code": null, "e": 6864, "s": 6855, "text": "triangle" }, { "code": null, "e": 6874, "s": 6864, "text": "Geometric" }, { "code": null, "e": 6884, "s": 6874, "text": "Geometric" }, { "code": null, "e": 6982, "s": 6884, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7029, "s": 6982, "text": "Rotation of a point about another point in C++" }, { "code": null, "e": 7099, "s": 7029, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 7149, "s": 7099, "text": "C++ Program to Illustrate Trigonometric functions" }, { "code": null, "e": 7190, "s": 7149, "text": "Total area of two overlapping rectangles" }, { "code": null, "e": 7268, "s": 7190, "text": "Largest area possible after removal of a series of horizontal & vertical bars" }, { "code": null, "e": 7314, "s": 7268, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 7399, "s": 7314, "text": "Count ways to partition a string such that both parts have equal distinct characters" }, { "code": null, "e": 7431, "s": 7399, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 7519, "s": 7431, "text": "Maximum distance between two points in coordinate plane using Rotating Caliper's Method" } ]
Print array elements in alternatively increasing and decreasing order in C++
In this problem, we are given an array of number and we have to print the elements of the array in alternatively increasing and decreasing order while printing. The alternative order will be in such a way that 1st two elements are in increasing order and then the next three elements are in decreasing order again next four are in ascending order. Let’s take an example to understand the problem better, Input : {1, 4, 0, 2, 7, 9, 3} Output : 0 1 9 7 4 2 3 Explanation − the array in increasing order of elements is 0 1 2 3 4 7 9. The first 2 elements are 0 1. The last 3 elements are 9 7 4. Next 4 four elements are 2 3 (we could take 4 elements but there are only 2 in the array). To solve this problem, we will first sort the array in ascending order. Now, we will use two pointers one for printing elements from start and one for printing element for the end. We will also use one flag element to check if the print is to be done from the start or from the end. Step 1 : Sort elements of the array. Step 2 : Initialise left = 0 , right = n-1 , flag = 2. Step 3 : while l is less than equal to r. Do : Step 4 : If flag%2 == 0. Do : Step 4.1 : loop from i = left to left + flag. And print arr[i]. Step 4.2 : update left = i ; flag ++; Step 5 : else. Do : Step 5.1 : loop from i = right to right - flag. And print arr[i]. Step 5.2 : update right = i and flag ++. Step 6 : EXIT Now, let’s create a program to illustrate the working of this algorithm. Live Demo #include <bits/stdc++.h> using namespace std; void printAlternateSeq(int arr[], int n){ sort(arr, arr + n); int left = 0, right = n - 1, flag = 2, i; while (left <= right) { if (flag%2 == 0) { for (i = left; i < left + flag && i <= right; i++) cout<<arr[i]<<" "; left = i; } else { for (i = right; i > right - flag && i >= left; i--) cout<<arr[i]<<" "; right = i; } flag++; } } int main(){ int n = 6; int arr[] = {23, 45, 78, 32, 89, 10 }; printAlternateSeq(arr, n); return 0; } 10 23 89 78 45 32
[ { "code": null, "e": 1535, "s": 1187, "text": "In this problem, we are given an array of number and we have to print the elements of the array in alternatively increasing and decreasing order while printing. The alternative order will be in such a way that 1st two elements are in increasing order and then the next three elements are in decreasing order again next four are in ascending order." }, { "code": null, "e": 1591, "s": 1535, "text": "Let’s take an example to understand the problem better," }, { "code": null, "e": 1645, "s": 1591, "text": "Input : {1, 4, 0, 2, 7, 9, 3}\nOutput : 0 1 9 7 4 2 3" }, { "code": null, "e": 1871, "s": 1645, "text": "Explanation − the array in increasing order of elements is 0 1 2 3 4 7 9. The first 2 elements are 0 1. The last 3 elements are 9 7 4. Next 4 four elements are 2 3 (we could take 4 elements but there are only 2 in the array)." }, { "code": null, "e": 2154, "s": 1871, "text": "To solve this problem, we will first sort the array in ascending order. Now, we will use two pointers one for printing elements from start and one for printing element for the end. We will also use one flag element to check if the print is to be done from the start or from the end." }, { "code": null, "e": 2578, "s": 2154, "text": "Step 1 : Sort elements of the array.\nStep 2 : Initialise left = 0 , right = n-1 , flag = 2.\nStep 3 : while l is less than equal to r. Do :\nStep 4 : If flag%2 == 0. Do :\n Step 4.1 : loop from i = left to left + flag. And print arr[i].\n Step 4.2 : update left = i ; flag ++;\nStep 5 : else. Do :\n Step 5.1 : loop from i = right to right - flag. And print arr[i].\n Step 5.2 : update right = i and flag ++.\nStep 6 : EXIT" }, { "code": null, "e": 2651, "s": 2578, "text": "Now, let’s create a program to illustrate the working of this algorithm." }, { "code": null, "e": 2662, "s": 2651, "text": " Live Demo" }, { "code": null, "e": 3246, "s": 2662, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid printAlternateSeq(int arr[], int n){\n sort(arr, arr + n);\n int left = 0, right = n - 1, flag = 2, i;\n while (left <= right) {\n if (flag%2 == 0) {\n for (i = left; i < left + flag && i <= right; i++)\n cout<<arr[i]<<\" \";\n left = i;\n } else {\n for (i = right; i > right - flag && i >= left; i--)\n cout<<arr[i]<<\" \";\n right = i;\n }\n flag++;\n }\n}\nint main(){\n int n = 6;\n int arr[] = {23, 45, 78, 32, 89, 10 };\n printAlternateSeq(arr, n);\n return 0;\n}" }, { "code": null, "e": 3264, "s": 3246, "text": "10 23 89 78 45 32" } ]
KeyStore getKey() method in Java with Examples
10 Dec, 2019 The getKey() method of java.security.KeyStore class is used to get the key associated with the given alias, using the given password to recover it. Syntax: public final Key getKey(String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException Parameter: This method accepts following parameters: alias: which is the alias name with whom the key is to be checked password: which is the password for recovering the key that is to be checked Return Value: This method returns the key for the requested alias if it exists. Exception: This method throws following exceptions KeyStoreException: if keystore is not loaded. NoSuchAlgorithmException: if the algorithm is missing Note: All the programs in this article won’t run on online IDE as no ‘privatekey’ Keystore exists. You can check this code on Java compiler on your system. To check this code, create a Keystore ‘privatekey’ on your system and set your own Keystore password to access that Keystore. Below are the examples to illustrate the getKey() method: Example 1: // Java program to demonstrate getKey() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance // By using getInstance() method KeyStore sr = KeyStore.getInstance("JKS"); // keystore password is required to access keystore char[] pass = ("123456").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( "f:/java/private key.store"); // initializing keystore object sr.load(is, pass); // getting the Key // using getKey() method Key key = sr.getKey("ftpkey", pass); // display the result System.out.println("Key : " + key); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (KeyStoreException e) { System.out.println("Exception thrown : " + e); } catch (FileNotFoundException e) { System.out.println("Exception thrown : " + e); } catch (IOException e) { System.out.println("Exception thrown : " + e); } catch (CertificateException e) { System.out.println("Exception thrown : " + e); } catch (UnrecoverableKeyException e) { System.out.println("Exception thrown : " + e); } }} Example 2: For KeyStoreException // Java program to demonstrate getKey() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance // By using getInstance() method KeyStore sr = KeyStore.getInstance("JKS"); // keystore password is required to access keystore char[] pass = ("123456").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( "f:/java/private key.store"); // initializing keystore object // sr.load(is, pass); // getting the Key // using getKey() method Key key = sr.getKey("ftpkey", pass); // display the result System.out.println("Key : " + key); } catch (FileNotFoundException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (KeyStoreException e) { System.out.println("\nException thrown : " + e); } catch (UnrecoverableKeyException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } }} Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyStore.html#getKey-java.lang.String-char:A- shubham_singh Java-Functions Java-KeyStore Java-security package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Stack Class in Java Introduction to Java
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2019" }, { "code": null, "e": 176, "s": 28, "text": "The getKey() method of java.security.KeyStore class is used to get the key associated with the given alias, using the given password to recover it." }, { "code": null, "e": 184, "s": 176, "text": "Syntax:" }, { "code": null, "e": 345, "s": 184, "text": "public final Key getKey(String alias, char[] password)\n throws KeyStoreException, \n NoSuchAlgorithmException, \n UnrecoverableKeyException" }, { "code": null, "e": 398, "s": 345, "text": "Parameter: This method accepts following parameters:" }, { "code": null, "e": 464, "s": 398, "text": "alias: which is the alias name with whom the key is to be checked" }, { "code": null, "e": 541, "s": 464, "text": "password: which is the password for recovering the key that is to be checked" }, { "code": null, "e": 621, "s": 541, "text": "Return Value: This method returns the key for the requested alias if it exists." }, { "code": null, "e": 672, "s": 621, "text": "Exception: This method throws following exceptions" }, { "code": null, "e": 718, "s": 672, "text": "KeyStoreException: if keystore is not loaded." }, { "code": null, "e": 772, "s": 718, "text": "NoSuchAlgorithmException: if the algorithm is missing" }, { "code": null, "e": 1054, "s": 772, "text": "Note: All the programs in this article won’t run on online IDE as no ‘privatekey’ Keystore exists. You can check this code on Java compiler on your system. To check this code, create a Keystore ‘privatekey’ on your system and set your own Keystore password to access that Keystore." }, { "code": null, "e": 1112, "s": 1054, "text": "Below are the examples to illustrate the getKey() method:" }, { "code": null, "e": 1123, "s": 1112, "text": "Example 1:" }, { "code": "// Java program to demonstrate getKey() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance // By using getInstance() method KeyStore sr = KeyStore.getInstance(\"JKS\"); // keystore password is required to access keystore char[] pass = (\"123456\").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( \"f:/java/private key.store\"); // initializing keystore object sr.load(is, pass); // getting the Key // using getKey() method Key key = sr.getKey(\"ftpkey\", pass); // display the result System.out.println(\"Key : \" + key); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (KeyStoreException e) { System.out.println(\"Exception thrown : \" + e); } catch (FileNotFoundException e) { System.out.println(\"Exception thrown : \" + e); } catch (IOException e) { System.out.println(\"Exception thrown : \" + e); } catch (CertificateException e) { System.out.println(\"Exception thrown : \" + e); } catch (UnrecoverableKeyException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 2894, "s": 1123, "text": null }, { "code": null, "e": 2927, "s": 2894, "text": "Example 2: For KeyStoreException" }, { "code": "// Java program to demonstrate getKey() method import java.security.*;import java.security.cert.*;import java.util.*;import java.io.*; public class GFG { public static void main(String[] argv) { try { // creating the object of KeyStore // and getting instance // By using getInstance() method KeyStore sr = KeyStore.getInstance(\"JKS\"); // keystore password is required to access keystore char[] pass = (\"123456\").toCharArray(); // creating and initializing object of InputStream InputStream is = new FileInputStream( \"f:/java/private key.store\"); // initializing keystore object // sr.load(is, pass); // getting the Key // using getKey() method Key key = sr.getKey(\"ftpkey\", pass); // display the result System.out.println(\"Key : \" + key); } catch (FileNotFoundException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (KeyStoreException e) { System.out.println(\"\\nException thrown : \" + e); } catch (UnrecoverableKeyException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 4492, "s": 2927, "text": null }, { "code": null, "e": 4605, "s": 4492, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyStore.html#getKey-java.lang.String-char:A-" }, { "code": null, "e": 4619, "s": 4605, "text": "shubham_singh" }, { "code": null, "e": 4634, "s": 4619, "text": "Java-Functions" }, { "code": null, "e": 4648, "s": 4634, "text": "Java-KeyStore" }, { "code": null, "e": 4670, "s": 4648, "text": "Java-security package" }, { "code": null, "e": 4675, "s": 4670, "text": "Java" }, { "code": null, "e": 4680, "s": 4675, "text": "Java" }, { "code": null, "e": 4778, "s": 4680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4829, "s": 4778, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 4860, "s": 4829, "text": "How to iterate any Map in Java" }, { "code": null, "e": 4879, "s": 4860, "text": "Interfaces in Java" }, { "code": null, "e": 4894, "s": 4879, "text": "Stream In Java" }, { "code": null, "e": 4912, "s": 4894, "text": "ArrayList in Java" }, { "code": null, "e": 4932, "s": 4912, "text": "Collections in Java" }, { "code": null, "e": 4956, "s": 4932, "text": "Singleton Class in Java" }, { "code": null, "e": 4988, "s": 4956, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 5008, "s": 4988, "text": "Stack Class in Java" } ]
Create Countdown Timer using Python-Tkinter
20 Jan, 2022 Prerequisites: Python GUI – tkinterPython Tkinter is a GUI programming package or built-in library. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Approach Importing the module – tkinter, timeCreate the main window (container)Add number of widgets to the main window:Button, EntryApply the event Trigger on the widgets. Importing the module – tkinter, time Create the main window (container) Add number of widgets to the main window:Button, Entry Apply the event Trigger on the widgets. Below is the implementation. python3 import timefrom tkinter import *from tkinter import messagebox # creating Tk windowroot = Tk() # setting geometry of tk windowroot.geometry("300x250") # Using title() to display a message in# the dialogue box of the message in the# title bar.root.title("Time Counter") # Declaration of variableshour=StringVar()minute=StringVar()second=StringVar() # setting the default value as 0hour.set("00")minute.set("00")second.set("00") # Use of Entry class to take input from the userhourEntry= Entry(root, width=3, font=("Arial",18,""), textvariable=hour)hourEntry.place(x=80,y=20) minuteEntry= Entry(root, width=3, font=("Arial",18,""), textvariable=minute)minuteEntry.place(x=130,y=20) secondEntry= Entry(root, width=3, font=("Arial",18,""), textvariable=second)secondEntry.place(x=180,y=20) def submit(): try: # the input provided by the user is # stored in here :temp temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get()) except: print("Please input the right value") while temp >-1: # divmod(firstvalue = temp//60, secondvalue = temp%60) mins,secs = divmod(temp,60) # Converting the input entered in mins or secs to hours, # mins ,secs(input = 110 min --> 120*60 = 6600 => 1hr : # 50min: 0sec) hours=0 if mins >60: # divmod(firstvalue = temp//60, secondvalue # = temp%60) hours, mins = divmod(mins, 60) # using format () method to store the value up to # two decimal places hour.set("{0:2d}".format(hours)) minute.set("{0:2d}".format(mins)) second.set("{0:2d}".format(secs)) # updating the GUI window after decrementing the # temp value every time root.update() time.sleep(1) # when temp value = 0; then a messagebox pop's up # with a message:"Time's up" if (temp == 0): messagebox.showinfo("Time Countdown", "Time's up ") # after every one sec the value of temp will be decremented # by one temp -= 1 # button widgetbtn = Button(root, text='Set Time Countdown', bd='5', command= submit)btn.place(x = 70,y = 120) # infinite loop which is required to# run tkinter program infinitely# until an interrupt occursroot.mainloop() Output: tuqajazara sumitgumber28 Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jan, 2022" }, { "code": null, "e": 364, "s": 52, "text": "Prerequisites: Python GUI – tkinterPython Tkinter is a GUI programming package or built-in library. Tkinter provides the Tk GUI toolkit with a potent object-oriented interface. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.Approach " }, { "code": null, "e": 528, "s": 364, "text": "Importing the module – tkinter, timeCreate the main window (container)Add number of widgets to the main window:Button, EntryApply the event Trigger on the widgets." }, { "code": null, "e": 565, "s": 528, "text": "Importing the module – tkinter, time" }, { "code": null, "e": 600, "s": 565, "text": "Create the main window (container)" }, { "code": null, "e": 655, "s": 600, "text": "Add number of widgets to the main window:Button, Entry" }, { "code": null, "e": 695, "s": 655, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 726, "s": 695, "text": "Below is the implementation. " }, { "code": null, "e": 734, "s": 726, "text": "python3" }, { "code": "import timefrom tkinter import *from tkinter import messagebox # creating Tk windowroot = Tk() # setting geometry of tk windowroot.geometry(\"300x250\") # Using title() to display a message in# the dialogue box of the message in the# title bar.root.title(\"Time Counter\") # Declaration of variableshour=StringVar()minute=StringVar()second=StringVar() # setting the default value as 0hour.set(\"00\")minute.set(\"00\")second.set(\"00\") # Use of Entry class to take input from the userhourEntry= Entry(root, width=3, font=(\"Arial\",18,\"\"), textvariable=hour)hourEntry.place(x=80,y=20) minuteEntry= Entry(root, width=3, font=(\"Arial\",18,\"\"), textvariable=minute)minuteEntry.place(x=130,y=20) secondEntry= Entry(root, width=3, font=(\"Arial\",18,\"\"), textvariable=second)secondEntry.place(x=180,y=20) def submit(): try: # the input provided by the user is # stored in here :temp temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get()) except: print(\"Please input the right value\") while temp >-1: # divmod(firstvalue = temp//60, secondvalue = temp%60) mins,secs = divmod(temp,60) # Converting the input entered in mins or secs to hours, # mins ,secs(input = 110 min --> 120*60 = 6600 => 1hr : # 50min: 0sec) hours=0 if mins >60: # divmod(firstvalue = temp//60, secondvalue # = temp%60) hours, mins = divmod(mins, 60) # using format () method to store the value up to # two decimal places hour.set(\"{0:2d}\".format(hours)) minute.set(\"{0:2d}\".format(mins)) second.set(\"{0:2d}\".format(secs)) # updating the GUI window after decrementing the # temp value every time root.update() time.sleep(1) # when temp value = 0; then a messagebox pop's up # with a message:\"Time's up\" if (temp == 0): messagebox.showinfo(\"Time Countdown\", \"Time's up \") # after every one sec the value of temp will be decremented # by one temp -= 1 # button widgetbtn = Button(root, text='Set Time Countdown', bd='5', command= submit)btn.place(x = 70,y = 120) # infinite loop which is required to# run tkinter program infinitely# until an interrupt occursroot.mainloop()", "e": 3129, "s": 734, "text": null }, { "code": null, "e": 3138, "s": 3129, "text": "Output: " }, { "code": null, "e": 3151, "s": 3140, "text": "tuqajazara" }, { "code": null, "e": 3165, "s": 3151, "text": "sumitgumber28" }, { "code": null, "e": 3190, "s": 3165, "text": "Python Tkinter-exercises" }, { "code": null, "e": 3205, "s": 3190, "text": "Python-tkinter" }, { "code": null, "e": 3212, "s": 3205, "text": "Python" } ]
Number of ways to go from one point to another in a grid
16 Apr, 2021 Given the NxN grid of horizontal and vertical roads. The task is to find out the number of ways that the person can go from point A to point B using the shortest possible path.Note: A and B point are fixed i.e A is at top left corner and B at bottom right corner as shown in the below image. In the above image, the path shown in the red and light green colour are the two possible paths to reach from point A to point B.Examples: Input: N = 3 Output: Ways = 20 Input: N = 4 Output: Ways = 70 Formula: Let the grid be N x N, number of ways can be written as. How does above formula work? Let consider the example of the 5×5 grid as shown above. In order to go from point A to point B in the 5×5 grid, We have to take 5 horizontal steps and 5 vertical steps. Each path will be an arrangement of 10 steps out of which 5 steps are identical of one kind and other 5 steps are identical of a second kind. ThereforeNo. of ways = 10! / (5! * 5!) i.e 252 ways. C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // function that will// calculate the factoriallong factorial(int N){ int result = 1; while (N > 0) { result = result * N; N--; } return result;} long countWays(int N){ long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1;} // Driver codeint main(){ int N = 5; cout << "Ways = " << countWays(N); return 0;} // Java implementation of above approachclass GfG { // function that will // calculate the factorial static long factorial(int N) { int result = 1; while (N > 0) { result = result * N; N--; } return result; } static long countWays(int N) { long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1; } // Driver code public static void main(String[] args) { int N = 5; System.out.println("Ways = " + countWays(N)); }} # Python3 implementation of above approach # function that will calculate the factorialdef factorial(N) : result = 1; while (N > 0) : result = result * N; N -= 1; return result; def countWays(N) : total = factorial(N + N); total1 = factorial(N); return (total // total1) // total1; # Driver codeif __name__ == "__main__" : N = 5; print("Ways =", countWays(N)); # This code is contributed by Ryuga // C# implementation of above approachusing System;class GfG{ // function that will // calculate the factorial static long factorial(int N) { int result = 1; while (N > 0) { result = result * N; N--; } return result; } static long countWays(int N) { long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1; } // Driver code public static void Main(String []args) { int N = 5; Console.WriteLine("Ways = " + countWays(N)); }} // This code is contributed by Arnab Kundu <?php// PHP implementation of above approach // function that will// calculate the factorialfunction factorial($N){ $result = 1; while ($N > 0) { $result = $result * $N; $N--; } return $result;} function countWays($N){ $total = factorial($N + $N); $total1 = factorial($N); return ($total / $total1) / $total1;} // Driver code$N = 5;echo "Ways = ", countWays($N); // This code is contributed by ajit?> <script> // Javascript implementation of above approach // function that will// calculate the factorialfunction factorial(N){ var result = 1; while (N > 0) { result = result * N; N--; } return result;} function countWays(N){ var total = factorial(N + N); var total1 = factorial(N); return (total / total1) / total1;} // Driver codevar N = 5;document.write( "Ways = " + countWays(N)); // This code is contributed by rutvik_56.</script> Ways = 252 prerna saini andrew1234 ankthon jit_t rutvik_56 binomial coefficient factorial Marketing Permutation and Combination Combinatorial Combinatorial factorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Apr, 2021" }, { "code": null, "e": 345, "s": 52, "text": "Given the NxN grid of horizontal and vertical roads. The task is to find out the number of ways that the person can go from point A to point B using the shortest possible path.Note: A and B point are fixed i.e A is at top left corner and B at bottom right corner as shown in the below image. " }, { "code": null, "e": 486, "s": 345, "text": "In the above image, the path shown in the red and light green colour are the two possible paths to reach from point A to point B.Examples: " }, { "code": null, "e": 549, "s": 486, "text": "Input: N = 3\nOutput: Ways = 20\n\nInput: N = 4\nOutput: Ways = 70" }, { "code": null, "e": 619, "s": 551, "text": "Formula: Let the grid be N x N, number of ways can be written as. " }, { "code": null, "e": 1014, "s": 619, "text": "How does above formula work? Let consider the example of the 5×5 grid as shown above. In order to go from point A to point B in the 5×5 grid, We have to take 5 horizontal steps and 5 vertical steps. Each path will be an arrangement of 10 steps out of which 5 steps are identical of one kind and other 5 steps are identical of a second kind. ThereforeNo. of ways = 10! / (5! * 5!) i.e 252 ways. " }, { "code": null, "e": 1018, "s": 1014, "text": "C++" }, { "code": null, "e": 1023, "s": 1018, "text": "Java" }, { "code": null, "e": 1031, "s": 1023, "text": "Python3" }, { "code": null, "e": 1034, "s": 1031, "text": "C#" }, { "code": null, "e": 1038, "s": 1034, "text": "PHP" }, { "code": null, "e": 1049, "s": 1038, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // function that will// calculate the factoriallong factorial(int N){ int result = 1; while (N > 0) { result = result * N; N--; } return result;} long countWays(int N){ long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1;} // Driver codeint main(){ int N = 5; cout << \"Ways = \" << countWays(N); return 0;}", "e": 1523, "s": 1049, "text": null }, { "code": "// Java implementation of above approachclass GfG { // function that will // calculate the factorial static long factorial(int N) { int result = 1; while (N > 0) { result = result * N; N--; } return result; } static long countWays(int N) { long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1; } // Driver code public static void main(String[] args) { int N = 5; System.out.println(\"Ways = \" + countWays(N)); }}", "e": 2098, "s": 1523, "text": null }, { "code": "# Python3 implementation of above approach # function that will calculate the factorialdef factorial(N) : result = 1; while (N > 0) : result = result * N; N -= 1; return result; def countWays(N) : total = factorial(N + N); total1 = factorial(N); return (total // total1) // total1; # Driver codeif __name__ == \"__main__\" : N = 5; print(\"Ways =\", countWays(N)); # This code is contributed by Ryuga", "e": 2569, "s": 2098, "text": null }, { "code": "// C# implementation of above approachusing System;class GfG{ // function that will // calculate the factorial static long factorial(int N) { int result = 1; while (N > 0) { result = result * N; N--; } return result; } static long countWays(int N) { long total = factorial(N + N); long total1 = factorial(N); return (total / total1) / total1; } // Driver code public static void Main(String []args) { int N = 5; Console.WriteLine(\"Ways = \" + countWays(N)); }} // This code is contributed by Arnab Kundu", "e": 3203, "s": 2569, "text": null }, { "code": "<?php// PHP implementation of above approach // function that will// calculate the factorialfunction factorial($N){ $result = 1; while ($N > 0) { $result = $result * $N; $N--; } return $result;} function countWays($N){ $total = factorial($N + $N); $total1 = factorial($N); return ($total / $total1) / $total1;} // Driver code$N = 5;echo \"Ways = \", countWays($N); // This code is contributed by ajit?>", "e": 3646, "s": 3203, "text": null }, { "code": "<script> // Javascript implementation of above approach // function that will// calculate the factorialfunction factorial(N){ var result = 1; while (N > 0) { result = result * N; N--; } return result;} function countWays(N){ var total = factorial(N + N); var total1 = factorial(N); return (total / total1) / total1;} // Driver codevar N = 5;document.write( \"Ways = \" + countWays(N)); // This code is contributed by rutvik_56.</script>", "e": 4116, "s": 3646, "text": null }, { "code": null, "e": 4127, "s": 4116, "text": "Ways = 252" }, { "code": null, "e": 4142, "s": 4129, "text": "prerna saini" }, { "code": null, "e": 4153, "s": 4142, "text": "andrew1234" }, { "code": null, "e": 4161, "s": 4153, "text": "ankthon" }, { "code": null, "e": 4167, "s": 4161, "text": "jit_t" }, { "code": null, "e": 4177, "s": 4167, "text": "rutvik_56" }, { "code": null, "e": 4198, "s": 4177, "text": "binomial coefficient" }, { "code": null, "e": 4208, "s": 4198, "text": "factorial" }, { "code": null, "e": 4218, "s": 4208, "text": "Marketing" }, { "code": null, "e": 4246, "s": 4218, "text": "Permutation and Combination" }, { "code": null, "e": 4260, "s": 4246, "text": "Combinatorial" }, { "code": null, "e": 4274, "s": 4260, "text": "Combinatorial" }, { "code": null, "e": 4284, "s": 4274, "text": "factorial" } ]
Java Program to Concatenate Two List
19 Jan, 2021 Concatenating two lists means merging two lists into a single list. Consider the given lists: LIST 1 LIST 2 LIST AFTER CONCATENATION There are several methods to perform concatenation operation: Using addAll() methodUsing streamUsing union() Using addAll() method Using stream Using union() Method 1: Using addAll() method Syntax: addAll ( list name ) This method takes name of list as argument and add all the elements of the specified list in the same order as the original list. Create a new empty list ( concatenated_list) Use addAll () method to concatenate the given list1 and list2 into the newly created list. concatenated_list.addAll (list1) // concatenates first list concatenated_list.addAll (list2) // concatenates second list After performing the above steps our empty list now contains both the list. Java // Java Program to Concatenate Two List// using addAll() method import java.io.*;import java.util.ArrayList;import java.util.List; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using addAll( ) method to concatenate the lists concatenated_list.addAll(list1); concatenated_list.addAll(list2); System.out.println("list1: " + list1); System.out.println("list2: " + list2); System.out.println("Concatenated list: " + concatenated_list); }} list1: [1, 2, 3, 4] list2: [5, 6, 7, 8] Concatenated list: [1, 2, 3, 4, 5, 6, 7, 8] Method 2: Using streams Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList()) It takes two streams as argument and creates a concatenated stream out of them.Second list is appended to the first list. Java // Java Program to Concatenate Two List // using streams import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using Stream.concat() method to concatenate the lists concatenated_list = Stream.concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); System.out.println("list1: " + list1); System.out.println("list2: " + list2); System.out.println("Concatenated list: "+ concatenated_list); }} list1: [1, 2, 3, 4] list2: [5, 6, 7, 8] Concatenated list: [1, 2, 3, 4, 5, 6, 7, 8] Method 3: Using union() ListUtils.union( list1, list2) It takes two list as argument and return new concatenated list. Second list is appended to the first list. Java // Java program to concatenate two lists// using union() import java.io.*;import java.util.*;import java.lang.*;import org.apache.commons.collections.ListUtils; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using ListUtils.union() method to concatenate // the lists concatenated_list = ListUtils.union(list1, list2); System.out.println("list1: " + list1); System.out.println("list2: " + list2); System.out.println("Concatenated list: " + concatenated_list); }} Output: Prerequisites for running the above code: Download and Install the following Apache Commons Collections library http://commons.apache.org/proper/commons-collections/download_collections.cgi Now go to the properties of your project. Select Java Build Path. Under Java Build Path go to libraries. Under libraries select Classpath. Now go to add external JARs and add the JAR executable file, downloaded from the given link. Java-Collections java-list Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Jan, 2021" }, { "code": null, "e": 120, "s": 52, "text": "Concatenating two lists means merging two lists into a single list." }, { "code": null, "e": 146, "s": 120, "text": "Consider the given lists:" }, { "code": null, "e": 153, "s": 146, "text": "LIST 1" }, { "code": null, "e": 160, "s": 153, "text": "LIST 2" }, { "code": null, "e": 185, "s": 160, "text": "LIST AFTER CONCATENATION" }, { "code": null, "e": 247, "s": 185, "text": "There are several methods to perform concatenation operation:" }, { "code": null, "e": 294, "s": 247, "text": "Using addAll() methodUsing streamUsing union()" }, { "code": null, "e": 316, "s": 294, "text": "Using addAll() method" }, { "code": null, "e": 329, "s": 316, "text": "Using stream" }, { "code": null, "e": 343, "s": 329, "text": "Using union()" }, { "code": null, "e": 375, "s": 343, "text": "Method 1: Using addAll() method" }, { "code": null, "e": 383, "s": 375, "text": "Syntax:" }, { "code": null, "e": 405, "s": 383, "text": "addAll ( list name ) " }, { "code": null, "e": 536, "s": 405, "text": "This method takes name of list as argument and add all the elements of the specified list in the same order as the original list. " }, { "code": null, "e": 581, "s": 536, "text": "Create a new empty list ( concatenated_list)" }, { "code": null, "e": 672, "s": 581, "text": "Use addAll () method to concatenate the given list1 and list2 into the newly created list." }, { "code": null, "e": 733, "s": 672, "text": "concatenated_list.addAll (list1) // concatenates first list " }, { "code": null, "e": 795, "s": 733, "text": "concatenated_list.addAll (list2) // concatenates second list " }, { "code": null, "e": 871, "s": 795, "text": "After performing the above steps our empty list now contains both the list." }, { "code": null, "e": 876, "s": 871, "text": "Java" }, { "code": "// Java Program to Concatenate Two List// using addAll() method import java.io.*;import java.util.ArrayList;import java.util.List; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using addAll( ) method to concatenate the lists concatenated_list.addAll(list1); concatenated_list.addAll(list2); System.out.println(\"list1: \" + list1); System.out.println(\"list2: \" + list2); System.out.println(\"Concatenated list: \" + concatenated_list); }}", "e": 1859, "s": 876, "text": null }, { "code": null, "e": 1943, "s": 1859, "text": "list1: [1, 2, 3, 4]\nlist2: [5, 6, 7, 8]\nConcatenated list: [1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 1967, "s": 1943, "text": "Method 2: Using streams" }, { "code": null, "e": 2041, "s": 1967, "text": "Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList())" }, { "code": null, "e": 2164, "s": 2041, "text": "It takes two streams as argument and creates a concatenated stream out of them.Second list is appended to the first list. " }, { "code": null, "e": 2169, "s": 2164, "text": "Java" }, { "code": "// Java Program to Concatenate Two List // using streams import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using Stream.concat() method to concatenate the lists concatenated_list = Stream.concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); System.out.println(\"list1: \" + list1); System.out.println(\"list2: \" + list2); System.out.println(\"Concatenated list: \"+ concatenated_list); }}", "e": 3228, "s": 2169, "text": null }, { "code": null, "e": 3312, "s": 3228, "text": "list1: [1, 2, 3, 4]\nlist2: [5, 6, 7, 8]\nConcatenated list: [1, 2, 3, 4, 5, 6, 7, 8]" }, { "code": null, "e": 3337, "s": 3312, "text": "Method 3: Using union() " }, { "code": null, "e": 3369, "s": 3337, "text": "ListUtils.union( list1, list2) " }, { "code": null, "e": 3478, "s": 3369, "text": " It takes two list as argument and return new concatenated list. Second list is appended to the first list. " }, { "code": null, "e": 3483, "s": 3478, "text": "Java" }, { "code": "// Java program to concatenate two lists// using union() import java.io.*;import java.util.*;import java.lang.*;import org.apache.commons.collections.ListUtils; public class GFG { public static void main(String[] args) { // given list 1 List<Integer> list1 = new ArrayList<Integer>(); list1.add(1); list1.add(2); list1.add(3); list1.add(4); // given list 2 List<Integer> list2 = new ArrayList<Integer>(); list2.add(5); list2.add(6); list2.add(7); list2.add(8); // creating new empty list List<Integer> concatenated_list = new ArrayList<Integer>(); // using ListUtils.union() method to concatenate // the lists concatenated_list = ListUtils.union(list1, list2); System.out.println(\"list1: \" + list1); System.out.println(\"list2: \" + list2); System.out.println(\"Concatenated list: \" + concatenated_list); }}", "e": 4475, "s": 3483, "text": null }, { "code": null, "e": 4483, "s": 4475, "text": "Output:" }, { "code": null, "e": 4525, "s": 4483, "text": "Prerequisites for running the above code:" }, { "code": null, "e": 4673, "s": 4525, "text": "Download and Install the following Apache Commons Collections library http://commons.apache.org/proper/commons-collections/download_collections.cgi" }, { "code": null, "e": 4715, "s": 4673, "text": "Now go to the properties of your project." }, { "code": null, "e": 4739, "s": 4715, "text": "Select Java Build Path." }, { "code": null, "e": 4778, "s": 4739, "text": "Under Java Build Path go to libraries." }, { "code": null, "e": 4812, "s": 4778, "text": "Under libraries select Classpath." }, { "code": null, "e": 4905, "s": 4812, "text": "Now go to add external JARs and add the JAR executable file, downloaded from the given link." }, { "code": null, "e": 4922, "s": 4905, "text": "Java-Collections" }, { "code": null, "e": 4932, "s": 4922, "text": "java-list" }, { "code": null, "e": 4939, "s": 4932, "text": "Picked" }, { "code": null, "e": 4944, "s": 4939, "text": "Java" }, { "code": null, "e": 4958, "s": 4944, "text": "Java Programs" }, { "code": null, "e": 4963, "s": 4958, "text": "Java" }, { "code": null, "e": 4980, "s": 4963, "text": "Java-Collections" } ]
scp command in Linux with Examples
27 May, 2019 scp (secure copy) command in Linux system is used to copy file(s) between servers in a secure way. The SCP command or secure copy allows secure transferring of files in between the local host and the remote host or between two remote hosts. It uses the same authentication and security as it is used in the Secure Shell (SSH) protocol. SCP is known for its simplicity, security and pre-installed availability. Syntax: scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 ... [[user@]host2:]file2 Options: scp –P port: Specifies the port to connect on the remote host. scp –p: Preserves modification times, access times, and modes from the original file. scp –q: Disables the progress meter. scp –r: Recursively copy entire directories. scp –S program: Name of program to use for the encrypted connection. The program must understand ssh(1) options. scp –v: Verbose mode. Causes scp and ssh to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. Examples: Copying file without the “-C” parameter will result in 1671.3 second delay. You may compare the result to the command below which is using the “-C” parameter.As you can see, whenever you are using compression, the transfer process is being done in 172.5 seconds. It is 10 times faster than not using the “-C” parameter. If you are copying a lot of files across the network, “-C” parameter would definitely be going to help you to decrease the total time you need. As you can see, whenever you are using compression, the transfer process is being done in 172.5 seconds. It is 10 times faster than not using the “-C” parameter. If you are copying a lot of files across the network, “-C” parameter would definitely be going to help you to decrease the total time you need. Select another cipher as to encrypt files: By default, SCP is using the “AES-128” to encrypt files. If you want to change to any another cipher to encrypt it, you can use that by using “-c” parameter. To specify a specific port to use with SCP: Usually, SCP is using port 22 as a default port. But for security reason, you can change the port into another port. For example, we are going to use port 2249. Then the command needs to be like this.scp -P 2249 Label.pdf mrarianto@202.x.x.x:.Sample Output:As you can see, after you enter the password, there is no information about the SCP process. After the process is complete, you will see a prompt again. If you want the detailed information of the SCP process, then -v parameter helps you out.scp -v Label.pdf mrarianto@202.x.x.x:.Sample Output: scp -P 2249 Label.pdf mrarianto@202.x.x.x:. Sample Output: As you can see, after you enter the password, there is no information about the SCP process. After the process is complete, you will see a prompt again. If you want the detailed information of the SCP process, then -v parameter helps you out. scp -v Label.pdf mrarianto@202.x.x.x:. Sample Output: Limiting bandwidth usage: Another parameter that may be proven useful is “-l” parameter. The “-l” parameter will limit the total bandwidth to use. It will be useful if you made an automation script to copy a lot of files, but you don’t want the bandwidth to be drained by the SCP process.scp -l 400 Label.pdf mrarianto@202.x.x.x:.Sample Output:If you want to provide modification times, access times, and modes from original files then “-p” parameter will help you on this. Estimated time and the connection speed will be going to appear on the screen.scp -p Label.pdf mrarianto@202.x.x.x:.Sample Output: scp -l 400 Label.pdf mrarianto@202.x.x.x:. Sample Output: If you want to provide modification times, access times, and modes from original files then “-p” parameter will help you on this. Estimated time and the connection speed will be going to appear on the screen. scp -p Label.pdf mrarianto@202.x.x.x:. Sample Output: linux-command Linux-misc-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples 'crontab' in Linux with Examples Tail command in Linux with examples Docker - COPY Instruction UDP Server-Client implementation in C Cat command in Linux with examples echo command in Linux with Examples diff command in Linux with examples touch command in Linux with Examples
[ { "code": null, "e": 53, "s": 25, "text": "\n27 May, 2019" }, { "code": null, "e": 463, "s": 53, "text": "scp (secure copy) command in Linux system is used to copy file(s) between servers in a secure way. The SCP command or secure copy allows secure transferring of files in between the local host and the remote host or between two remote hosts. It uses the same authentication and security as it is used in the Secure Shell (SSH) protocol. SCP is known for its simplicity, security and pre-installed availability." }, { "code": null, "e": 471, "s": 463, "text": "Syntax:" }, { "code": null, "e": 632, "s": 471, "text": "scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 ... [[user@]host2:]file2" }, { "code": null, "e": 641, "s": 632, "text": "Options:" }, { "code": null, "e": 704, "s": 641, "text": "scp –P port: Specifies the port to connect on the remote host." }, { "code": null, "e": 790, "s": 704, "text": "scp –p: Preserves modification times, access times, and modes from the original file." }, { "code": null, "e": 827, "s": 790, "text": "scp –q: Disables the progress meter." }, { "code": null, "e": 872, "s": 827, "text": "scp –r: Recursively copy entire directories." }, { "code": null, "e": 985, "s": 872, "text": "scp –S program: Name of program to use for the encrypted connection. The program must understand ssh(1) options." }, { "code": null, "e": 1161, "s": 985, "text": "scp –v: Verbose mode. Causes scp and ssh to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems." }, { "code": null, "e": 1171, "s": 1161, "text": "Examples:" }, { "code": null, "e": 1635, "s": 1171, "text": "Copying file without the “-C” parameter will result in 1671.3 second delay. You may compare the result to the command below which is using the “-C” parameter.As you can see, whenever you are using compression, the transfer process is being done in 172.5 seconds. It is 10 times faster than not using the “-C” parameter. If you are copying a lot of files across the network, “-C” parameter would definitely be going to help you to decrease the total time you need." }, { "code": null, "e": 1941, "s": 1635, "text": "As you can see, whenever you are using compression, the transfer process is being done in 172.5 seconds. It is 10 times faster than not using the “-C” parameter. If you are copying a lot of files across the network, “-C” parameter would definitely be going to help you to decrease the total time you need." }, { "code": null, "e": 2142, "s": 1941, "text": "Select another cipher as to encrypt files: By default, SCP is using the “AES-128” to encrypt files. If you want to change to any another cipher to encrypt it, you can use that by using “-c” parameter." }, { "code": null, "e": 2738, "s": 2142, "text": "To specify a specific port to use with SCP: Usually, SCP is using port 22 as a default port. But for security reason, you can change the port into another port. For example, we are going to use port 2249. Then the command needs to be like this.scp -P 2249 Label.pdf mrarianto@202.x.x.x:.Sample Output:As you can see, after you enter the password, there is no information about the SCP process. After the process is complete, you will see a prompt again. If you want the detailed information of the SCP process, then -v parameter helps you out.scp -v Label.pdf mrarianto@202.x.x.x:.Sample Output:" }, { "code": null, "e": 2782, "s": 2738, "text": "scp -P 2249 Label.pdf mrarianto@202.x.x.x:." }, { "code": null, "e": 2797, "s": 2782, "text": "Sample Output:" }, { "code": null, "e": 3040, "s": 2797, "text": "As you can see, after you enter the password, there is no information about the SCP process. After the process is complete, you will see a prompt again. If you want the detailed information of the SCP process, then -v parameter helps you out." }, { "code": null, "e": 3079, "s": 3040, "text": "scp -v Label.pdf mrarianto@202.x.x.x:." }, { "code": null, "e": 3094, "s": 3079, "text": "Sample Output:" }, { "code": null, "e": 3699, "s": 3094, "text": "Limiting bandwidth usage: Another parameter that may be proven useful is “-l” parameter. The “-l” parameter will limit the total bandwidth to use. It will be useful if you made an automation script to copy a lot of files, but you don’t want the bandwidth to be drained by the SCP process.scp -l 400 Label.pdf mrarianto@202.x.x.x:.Sample Output:If you want to provide modification times, access times, and modes from original files then “-p” parameter will help you on this. Estimated time and the connection speed will be going to appear on the screen.scp -p Label.pdf mrarianto@202.x.x.x:.Sample Output:" }, { "code": null, "e": 3742, "s": 3699, "text": "scp -l 400 Label.pdf mrarianto@202.x.x.x:." }, { "code": null, "e": 3757, "s": 3742, "text": "Sample Output:" }, { "code": null, "e": 3966, "s": 3757, "text": "If you want to provide modification times, access times, and modes from original files then “-p” parameter will help you on this. Estimated time and the connection speed will be going to appear on the screen." }, { "code": null, "e": 4005, "s": 3966, "text": "scp -p Label.pdf mrarianto@202.x.x.x:." }, { "code": null, "e": 4020, "s": 4005, "text": "Sample Output:" }, { "code": null, "e": 4034, "s": 4020, "text": "linux-command" }, { "code": null, "e": 4054, "s": 4034, "text": "Linux-misc-commands" }, { "code": null, "e": 4065, "s": 4054, "text": "Linux-Unix" }, { "code": null, "e": 4163, "s": 4065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4198, "s": 4163, "text": "tar command in Linux with examples" }, { "code": null, "e": 4234, "s": 4198, "text": "curl command in Linux with Examples" }, { "code": null, "e": 4267, "s": 4234, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 4303, "s": 4267, "text": "Tail command in Linux with examples" }, { "code": null, "e": 4329, "s": 4303, "text": "Docker - COPY Instruction" }, { "code": null, "e": 4367, "s": 4329, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 4402, "s": 4367, "text": "Cat command in Linux with examples" }, { "code": null, "e": 4438, "s": 4402, "text": "echo command in Linux with Examples" }, { "code": null, "e": 4474, "s": 4438, "text": "diff command in Linux with examples" } ]
Python – Draw “GFG” logo using Turtle Graphics
13 Oct, 2020 Prerequisites: Turtle Programming in Python Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways. Some of the commonly used methods are: forward(length): moves the pen in the forward direction by x unit. backward(length): moves the pen in the backward direction by x unit. right(angle): rotate the pen in the clockwise direction by an angle x. left(angle): rotate the pen in the anticlockwise direction by an angle x. penup(): stop drawing of the turtle pen. pendown(): start drawing of the turtle pen. In this article, we will be drawing the logo of GeeksforGeeks which looks like this – Approach : Importing Turtle. Forming a window screen with size and color. Then start to draw the logo:Form ‘C’ in the backward directionline 90 degree upline 90 degree rightline 90 degree downForm ‘C’ in forwarding direction Form ‘C’ in the backward direction line 90 degree up line 90 degree right line 90 degree down Form ‘C’ in forwarding direction Below is the implementation. # importing turtle for graphics import turtle # Forming the window screen tut = turtle.Screen() # background color green tut.bgcolor("White") # object pen = turtle.Turtle() #speed of pen pen.speed(10) # object color pen.color("Green") # object width pen.width(10) tut = turtle.Screen() # Code for symbol # backward C for x in range(180): pen.forward(1) pen.right(1) # up pen.right(90) pen.forward(50) # right pen.right(90) pen.forward(130) # down pen.right(90) pen.forward(50) pen.left(90) # forward C for x in range(180): pen.backward(1) pen.right(1) turtle.done() Output : pulkitagarwal03pulkit Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Oct, 2020" }, { "code": null, "e": 98, "s": 54, "text": "Prerequisites: Turtle Programming in Python" }, { "code": null, "e": 386, "s": 98, "text": "Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes into the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways." }, { "code": null, "e": 425, "s": 386, "text": "Some of the commonly used methods are:" }, { "code": null, "e": 492, "s": 425, "text": "forward(length): moves the pen in the forward direction by x unit." }, { "code": null, "e": 561, "s": 492, "text": "backward(length): moves the pen in the backward direction by x unit." }, { "code": null, "e": 632, "s": 561, "text": "right(angle): rotate the pen in the clockwise direction by an angle x." }, { "code": null, "e": 706, "s": 632, "text": "left(angle): rotate the pen in the anticlockwise direction by an angle x." }, { "code": null, "e": 747, "s": 706, "text": "penup(): stop drawing of the turtle pen." }, { "code": null, "e": 791, "s": 747, "text": "pendown(): start drawing of the turtle pen." }, { "code": null, "e": 879, "s": 791, "text": "In this article, we will be drawing the logo of GeeksforGeeks which looks like this – " }, { "code": null, "e": 892, "s": 881, "text": "Approach :" }, { "code": null, "e": 912, "s": 894, "text": "Importing Turtle." }, { "code": null, "e": 957, "s": 912, "text": "Forming a window screen with size and color." }, { "code": null, "e": 1108, "s": 957, "text": "Then start to draw the logo:Form ‘C’ in the backward directionline 90 degree upline 90 degree rightline 90 degree downForm ‘C’ in forwarding direction" }, { "code": null, "e": 1143, "s": 1108, "text": "Form ‘C’ in the backward direction" }, { "code": null, "e": 1161, "s": 1143, "text": "line 90 degree up" }, { "code": null, "e": 1182, "s": 1161, "text": "line 90 degree right" }, { "code": null, "e": 1202, "s": 1182, "text": "line 90 degree down" }, { "code": null, "e": 1235, "s": 1202, "text": "Form ‘C’ in forwarding direction" }, { "code": null, "e": 1266, "s": 1237, "text": "Below is the implementation." }, { "code": null, "e": 1863, "s": 1268, "text": "# importing turtle for graphics\nimport turtle\n\n# Forming the window screen\ntut = turtle.Screen()\n\n# background color green\ntut.bgcolor(\"White\")\n\n# object\npen = turtle.Turtle()\n\n#speed of pen\npen.speed(10)\n\n# object color\npen.color(\"Green\")\n\n# object width\npen.width(10)\ntut = turtle.Screen()\n\n\n# Code for symbol\n# backward C\nfor x in range(180):\n pen.forward(1)\n pen.right(1)\n\n# up\npen.right(90)\npen.forward(50)\n\n# right\npen.right(90)\npen.forward(130)\n\n# down\npen.right(90)\npen.forward(50)\npen.left(90)\n\n# forward C\nfor x in range(180):\n pen.backward(1)\n pen.right(1)\n\nturtle.done()" }, { "code": null, "e": 1874, "s": 1863, "text": " Output : " }, { "code": null, "e": 1898, "s": 1876, "text": "pulkitagarwal03pulkit" }, { "code": null, "e": 1912, "s": 1898, "text": "Python-turtle" }, { "code": null, "e": 1919, "s": 1912, "text": "Python" } ]
Maximum Sum SubArray using Divide and Conquer | Set 2
10 Nov, 2021 Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 Approach: Till now we are only aware of Kadane’s Algorithm which solves this problem in O(n) using dynamic programming. We had also discussed a divide and conquer approach for maximum sum subarray in O(N*logN) time complexity.The following approach solves it using Divide and Conquer approach which takes the same time complexity of O(n).Divide and conquer algorithms generally involves dividing the problem into sub-problems and conquering them separately. For this problem we maintain a structure (in cpp) or class(in java or python) which stores the following values: Total sum for a sub-array.Maximum prefix sum for a sub-array.Maximum suffix sum for a sub-array.Overall maximum sum for a sub-array.(This contains the max sum for a sub-array). Total sum for a sub-array. Maximum prefix sum for a sub-array. Maximum suffix sum for a sub-array. Overall maximum sum for a sub-array.(This contains the max sum for a sub-array). During the recursion(Divide part) the array is divided into 2 parts from the middle. The left node structure contains all the above values for the left part of array and the right node structure contains all the above values. Having both the nodes, now we can merge the two nodes by computing all the values for resulting node. The max prefix sum for the resulting node will be maximum value among the maximum prefix sum of left node or left node sum + max prefix sum of right node or total sum of both the nodes (which is possible for an array with all positive values). Similarly the max suffix sum for the resulting node will be maximum value among the maximum suffix sum of right node or right node sum + max suffix sum of left node or total sum of both the nodes (which is again possible for an array with all positive values). The total sum for the resulting node is the sum of both left node and right node sum. Now, the max subarray sum for the resulting node will be maximum among prefix sum of resulting node, suffix sum of resulting node, total sum of resulting node, maximum sum of left node, maximum sum of right node, sum of maximum suffix sum of left node and maximum prefix sum of right node. Here the conquer part can be done in O(1) time by combining the result from the left and right node structures.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; struct Node { // To store the maximum sum // for a sub-array long long _max; // To store the maximum prefix // sum for a sub-array long long _pre; // To store the maximum suffix // sum for a sub-array long long _suf; // To store the total sum // for a sub-array long long _sum; }; // Function to create a nodeNode getNode(long long x){ Node a; a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightNode merg(const Node &l, const Node &r){ // Creating node ans Node ans ; // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = max({l._pre, l._sum+r._pre, l._sum+r._sum}); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = max({r._suf, r._sum+l._suf, l._sum+r._sum}); // Total sum of ans Node = total sum of left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = max({ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre}); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerNode getMaxSumSubArray(int l, int r, vector<long long> &ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid+1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codeint main(){ vector<long long> ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.size(); Node ans = getMaxSumSubArray(0, n-1, ar); cout << "Answer is " << ans._max << "\n"; return 0;} // Java implementation of the approachimport java.util.*;class GFG{static class Node{ // To store the maximum sum // for a sub-array int _max; // To store the maximum prefix // sum for a sub-array int _pre; // To store the maximum suffix // sum for a sub-array int _suf; // To store the total sum // for a sub-array int _sum; }; // Function to create a nodestatic Node getNode(int x){ Node a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightstatic Node merg(Node l, Node r){ // Creating node ans Node ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = Arrays.stream(new int[]{l._pre, l._sum+r._pre, l._sum+r._sum}).max().getAsInt(); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = Arrays.stream(new int[]{r._suf, r._sum+l._suf, l._sum+r._sum}).max().getAsInt(); // Total sum of ans Node = total sum of // left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores // the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = Arrays.stream(new int[]{ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre}).max().getAsInt(); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerstatic Node getMaxSumSubArray(int l, int r, int []ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid + 1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codepublic static void main(String[] args){ int []ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.length; Node ans = getMaxSumSubArray(0, n - 1, ar); System.out.print("Answer is " + ans._max + "\n");}} // This code is contributed by shikhasingrajput # Python3 implementation of the approach class Node: def __init__(self, x): # To store the maximum sum for a sub-array self._max = x # To store the maximum prefix sum for a sub-array self._pre = x # To store the maximum suffix sum for a sub-array self._suf = x # To store the total sum for a sub-array self._sum = x # Function to merge the 2 nodes left and rightdef merg(l, r): # Creating node ans ans = Node(0) # The max prefix sum of ans Node is maximum of # a) max prefix sum of left Node # b) sum of left Node + max prefix sum of right Node # c) sum of left Node + sum of right Node ans._pre = max(l._pre, l._sum+r._pre, l._sum+r._sum) # The max suffix sum of ans Node is maximum of # a) max suffix sum of right Node # b) sum of right Node + max suffix sum of left Node # c) sum of left Node + sum of right Node ans._suf = max(r._suf, r._sum+l._suf, l._sum+r._sum) # Total sum of ans Node = total sum of # left Node + total sum of right Node ans._sum = l._sum + r._sum # The max sum of ans Node stores the answer # which is the maximum value among: # prefix sum of ans Node # suffix sum of ans Node # maximum value of left Node # maximum value of right Node # prefix value of left Node + suffix value of right Node ans._max = max(ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre) # Return the ans Node return ans # Function for calculating the# max_sum_subArray using divide and conquerdef getMaxSumSubArray(l, r, ar): if l == r: return Node(ar[l]) mid = (l + r) // 2 # Call method to return left Node: left = getMaxSumSubArray(l, mid, ar) # Call method to return right Node: right = getMaxSumSubArray(mid+1, r, ar) # Return the merged Node: return merg(left, right) # Driver codeif __name__ == "__main__": ar = [-2, -5, 6, -2, -3, 1, 5, -6] n = len(ar) ans = getMaxSumSubArray(0, n-1, ar) print("Answer is", ans._max) # This code is contributed by Rituraj Jain // C# implementation of the approachusing System;using System.Linq;public class GFG{ class Node{ // To store the maximum sum // for a sub-array public int _max; // To store the maximum prefix // sum for a sub-array public int _pre; // To store the maximum suffix // sum for a sub-array public int _suf; // To store the total sum // for a sub-array public int _sum;}; // Function to create a nodestatic Node getNode(int x){ Node a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightstatic Node merg(Node l, Node r){ // Creating node ans Node ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = (new int[]{l._pre, l._sum+r._pre, l._sum+r._sum}).Max(); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = (new int[]{r._suf, r._sum+l._suf, l._sum+r._sum}).Max(); // Total sum of ans Node = total sum of // left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores // the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = (new int[]{ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre}).Max(); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerstatic Node getMaxSumSubArray(int l, int r, int []ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid + 1, r, ar); // Return the merged Node: return merg(left, right);} // Driver codepublic static void Main(String[] args){ int []ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.Length; Node ans = getMaxSumSubArray(0, n - 1, ar); Console.Write("Answer is " + ans._max + "\n");}} // This code is contributed by shikhasingrajput <script> // Javascript implementation of the approachclass Node { constructor() { // To store the maximum sum // for a sub-array var _max; // To store the maximum prefix // sum for a sub-array var _pre; // To store the maximum suffix // sum for a sub-array var _suf; // To store the total sum // for a sub-array var _sum; } }; // Function to create a nodefunction getNode(x){ var a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightfunction merg(l, r){ // Creating node ans var ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = Math.max(l._pre, l._sum+r._pre, l._sum+r._sum); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = Math.max(r._suf, r._sum+l._suf, l._sum+r._sum); // Total sum of ans Node = total sum of left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = Math.max(ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerfunction getMaxSumSubArray(l, r, ar){ if (l == r) return getNode(ar[l]); var mid = (l + r) >> 1; // Call method to return left Node: var left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: var right = getMaxSumSubArray(mid+1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codevar ar = [-2, -5, 6, -2, -3, 1, 5, -6];var n = ar.length;var ans = getMaxSumSubArray(0, n-1, ar);document.write("Answer is " + ans._max + "<br>"); // This code is contributed by rutvik_56.</script> Output: Answer is 7 Time Complexity: The getMaxSumSubArray() recursive function generates the following recurrence relation. T(n) = 2 * T(n / 2) + O(1) note that conquer part takes only O(1) time. So on solving this recurrence using Master’s Theorem we get the time complexity of O(n). rituraj_jain Akanksha_Rai hitshob469 shikhasingrajput rutvik_56 subarray subarray-sum Arrays Divide and Conquer Arrays Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Merge Sort QuickSort Binary Search Maximum and minimum of an array using minimum number of comparisons Count Inversions in an array | Set 1 (Using Merge Sort)
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Nov, 2021" }, { "code": null, "e": 178, "s": 52, "text": "Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: " }, { "code": null, "e": 313, "s": 178, "text": "Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 " }, { "code": null, "e": 888, "s": 315, "text": "Approach: Till now we are only aware of Kadane’s Algorithm which solves this problem in O(n) using dynamic programming. We had also discussed a divide and conquer approach for maximum sum subarray in O(N*logN) time complexity.The following approach solves it using Divide and Conquer approach which takes the same time complexity of O(n).Divide and conquer algorithms generally involves dividing the problem into sub-problems and conquering them separately. For this problem we maintain a structure (in cpp) or class(in java or python) which stores the following values: " }, { "code": null, "e": 1065, "s": 888, "text": "Total sum for a sub-array.Maximum prefix sum for a sub-array.Maximum suffix sum for a sub-array.Overall maximum sum for a sub-array.(This contains the max sum for a sub-array)." }, { "code": null, "e": 1092, "s": 1065, "text": "Total sum for a sub-array." }, { "code": null, "e": 1128, "s": 1092, "text": "Maximum prefix sum for a sub-array." }, { "code": null, "e": 1164, "s": 1128, "text": "Maximum suffix sum for a sub-array." }, { "code": null, "e": 1245, "s": 1164, "text": "Overall maximum sum for a sub-array.(This contains the max sum for a sub-array)." }, { "code": null, "e": 2617, "s": 1245, "text": "During the recursion(Divide part) the array is divided into 2 parts from the middle. The left node structure contains all the above values for the left part of array and the right node structure contains all the above values. Having both the nodes, now we can merge the two nodes by computing all the values for resulting node. The max prefix sum for the resulting node will be maximum value among the maximum prefix sum of left node or left node sum + max prefix sum of right node or total sum of both the nodes (which is possible for an array with all positive values). Similarly the max suffix sum for the resulting node will be maximum value among the maximum suffix sum of right node or right node sum + max suffix sum of left node or total sum of both the nodes (which is again possible for an array with all positive values). The total sum for the resulting node is the sum of both left node and right node sum. Now, the max subarray sum for the resulting node will be maximum among prefix sum of resulting node, suffix sum of resulting node, total sum of resulting node, maximum sum of left node, maximum sum of right node, sum of maximum suffix sum of left node and maximum prefix sum of right node. Here the conquer part can be done in O(1) time by combining the result from the left and right node structures.Below is the implementation of the above approach: " }, { "code": null, "e": 2621, "s": 2617, "text": "C++" }, { "code": null, "e": 2626, "s": 2621, "text": "Java" }, { "code": null, "e": 2634, "s": 2626, "text": "Python3" }, { "code": null, "e": 2637, "s": 2634, "text": "C#" }, { "code": null, "e": 2648, "s": 2637, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; struct Node { // To store the maximum sum // for a sub-array long long _max; // To store the maximum prefix // sum for a sub-array long long _pre; // To store the maximum suffix // sum for a sub-array long long _suf; // To store the total sum // for a sub-array long long _sum; }; // Function to create a nodeNode getNode(long long x){ Node a; a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightNode merg(const Node &l, const Node &r){ // Creating node ans Node ans ; // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = max({l._pre, l._sum+r._pre, l._sum+r._sum}); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = max({r._suf, r._sum+l._suf, l._sum+r._sum}); // Total sum of ans Node = total sum of left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = max({ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre}); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerNode getMaxSumSubArray(int l, int r, vector<long long> &ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid+1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codeint main(){ vector<long long> ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.size(); Node ans = getMaxSumSubArray(0, n-1, ar); cout << \"Answer is \" << ans._max << \"\\n\"; return 0;}", "e": 5110, "s": 2648, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{static class Node{ // To store the maximum sum // for a sub-array int _max; // To store the maximum prefix // sum for a sub-array int _pre; // To store the maximum suffix // sum for a sub-array int _suf; // To store the total sum // for a sub-array int _sum; }; // Function to create a nodestatic Node getNode(int x){ Node a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightstatic Node merg(Node l, Node r){ // Creating node ans Node ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = Arrays.stream(new int[]{l._pre, l._sum+r._pre, l._sum+r._sum}).max().getAsInt(); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = Arrays.stream(new int[]{r._suf, r._sum+l._suf, l._sum+r._sum}).max().getAsInt(); // Total sum of ans Node = total sum of // left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores // the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = Arrays.stream(new int[]{ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre}).max().getAsInt(); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerstatic Node getMaxSumSubArray(int l, int r, int []ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid + 1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codepublic static void main(String[] args){ int []ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.length; Node ans = getMaxSumSubArray(0, n - 1, ar); System.out.print(\"Answer is \" + ans._max + \"\\n\");}} // This code is contributed by shikhasingrajput", "e": 7961, "s": 5110, "text": null }, { "code": "# Python3 implementation of the approach class Node: def __init__(self, x): # To store the maximum sum for a sub-array self._max = x # To store the maximum prefix sum for a sub-array self._pre = x # To store the maximum suffix sum for a sub-array self._suf = x # To store the total sum for a sub-array self._sum = x # Function to merge the 2 nodes left and rightdef merg(l, r): # Creating node ans ans = Node(0) # The max prefix sum of ans Node is maximum of # a) max prefix sum of left Node # b) sum of left Node + max prefix sum of right Node # c) sum of left Node + sum of right Node ans._pre = max(l._pre, l._sum+r._pre, l._sum+r._sum) # The max suffix sum of ans Node is maximum of # a) max suffix sum of right Node # b) sum of right Node + max suffix sum of left Node # c) sum of left Node + sum of right Node ans._suf = max(r._suf, r._sum+l._suf, l._sum+r._sum) # Total sum of ans Node = total sum of # left Node + total sum of right Node ans._sum = l._sum + r._sum # The max sum of ans Node stores the answer # which is the maximum value among: # prefix sum of ans Node # suffix sum of ans Node # maximum value of left Node # maximum value of right Node # prefix value of left Node + suffix value of right Node ans._max = max(ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre) # Return the ans Node return ans # Function for calculating the# max_sum_subArray using divide and conquerdef getMaxSumSubArray(l, r, ar): if l == r: return Node(ar[l]) mid = (l + r) // 2 # Call method to return left Node: left = getMaxSumSubArray(l, mid, ar) # Call method to return right Node: right = getMaxSumSubArray(mid+1, r, ar) # Return the merged Node: return merg(left, right) # Driver codeif __name__ == \"__main__\": ar = [-2, -5, 6, -2, -3, 1, 5, -6] n = len(ar) ans = getMaxSumSubArray(0, n-1, ar) print(\"Answer is\", ans._max) # This code is contributed by Rituraj Jain", "e": 10112, "s": 7961, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Linq;public class GFG{ class Node{ // To store the maximum sum // for a sub-array public int _max; // To store the maximum prefix // sum for a sub-array public int _pre; // To store the maximum suffix // sum for a sub-array public int _suf; // To store the total sum // for a sub-array public int _sum;}; // Function to create a nodestatic Node getNode(int x){ Node a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightstatic Node merg(Node l, Node r){ // Creating node ans Node ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = (new int[]{l._pre, l._sum+r._pre, l._sum+r._sum}).Max(); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = (new int[]{r._suf, r._sum+l._suf, l._sum+r._sum}).Max(); // Total sum of ans Node = total sum of // left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores // the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = (new int[]{ans._pre, ans._suf, ans._sum, l._max, r._max, l._suf+r._pre}).Max(); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerstatic Node getMaxSumSubArray(int l, int r, int []ar){ if (l == r) return getNode(ar[l]); int mid = (l + r) >> 1; // Call method to return left Node: Node left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: Node right = getMaxSumSubArray(mid + 1, r, ar); // Return the merged Node: return merg(left, right);} // Driver codepublic static void Main(String[] args){ int []ar = {-2, -5, 6, -2, -3, 1, 5, -6}; int n = ar.Length; Node ans = getMaxSumSubArray(0, n - 1, ar); Console.Write(\"Answer is \" + ans._max + \"\\n\");}} // This code is contributed by shikhasingrajput", "e": 12925, "s": 10112, "text": null }, { "code": "<script> // Javascript implementation of the approachclass Node { constructor() { // To store the maximum sum // for a sub-array var _max; // To store the maximum prefix // sum for a sub-array var _pre; // To store the maximum suffix // sum for a sub-array var _suf; // To store the total sum // for a sub-array var _sum; } }; // Function to create a nodefunction getNode(x){ var a = new Node(); a._max = x; a._pre = x; a._suf = x; a._sum = x; return a;} // Function to merge the 2 nodes left and rightfunction merg(l, r){ // Creating node ans var ans = new Node(); // Initializing all the variables: ans._max = ans._pre = ans._suf = ans._sum = 0; // The max prefix sum of ans Node is maximum of // a) max prefix sum of left Node // b) sum of left Node + max prefix sum of right Node // c) sum of left Node + sum of right Node ans._pre = Math.max(l._pre, l._sum+r._pre, l._sum+r._sum); // The max suffix sum of ans Node is maximum of // a) max suffix sum of right Node // b) sum of right Node + max suffix sum of left Node // c) sum of left Node + sum of right Node ans._suf = Math.max(r._suf, r._sum+l._suf, l._sum+r._sum); // Total sum of ans Node = total sum of left Node + total sum of right Node ans._sum = l._sum + r._sum; // The max sum of ans Node stores the answer which is the maximum value among: // prefix sum of ans Node // suffix sum of ans Node // maximum value of left Node // maximum value of right Node // prefix value of right Node + suffix value of left Node ans._max = Math.max(ans._pre, ans._suf, ans._sum,l._max, r._max, l._suf+r._pre); // Return the ans Node return ans;} // Function for calculating the// max_sum_subArray using divide and conquerfunction getMaxSumSubArray(l, r, ar){ if (l == r) return getNode(ar[l]); var mid = (l + r) >> 1; // Call method to return left Node: var left = getMaxSumSubArray(l, mid, ar); // Call method to return right Node: var right = getMaxSumSubArray(mid+1, r, ar); // Return the merged Node: return merg(left, right); } // Driver codevar ar = [-2, -5, 6, -2, -3, 1, 5, -6];var n = ar.length;var ans = getMaxSumSubArray(0, n-1, ar);document.write(\"Answer is \" + ans._max + \"<br>\"); // This code is contributed by rutvik_56.</script>", "e": 15399, "s": 12925, "text": null }, { "code": null, "e": 15408, "s": 15399, "text": "Output: " }, { "code": null, "e": 15420, "s": 15408, "text": "Answer is 7" }, { "code": null, "e": 15687, "s": 15420, "text": "Time Complexity: The getMaxSumSubArray() recursive function generates the following recurrence relation. T(n) = 2 * T(n / 2) + O(1) note that conquer part takes only O(1) time. So on solving this recurrence using Master’s Theorem we get the time complexity of O(n). " }, { "code": null, "e": 15700, "s": 15687, "text": "rituraj_jain" }, { "code": null, "e": 15713, "s": 15700, "text": "Akanksha_Rai" }, { "code": null, "e": 15724, "s": 15713, "text": "hitshob469" }, { "code": null, "e": 15741, "s": 15724, "text": "shikhasingrajput" }, { "code": null, "e": 15751, "s": 15741, "text": "rutvik_56" }, { "code": null, "e": 15760, "s": 15751, "text": "subarray" }, { "code": null, "e": 15773, "s": 15760, "text": "subarray-sum" }, { "code": null, "e": 15780, "s": 15773, "text": "Arrays" }, { "code": null, "e": 15799, "s": 15780, "text": "Divide and Conquer" }, { "code": null, "e": 15806, "s": 15799, "text": "Arrays" }, { "code": null, "e": 15825, "s": 15806, "text": "Divide and Conquer" }, { "code": null, "e": 15923, "s": 15825, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15991, "s": 15923, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 16035, "s": 15991, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 16067, "s": 16035, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 16115, "s": 16067, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 16129, "s": 16115, "text": "Linear Search" }, { "code": null, "e": 16140, "s": 16129, "text": "Merge Sort" }, { "code": null, "e": 16150, "s": 16140, "text": "QuickSort" }, { "code": null, "e": 16164, "s": 16150, "text": "Binary Search" }, { "code": null, "e": 16232, "s": 16164, "text": "Maximum and minimum of an array using minimum number of comparisons" } ]
Fibonacci Series in Bash
20 May, 2022 Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples: Input : 5 Output : Fibonacci Series is : 0 1 1 2 3 Input :4 Output : Fibonacci Series is : 0 1 1 2 The Fibonacci numbers are the numbers in the following integer sequence . 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ Approach As we know F0 = 0 and F1 = 1 and the next value comes by adding the previous two values . FN = FN-1 + FN-2 Loop to Nth number adding previous two numbers. BASH # Program for Fibonacci# Series # Static input for NN=6 # First Number of the# Fibonacci Seriesa=0 # Second Number of the# Fibonacci Seriesb=1 echo "The Fibonacci series is : " for (( i=0; i<N; i++ ))do echo -n "$a " fn=$((a + b)) a=$b b=$fndone# End of for loop Output: Fibonacci Series is : 0 1 1 2 3 5 8 varshagumber28 simmytarika5 Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2022" }, { "code": null, "e": 169, "s": 52, "text": "Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples:" }, { "code": null, "e": 271, "s": 169, "text": "Input : 5\nOutput :\nFibonacci Series is : \n0\n1\n1\n2\n3\n\nInput :4\nOutput :\nFibonacci Series is : \n0\n1\n1\n2" }, { "code": null, "e": 345, "s": 271, "text": "The Fibonacci numbers are the numbers in the following integer sequence ." }, { "code": null, "e": 400, "s": 345, "text": "0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........" }, { "code": null, "e": 499, "s": 400, "text": "Approach As we know F0 = 0 and F1 = 1 and the next value comes by adding the previous two values ." }, { "code": null, "e": 519, "s": 499, "text": " FN = FN-1 + FN-2" }, { "code": null, "e": 568, "s": 519, "text": "Loop to Nth number adding previous two numbers. " }, { "code": null, "e": 573, "s": 568, "text": "BASH" }, { "code": "# Program for Fibonacci# Series # Static input for NN=6 # First Number of the# Fibonacci Seriesa=0 # Second Number of the# Fibonacci Seriesb=1 echo \"The Fibonacci series is : \" for (( i=0; i<N; i++ ))do echo -n \"$a \" fn=$((a + b)) a=$b b=$fndone# End of for loop", "e": 851, "s": 573, "text": null }, { "code": null, "e": 859, "s": 851, "text": "Output:" }, { "code": null, "e": 896, "s": 859, "text": "Fibonacci Series is : \n0\n1\n1\n2\n3\n5\n8" }, { "code": null, "e": 911, "s": 896, "text": "varshagumber28" }, { "code": null, "e": 924, "s": 911, "text": "simmytarika5" }, { "code": null, "e": 937, "s": 924, "text": "Shell Script" }, { "code": null, "e": 948, "s": 937, "text": "Linux-Unix" } ]
HTML | <tbody> align Attribute
22 Feb, 2022 The HTML <tbody> align Attribute is used to set the horizontal alignment of text content inside the table body (tbody). Syntax: <tbody align="left | right | center | justify | char"> Attribute Value: left: It sets the text left-align. right: It sets the text right-align. center: It sets the text center-align. By default, it is set to center. justify: It stretches the text of paragraph to set the width of all lines equal. char: It sets the text-align to a specific character. Note: The <tbody> align Attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title> HTML tbody align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML tbody align Attribute</h2> <table border="1" width="500"> <thead> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> </thead> <tbody align="center"> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </tbody> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <tbody> align Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS HTTP headers | Content-Type How to Insert Form Data into Database using PHP ? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2022" }, { "code": null, "e": 148, "s": 28, "text": "The HTML <tbody> align Attribute is used to set the horizontal alignment of text content inside the table body (tbody)." }, { "code": null, "e": 156, "s": 148, "text": "Syntax:" }, { "code": null, "e": 211, "s": 156, "text": "<tbody align=\"left | right | center | justify | char\">" }, { "code": null, "e": 228, "s": 211, "text": "Attribute Value:" }, { "code": null, "e": 263, "s": 228, "text": "left: It sets the text left-align." }, { "code": null, "e": 300, "s": 263, "text": "right: It sets the text right-align." }, { "code": null, "e": 372, "s": 300, "text": "center: It sets the text center-align. By default, it is set to center." }, { "code": null, "e": 453, "s": 372, "text": "justify: It stretches the text of paragraph to set the width of all lines equal." }, { "code": null, "e": 507, "s": 453, "text": "char: It sets the text-align to a specific character." }, { "code": null, "e": 569, "s": 507, "text": "Note: The <tbody> align Attribute is not supported by HTML 5." }, { "code": null, "e": 578, "s": 569, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML tbody align Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML tbody align Attribute</h2> <table border=\"1\" width=\"500\"> <thead> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> </thead> <tbody align=\"center\"> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> </tbody> </table></body> </html>", "e": 1140, "s": 578, "text": null }, { "code": null, "e": 1148, "s": 1140, "text": "Output:" }, { "code": null, "e": 1240, "s": 1148, "text": "Supported Browsers: The browser supported by HTML <tbody> align Attribute are listed below:" }, { "code": null, "e": 1254, "s": 1240, "text": "Google Chrome" }, { "code": null, "e": 1272, "s": 1254, "text": "Internet Explorer" }, { "code": null, "e": 1280, "s": 1272, "text": "Firefox" }, { "code": null, "e": 1287, "s": 1280, "text": "Safari" }, { "code": null, "e": 1293, "s": 1287, "text": "Opera" }, { "code": null, "e": 1313, "s": 1293, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1329, "s": 1313, "text": "HTML-Attributes" }, { "code": null, "e": 1334, "s": 1329, "text": "HTML" }, { "code": null, "e": 1351, "s": 1334, "text": "Web Technologies" }, { "code": null, "e": 1356, "s": 1351, "text": "HTML" }, { "code": null, "e": 1454, "s": 1356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1478, "s": 1454, "text": "REST API (Introduction)" }, { "code": null, "e": 1515, "s": 1478, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1554, "s": 1515, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1582, "s": 1554, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1632, "s": 1582, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1665, "s": 1632, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1726, "s": 1665, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1769, "s": 1726, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1841, "s": 1769, "text": "Differences between Functional Components and Class Components in React" } ]
LEFT() Function in MySQL
24 Sep, 2021 LEFT() function in MySQL is used to extract a specified number of characters from the left side of a given string. It uses its second argument to decide, how many characters it should return. Syntax : LEFT (str, len) Parameter : This function accepts two parameters as mentioned above and described below : str : The given string from whose left side a number of characters are to be extracted. len : The number of characters to extract. If this parameter is larger than the number of characters in the string, this function will return the actual string. Returns : It returns a number of characters from a string (starting from left). Example-1 : Applying LEFT() Function to a given string. SELECT LEFT("geeksforgeeks", 4) AS Left_Str; Output : Example-2 : Applying Left() Function to a number. SELECT LEFT(12345678, 4) AS Left_Num; Output : Example-3 : Applying LEFT() Function to a given string when len > characters in the string. SELECT LEFT("geeksforgeeks", 20) AS Left_Str; Output : Example-4 : Applying LEFT() Function to a column in a table. Table : Student_Details SELECT Student_Name, LEFT(Student_Email, 9) AS Email_Name FROM Student_Details; Output : rajrishu784 DBMS-SQL mysql SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 221, "s": 28, "text": "LEFT() function in MySQL is used to extract a specified number of characters from the left side of a given string. It uses its second argument to decide, how many characters it should return. " }, { "code": null, "e": 232, "s": 221, "text": "Syntax : " }, { "code": null, "e": 248, "s": 232, "text": "LEFT (str, len)" }, { "code": null, "e": 339, "s": 248, "text": "Parameter : This function accepts two parameters as mentioned above and described below : " }, { "code": null, "e": 429, "s": 339, "text": "str : The given string from whose left side a number of characters are to be extracted. " }, { "code": null, "e": 592, "s": 429, "text": "len : The number of characters to extract. If this parameter is larger than the number of characters in the string, this function will return the actual string. " }, { "code": null, "e": 673, "s": 592, "text": "Returns : It returns a number of characters from a string (starting from left). " }, { "code": null, "e": 731, "s": 673, "text": "Example-1 : Applying LEFT() Function to a given string. " }, { "code": null, "e": 776, "s": 731, "text": "SELECT LEFT(\"geeksforgeeks\", 4) AS Left_Str;" }, { "code": null, "e": 786, "s": 776, "text": "Output : " }, { "code": null, "e": 838, "s": 786, "text": "Example-2 : Applying Left() Function to a number. " }, { "code": null, "e": 876, "s": 838, "text": "SELECT LEFT(12345678, 4) AS Left_Num;" }, { "code": null, "e": 886, "s": 876, "text": "Output : " }, { "code": null, "e": 980, "s": 886, "text": "Example-3 : Applying LEFT() Function to a given string when len > characters in the string. " }, { "code": null, "e": 1026, "s": 980, "text": "SELECT LEFT(\"geeksforgeeks\", 20) AS Left_Str;" }, { "code": null, "e": 1036, "s": 1026, "text": "Output : " }, { "code": null, "e": 1098, "s": 1036, "text": "Example-4 : Applying LEFT() Function to a column in a table. " }, { "code": null, "e": 1123, "s": 1098, "text": "Table : Student_Details " }, { "code": null, "e": 1204, "s": 1123, "text": "SELECT Student_Name, LEFT(Student_Email, 9) AS Email_Name \nFROM Student_Details;" }, { "code": null, "e": 1214, "s": 1204, "text": "Output : " }, { "code": null, "e": 1226, "s": 1214, "text": "rajrishu784" }, { "code": null, "e": 1235, "s": 1226, "text": "DBMS-SQL" }, { "code": null, "e": 1241, "s": 1235, "text": "mysql" }, { "code": null, "e": 1245, "s": 1241, "text": "SQL" }, { "code": null, "e": 1249, "s": 1245, "text": "SQL" } ]
How to get the next page on BeautifulSoup?
16 May, 2021 In this article, we are going to see how to Get the next page on beautifulsoup. BeautifulSoup: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. To install this module type the below command in the terminal. pip install bs4 requests: This library allows you to send HTTP/1.1 requests extremely easily. To install this module type the below command in the terminal. pip install requests Approach: Get the next page on beautifulsoup means first we will scrap one-page content and if many links are given on the page, and we want to scrap them also. We can get the next page first we will scrap the sample website after that any other links find, and we will call again requests. Get method for that page and will create a soup of that also. So this way we can get to the next page on beautifulsoup. Let’s execute the script step-by-step : Step 1: Import all dependence from bs4 import BeautifulSoup import requests Step 2: We need to request the page URL with requests. page=requests.get(sample_website) Step 3: With the help of beautifulsoup method and HTML parser we will create a soup of the page. soup = BeautifulSoup(page, 'html.parser') Step 4: We will search in the parse tree and find the link. If we want that URL, then with the help of the requests module and beautiful module we will again create the soup of the next page hence we can get the next page on beautifulsoup. Python3 for i in soup.find_all('a', href = True): # check all link which is contain # "www.geeksforgeeks.org" string if("www.geeksforgeeks.org" in i['href']): # call get method to request next url nextpage = requests.get(i['href']) # create soup for next url nextsoup = BeautifulSoup(nextpage.content, 'html.parser') # we can scrap any thing of the # next page here we are scraping title of # nexturl page string print("next url title : ",nextsoup.find('title').string) Below is the full Implementation: Python3 from bs4 import BeautifulSoupimport requests # sample websitesample_website='https://www.geeksforgeeks.org/different-ways-to-remove-all-the-digits-from-string-in-java/' # call get method to request the pagepage=requests.get(sample_website) # with the help of BeautifulSoup# method and html parser created soupsoup = BeautifulSoup(page.content, 'html.parser') # With the help of find_all# method perform searching in parser treefor i in soup.find_all('a', href = True): # check all link which is contain # "www.geeksforgeeks.org" string if("www.geeksforgeeks.org" in i['href']): # call get method to request next url nextpage = requests.get(i['href']) # create soup for next url nextsoup = BeautifulSoup(nextpage.content, 'html.parser') # we can scrap any thing of the # next page here we are scraping title of # nexturl page string print("next url title : ",nextsoup.find('title').string) Output: next url title : GeeksforGeeks | A computer science portal for geeks next url title : Analysis of Algorithms | Set 1 (Asymptotic Analysis) - GeeksforGeeks next url title : Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) - GeeksforGeeks next url title : Analysis of Algorithms | Set 3 (Asymptotic Notations) - GeeksforGeeks next url title : Analysis of algorithms | little o and little omega notations - GeeksforGeeks next url title : Lower and Upper Bound Theory - GeeksforGeeks next url title : Analysis of Algorithms | Set 4 (Analysis of Loops) - GeeksforGeeks next url title : Analysis of Algorithm | Set 4 (Solving Recurrences) - GeeksforGeeks next url title : Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) - GeeksforGeeks next url title : What does 'Space Complexity' mean? - GeeksforGeeks next url title : Pseudo-polynomial Algorithms - GeeksforGeeks next url title : Polynomial Time Approximation Scheme - GeeksforGeeks next url title : A Time Complexity Question - GeeksforGeeks ................................................................. Picked Python BeautifulSoup Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2021" }, { "code": null, "e": 108, "s": 28, "text": "In this article, we are going to see how to Get the next page on beautifulsoup." }, { "code": null, "e": 270, "s": 108, "text": "BeautifulSoup: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. To install this module type the below command in the terminal." }, { "code": null, "e": 286, "s": 270, "text": "pip install bs4" }, { "code": null, "e": 427, "s": 286, "text": "requests: This library allows you to send HTTP/1.1 requests extremely easily. To install this module type the below command in the terminal." }, { "code": null, "e": 448, "s": 427, "text": "pip install requests" }, { "code": null, "e": 458, "s": 448, "text": "Approach:" }, { "code": null, "e": 859, "s": 458, "text": "Get the next page on beautifulsoup means first we will scrap one-page content and if many links are given on the page, and we want to scrap them also. We can get the next page first we will scrap the sample website after that any other links find, and we will call again requests. Get method for that page and will create a soup of that also. So this way we can get to the next page on beautifulsoup." }, { "code": null, "e": 899, "s": 859, "text": "Let’s execute the script step-by-step :" }, { "code": null, "e": 929, "s": 899, "text": "Step 1: Import all dependence" }, { "code": null, "e": 975, "s": 929, "text": "from bs4 import BeautifulSoup\nimport requests" }, { "code": null, "e": 1030, "s": 975, "text": "Step 2: We need to request the page URL with requests." }, { "code": null, "e": 1064, "s": 1030, "text": "page=requests.get(sample_website)" }, { "code": null, "e": 1161, "s": 1064, "text": "Step 3: With the help of beautifulsoup method and HTML parser we will create a soup of the page." }, { "code": null, "e": 1203, "s": 1161, "text": "soup = BeautifulSoup(page, 'html.parser')" }, { "code": null, "e": 1211, "s": 1203, "text": "Step 4:" }, { "code": null, "e": 1443, "s": 1211, "text": "We will search in the parse tree and find the link. If we want that URL, then with the help of the requests module and beautiful module we will again create the soup of the next page hence we can get the next page on beautifulsoup." }, { "code": null, "e": 1451, "s": 1443, "text": "Python3" }, { "code": "for i in soup.find_all('a', href = True): # check all link which is contain # \"www.geeksforgeeks.org\" string if(\"www.geeksforgeeks.org\" in i['href']): # call get method to request next url nextpage = requests.get(i['href']) # create soup for next url nextsoup = BeautifulSoup(nextpage.content, 'html.parser') # we can scrap any thing of the # next page here we are scraping title of # nexturl page string print(\"next url title : \",nextsoup.find('title').string)", "e": 1964, "s": 1451, "text": null }, { "code": null, "e": 1998, "s": 1964, "text": "Below is the full Implementation:" }, { "code": null, "e": 2006, "s": 1998, "text": "Python3" }, { "code": "from bs4 import BeautifulSoupimport requests # sample websitesample_website='https://www.geeksforgeeks.org/different-ways-to-remove-all-the-digits-from-string-in-java/' # call get method to request the pagepage=requests.get(sample_website) # with the help of BeautifulSoup# method and html parser created soupsoup = BeautifulSoup(page.content, 'html.parser') # With the help of find_all# method perform searching in parser treefor i in soup.find_all('a', href = True): # check all link which is contain # \"www.geeksforgeeks.org\" string if(\"www.geeksforgeeks.org\" in i['href']): # call get method to request next url nextpage = requests.get(i['href']) # create soup for next url nextsoup = BeautifulSoup(nextpage.content, 'html.parser') # we can scrap any thing of the # next page here we are scraping title of # nexturl page string print(\"next url title : \",nextsoup.find('title').string)", "e": 2950, "s": 2006, "text": null }, { "code": null, "e": 2958, "s": 2950, "text": "Output:" }, { "code": null, "e": 4058, "s": 2958, "text": "next url title : GeeksforGeeks | A computer science portal for geeks\nnext url title : Analysis of Algorithms | Set 1 (Asymptotic Analysis) - GeeksforGeeks\nnext url title : Analysis of Algorithms | Set 2 (Worst, Average and Best Cases) - GeeksforGeeks\nnext url title : Analysis of Algorithms | Set 3 (Asymptotic Notations) - GeeksforGeeks\nnext url title : Analysis of algorithms | little o and little omega notations - GeeksforGeeks\nnext url title : Lower and Upper Bound Theory - GeeksforGeeks\nnext url title : Analysis of Algorithms | Set 4 (Analysis of Loops) - GeeksforGeeks\nnext url title : Analysis of Algorithm | Set 4 (Solving Recurrences) - GeeksforGeeks\nnext url title : Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) - GeeksforGeeks\nnext url title : What does 'Space Complexity' mean? - GeeksforGeeks\nnext url title : Pseudo-polynomial Algorithms - GeeksforGeeks\nnext url title : Polynomial Time Approximation Scheme - GeeksforGeeks\nnext url title : A Time Complexity Question - GeeksforGeeks\n................................................................. " }, { "code": null, "e": 4065, "s": 4058, "text": "Picked" }, { "code": null, "e": 4086, "s": 4065, "text": "Python BeautifulSoup" }, { "code": null, "e": 4093, "s": 4086, "text": "Python" }, { "code": null, "e": 4191, "s": 4093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4223, "s": 4191, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4250, "s": 4223, "text": "Python Classes and Objects" }, { "code": null, "e": 4271, "s": 4250, "text": "Python OOPs Concepts" }, { "code": null, "e": 4294, "s": 4271, "text": "Introduction To PYTHON" }, { "code": null, "e": 4350, "s": 4294, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4381, "s": 4350, "text": "Python | os.path.join() method" }, { "code": null, "e": 4423, "s": 4381, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4465, "s": 4423, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4504, "s": 4465, "text": "Python | Get unique values from a list" } ]
How to use multiple attribute in HTML?
The multiple attribute in HTML allows user to enter more than one value. It is a Boolean attribute and can be used on <input> as well as <select> element, To allow multiple file uploads in HTML forms, use the multiple attribute. The multiple attribute works with email and file input types. You can try to run the following code to learn how to use multiple attribute in HTML: <!DOCTYPE html> <html> <head> <title>HTML multiple attribute</title> </head> <body> <form> <input type="file" name="name" multiple><br><br> Upload multiple files, and click Submit.<br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1342, "s": 1187, "text": "The multiple attribute in HTML allows user to enter more than one value. It is a Boolean attribute and can be used on <input> as well as <select> element," }, { "code": null, "e": 1478, "s": 1342, "text": "To allow multiple file uploads in HTML forms, use the multiple attribute. The multiple attribute works with email and file input types." }, { "code": null, "e": 1564, "s": 1478, "text": "You can try to run the following code to learn how to use multiple attribute in HTML:" }, { "code": null, "e": 1867, "s": 1564, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML multiple attribute</title>\n </head>\n <body>\n <form>\n <input type=\"file\" name=\"name\" multiple><br><br>\n Upload multiple files, and click Submit.<br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
Unit Testing of Node.js Application
29 Jul, 2020 Node.js is a widely used javascript library based on Chrome’s V8 JavaScript engine for developing server-side applications in web development. Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of code in an application. Unit testing is generally carried out by developers during the development phase of an application. In Node.js there are many frameworks available for running unit tests. Some of them are: Mocha Jest Jasmine AVA Unit testing for a node application using these frameworks: Mocha: Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.To install it, open command prompt and type the following command:# Installs globally npm install mocha -g # installs in the current directory npm install mocha --save-dev How to use Mocha?In order to use this framework in your application:Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block."scripts": { "test": "mocha --recursive --exit" }Example:// Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe("Simple Calculations", () => { before(() => { console.log( "This part executes once before all tests" ); }); after(() => { console.log( "This part executes once after all tests" ); }); // We can add nested blocks for different tests describe( "Test1", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 5 when adding 2 + 3", () => { assert.equal(2 + 3, 5); }); it("Is returning 6 when multiplying 2 * 3", () => { assert.equal(2*3, 6); }); }); describe("Test2", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 4 when adding 2 + 3", () => { assert.equal(2 + 3, 4); }); it("Is returning 8 when multiplying 2 * 4", () => { assert.equal(2*4, 8); }); });});Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:npm run testOutput:What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.To install it, open the command prompt in the root directory of the project and type the following command:npm install chaiExample:const expect = require('chai').expect; describe("Testing with chai", () => { it("Is returning 4 when adding 2 + 2", () => { expect(2 + 2).to.equal(4); }); it("Is returning boolean value as true", () => { expect(5 == 5).to.be.true; }); it("Are both the sentences matching", () => { expect("This is working").to.equal('This is working'); }); });Output:Jest: Jest is also a popular testing framework that is known for its simplicity. It is developed and maintained regularly by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.You can install it using the following command:npm install --save-dev jestNote: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder.Example:describe("Testing with Jest", () => { test("Addition", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });});Output:Jasmine: Jasmine is also a powerful testing framework and has been around since 2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript code. It is known for its compatibility and flexibility with other testing frameworks like Sinon and Chai. Here test files must have a specific suffix (*spec.js).You can install it using the following command:npm install jasmine-nodeExample:describe("Test", function() { it("Addition", function() { var sum = 2 + 3; expect(sum).toEqual(5); });});AVA: AVA is a relatively new minimalistic framework that allows you to run your JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and parallel processing which makes it relatively fast compared to other frameworks. The key features include having no implicit globals and built-in support for asynchronous functions.You can install it using the following command:npm init avaExample:import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);}); Mocha: Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.To install it, open command prompt and type the following command:# Installs globally npm install mocha -g # installs in the current directory npm install mocha --save-dev How to use Mocha?In order to use this framework in your application:Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block."scripts": { "test": "mocha --recursive --exit" }Example:// Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe("Simple Calculations", () => { before(() => { console.log( "This part executes once before all tests" ); }); after(() => { console.log( "This part executes once after all tests" ); }); // We can add nested blocks for different tests describe( "Test1", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 5 when adding 2 + 3", () => { assert.equal(2 + 3, 5); }); it("Is returning 6 when multiplying 2 * 3", () => { assert.equal(2*3, 6); }); }); describe("Test2", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 4 when adding 2 + 3", () => { assert.equal(2 + 3, 4); }); it("Is returning 8 when multiplying 2 * 4", () => { assert.equal(2*4, 8); }); });});Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:npm run testOutput:What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.To install it, open the command prompt in the root directory of the project and type the following command:npm install chaiExample:const expect = require('chai').expect; describe("Testing with chai", () => { it("Is returning 4 when adding 2 + 2", () => { expect(2 + 2).to.equal(4); }); it("Is returning boolean value as true", () => { expect(5 == 5).to.be.true; }); it("Are both the sentences matching", () => { expect("This is working").to.equal('This is working'); }); });Output: To install it, open command prompt and type the following command: # Installs globally npm install mocha -g # installs in the current directory npm install mocha --save-dev How to use Mocha?In order to use this framework in your application: Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block."scripts": { "test": "mocha --recursive --exit" } Open the root folder of your project and create a new folder called test in it. Inside the test folder, create a new file called test.js which will contain all the code related to testing. open package.json and add the following line in the scripts block."scripts": { "test": "mocha --recursive --exit" } "scripts": { "test": "mocha --recursive --exit" } Example: // Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe("Simple Calculations", () => { before(() => { console.log( "This part executes once before all tests" ); }); after(() => { console.log( "This part executes once after all tests" ); }); // We can add nested blocks for different tests describe( "Test1", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 5 when adding 2 + 3", () => { assert.equal(2 + 3, 5); }); it("Is returning 6 when multiplying 2 * 3", () => { assert.equal(2*3, 6); }); }); describe("Test2", () => { beforeEach(() => { console.log( "executes before every test" ); }); it("Is returning 4 when adding 2 + 3", () => { assert.equal(2 + 3, 4); }); it("Is returning 8 when multiplying 2 * 4", () => { assert.equal(2*4, 8); }); });}); Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command: npm run test Output: What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences. To install it, open the command prompt in the root directory of the project and type the following command: npm install chai Example: const expect = require('chai').expect; describe("Testing with chai", () => { it("Is returning 4 when adding 2 + 2", () => { expect(2 + 2).to.equal(4); }); it("Is returning boolean value as true", () => { expect(5 == 5).to.be.true; }); it("Are both the sentences matching", () => { expect("This is working").to.equal('This is working'); }); }); Output: Jest: Jest is also a popular testing framework that is known for its simplicity. It is developed and maintained regularly by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.You can install it using the following command:npm install --save-dev jestNote: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder.Example:describe("Testing with Jest", () => { test("Addition", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });});Output: You can install it using the following command: npm install --save-dev jest Note: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder. Example: describe("Testing with Jest", () => { test("Addition", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });}); Output: Jasmine: Jasmine is also a powerful testing framework and has been around since 2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript code. It is known for its compatibility and flexibility with other testing frameworks like Sinon and Chai. Here test files must have a specific suffix (*spec.js).You can install it using the following command:npm install jasmine-nodeExample:describe("Test", function() { it("Addition", function() { var sum = 2 + 3; expect(sum).toEqual(5); });}); You can install it using the following command: npm install jasmine-node Example: describe("Test", function() { it("Addition", function() { var sum = 2 + 3; expect(sum).toEqual(5); });}); AVA: AVA is a relatively new minimalistic framework that allows you to run your JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and parallel processing which makes it relatively fast compared to other frameworks. The key features include having no implicit globals and built-in support for asynchronous functions.You can install it using the following command:npm init avaExample:import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);}); You can install it using the following command: npm init ava Example: import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);}); Node.js-Misc Picked JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ?
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jul, 2020" }, { "code": null, "e": 197, "s": 54, "text": "Node.js is a widely used javascript library based on Chrome’s V8 JavaScript engine for developing server-side applications in web development." }, { "code": null, "e": 479, "s": 197, "text": "Unit Testing is a software testing method where individual units/components are tested in isolation. A unit can be described as the smallest testable part of code in an application. Unit testing is generally carried out by developers during the development phase of an application." }, { "code": null, "e": 568, "s": 479, "text": "In Node.js there are many frameworks available for running unit tests. Some of them are:" }, { "code": null, "e": 574, "s": 568, "text": "Mocha" }, { "code": null, "e": 579, "s": 574, "text": "Jest" }, { "code": null, "e": 587, "s": 579, "text": "Jasmine" }, { "code": null, "e": 591, "s": 587, "text": "AVA" }, { "code": null, "e": 651, "s": 591, "text": "Unit testing for a node application using these frameworks:" }, { "code": null, "e": 5509, "s": 651, "text": "Mocha: Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.To install it, open command prompt and type the following command:# Installs globally\nnpm install mocha -g\n\n# installs in the current directory\nnpm install mocha --save-dev\nHow to use Mocha?In order to use this framework in your application:Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block.\"scripts\": {\n\"test\": \"mocha --recursive --exit\"\n}Example:// Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe(\"Simple Calculations\", () => { before(() => { console.log( \"This part executes once before all tests\" ); }); after(() => { console.log( \"This part executes once after all tests\" ); }); // We can add nested blocks for different tests describe( \"Test1\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 5 when adding 2 + 3\", () => { assert.equal(2 + 3, 5); }); it(\"Is returning 6 when multiplying 2 * 3\", () => { assert.equal(2*3, 6); }); }); describe(\"Test2\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 4 when adding 2 + 3\", () => { assert.equal(2 + 3, 4); }); it(\"Is returning 8 when multiplying 2 * 4\", () => { assert.equal(2*4, 8); }); });});Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:npm run testOutput:What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.To install it, open the command prompt in the root directory of the project and type the following command:npm install chaiExample:const expect = require('chai').expect; describe(\"Testing with chai\", () => { it(\"Is returning 4 when adding 2 + 2\", () => { expect(2 + 2).to.equal(4); }); it(\"Is returning boolean value as true\", () => { expect(5 == 5).to.be.true; }); it(\"Are both the sentences matching\", () => { expect(\"This is working\").to.equal('This is working'); }); });Output:Jest: Jest is also a popular testing framework that is known for its simplicity. It is developed and maintained regularly by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.You can install it using the following command:npm install --save-dev jestNote: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder.Example:describe(\"Testing with Jest\", () => { test(\"Addition\", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });});Output:Jasmine: Jasmine is also a powerful testing framework and has been around since 2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript code. It is known for its compatibility and flexibility with other testing frameworks like Sinon and Chai. Here test files must have a specific suffix (*spec.js).You can install it using the following command:npm install jasmine-nodeExample:describe(\"Test\", function() { it(\"Addition\", function() { var sum = 2 + 3; expect(sum).toEqual(5); });});AVA: AVA is a relatively new minimalistic framework that allows you to run your JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and parallel processing which makes it relatively fast compared to other frameworks. The key features include having no implicit globals and built-in support for asynchronous functions.You can install it using the following command:npm init avaExample:import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);});" }, { "code": null, "e": 8400, "s": 5509, "text": "Mocha: Mocha is an old and widely used testing framework for node applications. It supports asynchronous operations like callbacks, promises, and async/await. It is a highly extensible and customizable framework that supports different assertions and mocking libraries.To install it, open command prompt and type the following command:# Installs globally\nnpm install mocha -g\n\n# installs in the current directory\nnpm install mocha --save-dev\nHow to use Mocha?In order to use this framework in your application:Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block.\"scripts\": {\n\"test\": \"mocha --recursive --exit\"\n}Example:// Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe(\"Simple Calculations\", () => { before(() => { console.log( \"This part executes once before all tests\" ); }); after(() => { console.log( \"This part executes once after all tests\" ); }); // We can add nested blocks for different tests describe( \"Test1\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 5 when adding 2 + 3\", () => { assert.equal(2 + 3, 5); }); it(\"Is returning 6 when multiplying 2 * 3\", () => { assert.equal(2*3, 6); }); }); describe(\"Test2\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 4 when adding 2 + 3\", () => { assert.equal(2 + 3, 4); }); it(\"Is returning 8 when multiplying 2 * 4\", () => { assert.equal(2*4, 8); }); });});Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:npm run testOutput:What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences.To install it, open the command prompt in the root directory of the project and type the following command:npm install chaiExample:const expect = require('chai').expect; describe(\"Testing with chai\", () => { it(\"Is returning 4 when adding 2 + 2\", () => { expect(2 + 2).to.equal(4); }); it(\"Is returning boolean value as true\", () => { expect(5 == 5).to.be.true; }); it(\"Are both the sentences matching\", () => { expect(\"This is working\").to.equal('This is working'); }); });Output:" }, { "code": null, "e": 8467, "s": 8400, "text": "To install it, open command prompt and type the following command:" }, { "code": null, "e": 8575, "s": 8467, "text": "# Installs globally\nnpm install mocha -g\n\n# installs in the current directory\nnpm install mocha --save-dev\n" }, { "code": null, "e": 8644, "s": 8575, "text": "How to use Mocha?In order to use this framework in your application:" }, { "code": null, "e": 8947, "s": 8644, "text": "Open the root folder of your project and create a new folder called test in it.Inside the test folder, create a new file called test.js which will contain all the code related to testing.open package.json and add the following line in the scripts block.\"scripts\": {\n\"test\": \"mocha --recursive --exit\"\n}" }, { "code": null, "e": 9027, "s": 8947, "text": "Open the root folder of your project and create a new folder called test in it." }, { "code": null, "e": 9136, "s": 9027, "text": "Inside the test folder, create a new file called test.js which will contain all the code related to testing." }, { "code": null, "e": 9252, "s": 9136, "text": "open package.json and add the following line in the scripts block.\"scripts\": {\n\"test\": \"mocha --recursive --exit\"\n}" }, { "code": null, "e": 9302, "s": 9252, "text": "\"scripts\": {\n\"test\": \"mocha --recursive --exit\"\n}" }, { "code": null, "e": 9311, "s": 9302, "text": "Example:" }, { "code": "// Requiring moduleconst assert = require('assert'); // We can group similar tests inside a describe blockdescribe(\"Simple Calculations\", () => { before(() => { console.log( \"This part executes once before all tests\" ); }); after(() => { console.log( \"This part executes once after all tests\" ); }); // We can add nested blocks for different tests describe( \"Test1\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 5 when adding 2 + 3\", () => { assert.equal(2 + 3, 5); }); it(\"Is returning 6 when multiplying 2 * 3\", () => { assert.equal(2*3, 6); }); }); describe(\"Test2\", () => { beforeEach(() => { console.log( \"executes before every test\" ); }); it(\"Is returning 4 when adding 2 + 3\", () => { assert.equal(2 + 3, 4); }); it(\"Is returning 8 when multiplying 2 * 4\", () => { assert.equal(2*4, 8); }); });});", "e": 10273, "s": 9311, "text": null }, { "code": null, "e": 10468, "s": 10273, "text": "Copy the above code and paste it in the test.js file that we have created before. To run these tests, open the command prompt in the root directory of the project and type the following command:" }, { "code": null, "e": 10481, "s": 10468, "text": "npm run test" }, { "code": null, "e": 10489, "s": 10481, "text": "Output:" }, { "code": null, "e": 10863, "s": 10489, "text": "What is Chai?Chai is an assertion library that is often used alongside Mocha. It can be used as a TTD (Test Driven Development) / BDD (Behavior Driven Development) assertion library for Node.js that can be paired up with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, we can use Chai to write tests like English sentences." }, { "code": null, "e": 10971, "s": 10863, "text": "To install it, open the command prompt in the root directory of the project and type the following command:" }, { "code": null, "e": 10988, "s": 10971, "text": "npm install chai" }, { "code": null, "e": 10997, "s": 10988, "text": "Example:" }, { "code": "const expect = require('chai').expect; describe(\"Testing with chai\", () => { it(\"Is returning 4 when adding 2 + 2\", () => { expect(2 + 2).to.equal(4); }); it(\"Is returning boolean value as true\", () => { expect(5 == 5).to.be.true; }); it(\"Are both the sentences matching\", () => { expect(\"This is working\").to.equal('This is working'); }); });", "e": 11383, "s": 10997, "text": null }, { "code": null, "e": 11391, "s": 11383, "text": "Output:" }, { "code": null, "e": 12361, "s": 11391, "text": "Jest: Jest is also a popular testing framework that is known for its simplicity. It is developed and maintained regularly by Facebook. One of the key features of jest is it is well documented, and it supports parallel test running i.e. each test will run in their own processes to maximize performance. It also includes several features like test watching, coverage, and snapshots.You can install it using the following command:npm install --save-dev jestNote: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder.Example:describe(\"Testing with Jest\", () => { test(\"Addition\", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });});Output:" }, { "code": null, "e": 12409, "s": 12361, "text": "You can install it using the following command:" }, { "code": null, "e": 12437, "s": 12409, "text": "npm install --save-dev jest" }, { "code": null, "e": 12547, "s": 12437, "text": "Note: By default, Jest expects to find all the test files in a folder called “__tests__” in your root folder." }, { "code": null, "e": 12556, "s": 12547, "text": "Example:" }, { "code": "describe(\"Testing with Jest\", () => { test(\"Addition\", () => { const sum = 2 + 3; const expectedResult = 5; expect(sum).toEqual(expectedResult); }); // Jest also allows a test to run multiple // times using different values test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])( 'Does %i + %i equals %i', (a, b, expectedResult) => { expect(a + b).toBe(expectedResult); });});", "e": 12947, "s": 12556, "text": null }, { "code": null, "e": 12955, "s": 12947, "text": "Output:" }, { "code": null, "e": 13471, "s": 12955, "text": "Jasmine: Jasmine is also a powerful testing framework and has been around since 2010. It is a Behaviour Driven Development(BDD) framework for testing JavaScript code. It is known for its compatibility and flexibility with other testing frameworks like Sinon and Chai. Here test files must have a specific suffix (*spec.js).You can install it using the following command:npm install jasmine-nodeExample:describe(\"Test\", function() { it(\"Addition\", function() { var sum = 2 + 3; expect(sum).toEqual(5); });});" }, { "code": null, "e": 13519, "s": 13471, "text": "You can install it using the following command:" }, { "code": null, "e": 13544, "s": 13519, "text": "npm install jasmine-node" }, { "code": null, "e": 13553, "s": 13544, "text": "Example:" }, { "code": "describe(\"Test\", function() { it(\"Addition\", function() { var sum = 2 + 3; expect(sum).toEqual(5); });});", "e": 13667, "s": 13553, "text": null }, { "code": null, "e": 14151, "s": 13667, "text": "AVA: AVA is a relatively new minimalistic framework that allows you to run your JavaScript tests concurrently. Like the Jest framework, it also supports snapshots and parallel processing which makes it relatively fast compared to other frameworks. The key features include having no implicit globals and built-in support for asynchronous functions.You can install it using the following command:npm init avaExample:import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);});" }, { "code": null, "e": 14199, "s": 14151, "text": "You can install it using the following command:" }, { "code": null, "e": 14212, "s": 14199, "text": "npm init ava" }, { "code": null, "e": 14221, "s": 14212, "text": "Example:" }, { "code": "import test from 'ava'; test('Addition', t => { t.is(2 + 3, 5);});", "e": 14290, "s": 14221, "text": null }, { "code": null, "e": 14303, "s": 14290, "text": "Node.js-Misc" }, { "code": null, "e": 14310, "s": 14303, "text": "Picked" }, { "code": null, "e": 14321, "s": 14310, "text": "JavaScript" }, { "code": null, "e": 14329, "s": 14321, "text": "Node.js" }, { "code": null, "e": 14346, "s": 14329, "text": "Web Technologies" }, { "code": null, "e": 14444, "s": 14346, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14505, "s": 14444, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 14577, "s": 14505, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 14617, "s": 14577, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 14659, "s": 14617, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 14700, "s": 14659, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 14748, "s": 14700, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 14781, "s": 14748, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 14814, "s": 14781, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 14844, "s": 14814, "text": "Node.js fs.writeFile() Method" } ]
How to check an object is empty using JavaScript? - GeeksforGeeks
30 Apr, 2019 Method 1: Using the Object.keys(object) method: The required object could be passed to the Object.keys(object) method which will return the keys in the object. The length property is used to the result to check the number of keys. If the length property returns 0 keys, it means that the object is empty. Syntax: Object.keys(object).length === 0 Example: <!DOCTYPE html><html> <head> <title> How to check an object is empty using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check an object is empty using JavaScript? </b> <p> Click on the button to check if the object is empty </p> <p>Output for empty object: <span class="outputEmpty"></span> </p> <p>Output for non empty object: <span class="outputNonEmpty"></span> </p> <button onclick="checkObject()"> Click here </button> <!-- Script to check the object is empty or not --> <script type="text/javascript"> function checkObject() { let emptyObj = {} let nonEmptyObj = { title: 'Title 1', info: 'Sample Info' } ans1 = (Object.keys(emptyObj).length === 0) document.querySelector('.outputEmpty').textContent = ans1; ans2 = (Object.keys(nonEmptyObj).length === 0) document.querySelector('.outputNonEmpty').textContent = ans2; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Looping through the object using object.hasOwnProperty(key): A function is created where the object is looped over and checked if it contains the ‘key’ property using the object.hasOwnProperty() method. This function would return true if it could find no keys in the loop, which means that the object is empty. If any key is encountered, the loop breaks and false is returned. This method also works for older browsers that may not support the first method. Syntax: function isEmptyObj(object) { for (var key in object) { if (object.hasOwnProperty(key)) { return false; } } } Example: <!DOCTYPE html><html> <head> <title> How to check an object is empty using JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check an object is empty using JavaScript? </b> <p> on the button to check if the object is empty </p> <p> Output for empty object: <span class="outputEmpty"></span> </p> <p> Output for non empty object: <span class="outputNonEmpty"></span> </p> <button onclick="checkObject()"> Click here </button> <script type="text/javascript"> function checkObject() { let emptyObj = {} let nonEmptyObj = { title: 'Title 1', info: 'Sample Info' } ans1 = isEmptyObj(emptyObj); document.querySelector('.outputEmpty').textContent = ans1; ans2 = isEmptyObj(nonEmptyObj); document.querySelector('.outputNonEmpty').textContent = ans2; } function isEmptyObj(object) { for (var key in object) { if (object.hasOwnProperty(key)) { return false; } } return true; } </script></body> </html> Output: Before clicking the button: After clicking the button: jQuery-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request Angular File Upload How to get selected value in dropdown list using JavaScript ? How to remove duplicate elements from JavaScript Array ? Express.js express.Router() Function Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24909, "s": 24881, "text": "\n30 Apr, 2019" }, { "code": null, "e": 25214, "s": 24909, "text": "Method 1: Using the Object.keys(object) method: The required object could be passed to the Object.keys(object) method which will return the keys in the object. The length property is used to the result to check the number of keys. If the length property returns 0 keys, it means that the object is empty." }, { "code": null, "e": 25222, "s": 25214, "text": "Syntax:" }, { "code": null, "e": 25255, "s": 25222, "text": "Object.keys(object).length === 0" }, { "code": null, "e": 25264, "s": 25255, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to check an object is empty using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check an object is empty using JavaScript? </b> <p> Click on the button to check if the object is empty </p> <p>Output for empty object: <span class=\"outputEmpty\"></span> </p> <p>Output for non empty object: <span class=\"outputNonEmpty\"></span> </p> <button onclick=\"checkObject()\"> Click here </button> <!-- Script to check the object is empty or not --> <script type=\"text/javascript\"> function checkObject() { let emptyObj = {} let nonEmptyObj = { title: 'Title 1', info: 'Sample Info' } ans1 = (Object.keys(emptyObj).length === 0) document.querySelector('.outputEmpty').textContent = ans1; ans2 = (Object.keys(nonEmptyObj).length === 0) document.querySelector('.outputNonEmpty').textContent = ans2; } </script></body> </html> ", "e": 26521, "s": 25264, "text": null }, { "code": null, "e": 26529, "s": 26521, "text": "Output:" }, { "code": null, "e": 26557, "s": 26529, "text": "Before clicking the button:" }, { "code": null, "e": 26584, "s": 26557, "text": "After clicking the button:" }, { "code": null, "e": 27052, "s": 26584, "text": "Method 2: Looping through the object using object.hasOwnProperty(key): A function is created where the object is looped over and checked if it contains the ‘key’ property using the object.hasOwnProperty() method. This function would return true if it could find no keys in the loop, which means that the object is empty. If any key is encountered, the loop breaks and false is returned. This method also works for older browsers that may not support the first method." }, { "code": null, "e": 27060, "s": 27052, "text": "Syntax:" }, { "code": null, "e": 27207, "s": 27060, "text": "function isEmptyObj(object) {\n for (var key in object) {\n if (object.hasOwnProperty(key)) {\n return false;\n }\n }\n}\n" }, { "code": null, "e": 27216, "s": 27207, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to check an object is empty using JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check an object is empty using JavaScript? </b> <p> on the button to check if the object is empty </p> <p> Output for empty object: <span class=\"outputEmpty\"></span> </p> <p> Output for non empty object: <span class=\"outputNonEmpty\"></span> </p> <button onclick=\"checkObject()\"> Click here </button> <script type=\"text/javascript\"> function checkObject() { let emptyObj = {} let nonEmptyObj = { title: 'Title 1', info: 'Sample Info' } ans1 = isEmptyObj(emptyObj); document.querySelector('.outputEmpty').textContent = ans1; ans2 = isEmptyObj(nonEmptyObj); document.querySelector('.outputNonEmpty').textContent = ans2; } function isEmptyObj(object) { for (var key in object) { if (object.hasOwnProperty(key)) { return false; } } return true; } </script></body> </html>", "e": 28596, "s": 27216, "text": null }, { "code": null, "e": 28604, "s": 28596, "text": "Output:" }, { "code": null, "e": 28632, "s": 28604, "text": "Before clicking the button:" }, { "code": null, "e": 28659, "s": 28632, "text": "After clicking the button:" }, { "code": null, "e": 28671, "s": 28659, "text": "jQuery-Misc" }, { "code": null, "e": 28678, "s": 28671, "text": "Picked" }, { "code": null, "e": 28689, "s": 28678, "text": "JavaScript" }, { "code": null, "e": 28706, "s": 28689, "text": "Web Technologies" }, { "code": null, "e": 28733, "s": 28706, "text": "Web technologies Questions" }, { "code": null, "e": 28831, "s": 28733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28840, "s": 28831, "text": "Comments" }, { "code": null, "e": 28853, "s": 28840, "text": "Old Comments" }, { "code": null, "e": 28914, "s": 28853, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28955, "s": 28914, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28975, "s": 28955, "text": "Angular File Upload" }, { "code": null, "e": 29037, "s": 28975, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 29094, "s": 29037, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 29131, "s": 29094, "text": "Express.js express.Router() Function" }, { "code": null, "e": 29164, "s": 29131, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29226, "s": 29164, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29269, "s": 29226, "text": "How to fetch data from an API in ReactJS ?" } ]
ASP.NET WP - Charts
In this chapter, we will cover the chart helper and how to display data on charts. In the last chapter, we have displayed data on the WebGrid helper. Chart helper can be used to display data in a graphical format. The Chart helper can render an image that displays data in a variety of chart types. The Chart helper can render an image that displays data in a variety of chart types. It can also support different formatting and labeling options. It can also support different formatting and labeling options. It has the ability to render more than 30 types of charts in which you might have seen in Microsoft office, like area chart, bar chart column chart, etc. It has the ability to render more than 30 types of charts in which you might have seen in Microsoft office, like area chart, bar chart column chart, etc. Charts show data and additional elements like legends, axes, series, etc. Charts show data and additional elements like legends, axes, series, etc. The data you display in a chart can be from an array, from the results returned from a database, or from the data that's in an XML file. The data you display in a chart can be from an array, from the results returned from a database, or from the data that's in an XML file. Let’s have a look into a simple example in which we will display data on the charts. So first we need to create a new CSHTML file. Enter Charts.cshtml in the name field and click OK and then replace the following code in the Charts.cshtml file. @{ var myChart = new Chart(width: 600, height: 400) .AddTitle("Student Marks (%)") .AddSeries( name: "Student", xValue: new[] { "Allan", "Mark", "Ali", "Kerry", "Steve" }, yValues: new[] { "79", "53", "73", "81", "43" }) .Write(); } As you can see in the above code that first it will create a new chart and the set its width and height. var myChart = new Chart(width: 600, height: 400) You can specify the chart title by using the AddTitle method as shown in the following code. .AddTitle("Student Marks (%)") The AddSeries method can be used to add data and then assign the values to xValue, and yValues parameters of the AddSeries method. The name parameter is displayed in the chart legend. .AddSeries( name: "Student", xValue: new[] { "Allan", "Mark", "Ali", "Kerry", "Steve" }, yValues: new[] { "79", "53", "73", "81", "43" }) The xValue parameter contains an array of data that will be displayed along the horizontal axis of the chart, while the yValues parameter contains an array of data that will be used to plot the vertical points of the chart. The Write method actually renders the chart. In this case, because you didn't specify a chart type, the Chart helper renders its default chart, which is a column chart. Now let’s run your application and specify the following url − http://localhost:36905/charts and you will see the following web page. Now let’s have look into another example in which we will use the database query to retrieve the data and then that data will be displayed on the chart. So, first we need to add another Student table to our database as shown in the following screenshot. Now let’s add some data to the Students table as shown in the following screenshot. As you can see, now we have Students data. Now to display this data on the chart, let’s create a new CSHTML file. Enter ChartDataUsingDB.cshtml in the Name field and click OK and then replace all the code in ChartDataUsingDB.cshtml file. @{ var db = Database.Open("WebPagesCustomers"); var data = db.Query("SELECT FirstName, Marks FROM Students"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Student Marks") .DataBindTable(dataSource: data, xField: "FirstName") .Write(); } As you can see in the above code that first it will open WebPagesCustomers database and then assigns it to a variable named db. var db = Database.Open("WebPagesCustomers"); Next a simple SQL query is created which will retrieve the FirstName and Marks from the Students table. var data = db.Query("SELECT FirstName, Marks FROM Students"); Then a new chart is created and passes the database query to it by calling the chart's DataBindTable method. var myChart = new Chart(width: 600, height: 400) .AddTitle("Student Marks") .DataBindTable(dataSource: data, xField: "FirstName") .Write(); This method takes two parameters The dataSource parameter is for the data from the query. The dataSource parameter is for the data from the query. The xField parameter lets you set which data column is used for the chart's x-axis. The xField parameter lets you set which data column is used for the chart's x-axis. Now let’s run this application and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page. You can use the AddSeries method instead of DataBindTable and you can also specify the chart type parameter in the AddSeries method as shown in the following code. @{ var db = Database.Open("WebPagesCustomers"); var data = db.Query("SELECT FirstName, Marks FROM Students"); var myChart = new Chart(width: 600, height: 400) .AddTitle("Student Marks") .AddSeries("Default", chartType: "Pie", xValue: data, xField: "FirstName", yValues: data, yFields: "Marks") .Write(); } Now let’s run the application again and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page. You can also change the theme of the chart by simply specifying the theme parameter while creating a chart as explained in the following code. var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green) Now let’s run this application again and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2499, "s": 2285, "text": "In this chapter, we will cover the chart helper and how to display data on charts. In the last chapter, we have displayed data on the WebGrid helper. Chart helper can be used to display data in a graphical format." }, { "code": null, "e": 2584, "s": 2499, "text": "The Chart helper can render an image that displays data in a variety of chart types." }, { "code": null, "e": 2669, "s": 2584, "text": "The Chart helper can render an image that displays data in a variety of chart types." }, { "code": null, "e": 2732, "s": 2669, "text": "It can also support different formatting and labeling options." }, { "code": null, "e": 2795, "s": 2732, "text": "It can also support different formatting and labeling options." }, { "code": null, "e": 2949, "s": 2795, "text": "It has the ability to render more than 30 types of charts in which you might have seen in Microsoft office, like area chart, bar chart column chart, etc." }, { "code": null, "e": 3103, "s": 2949, "text": "It has the ability to render more than 30 types of charts in which you might have seen in Microsoft office, like area chart, bar chart column chart, etc." }, { "code": null, "e": 3177, "s": 3103, "text": "Charts show data and additional elements like legends, axes, series, etc." }, { "code": null, "e": 3251, "s": 3177, "text": "Charts show data and additional elements like legends, axes, series, etc." }, { "code": null, "e": 3388, "s": 3251, "text": "The data you display in a chart can be from an array, from the results returned from a database, or from the data that's in an XML file." }, { "code": null, "e": 3525, "s": 3388, "text": "The data you display in a chart can be from an array, from the results returned from a database, or from the data that's in an XML file." }, { "code": null, "e": 3656, "s": 3525, "text": "Let’s have a look into a simple example in which we will display data on the charts. So first we need to create a new CSHTML file." }, { "code": null, "e": 3770, "s": 3656, "text": "Enter Charts.cshtml in the name field and click OK and then replace the following code in the Charts.cshtml file." }, { "code": null, "e": 4033, "s": 3770, "text": "@{\n var myChart = new Chart(width: 600, height: 400)\n .AddTitle(\"Student Marks (%)\")\n .AddSeries(\n name: \"Student\",\n xValue: new[] { \"Allan\", \"Mark\", \"Ali\", \"Kerry\", \"Steve\" },\n yValues: new[] { \"79\", \"53\", \"73\", \"81\", \"43\" })\n .Write();\n}" }, { "code": null, "e": 4138, "s": 4033, "text": "As you can see in the above code that first it will create a new chart and the set its width and height." }, { "code": null, "e": 4188, "s": 4138, "text": "var myChart = new Chart(width: 600, height: 400)\n" }, { "code": null, "e": 4281, "s": 4188, "text": "You can specify the chart title by using the AddTitle method as shown in the following code." }, { "code": null, "e": 4313, "s": 4281, "text": ".AddTitle(\"Student Marks (%)\")\n" }, { "code": null, "e": 4497, "s": 4313, "text": "The AddSeries method can be used to add data and then assign the values to xValue, and yValues parameters of the AddSeries method. The name parameter is displayed in the chart legend." }, { "code": null, "e": 4644, "s": 4497, "text": ".AddSeries(\n name: \"Student\",\n xValue: new[] { \"Allan\", \"Mark\", \"Ali\", \"Kerry\", \"Steve\" },\n yValues: new[] { \"79\", \"53\", \"73\", \"81\", \"43\" })" }, { "code": null, "e": 4868, "s": 4644, "text": "The xValue parameter contains an array of data that will be displayed along the horizontal axis of the chart, while the yValues parameter contains an array of data that will be used to plot the vertical points of the chart." }, { "code": null, "e": 5037, "s": 4868, "text": "The Write method actually renders the chart. In this case, because you didn't specify a chart type, the Chart helper renders its default chart, which is a column chart." }, { "code": null, "e": 5171, "s": 5037, "text": "Now let’s run your application and specify the following url − http://localhost:36905/charts and you will see the following web page." }, { "code": null, "e": 5425, "s": 5171, "text": "Now let’s have look into another example in which we will use the database query to retrieve the data and then that data will be displayed on the chart. So, first we need to add another Student table to our database as shown in the following screenshot." }, { "code": null, "e": 5509, "s": 5425, "text": "Now let’s add some data to the Students table as shown in the following screenshot." }, { "code": null, "e": 5552, "s": 5509, "text": "As you can see, now we have Students data." }, { "code": null, "e": 5623, "s": 5552, "text": "Now to display this data on the chart, let’s create a new CSHTML file." }, { "code": null, "e": 5747, "s": 5623, "text": "Enter ChartDataUsingDB.cshtml in the Name field and click OK and then replace all the code in ChartDataUsingDB.cshtml file." }, { "code": null, "e": 6017, "s": 5747, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var data = db.Query(\"SELECT FirstName, Marks FROM Students\");\n var myChart = new Chart(width: 600, height: 400)\n .AddTitle(\"Student Marks\")\n .DataBindTable(dataSource: data, xField: \"FirstName\")\n .Write();\n}" }, { "code": null, "e": 6145, "s": 6017, "text": "As you can see in the above code that first it will open WebPagesCustomers database and then assigns it to a variable named db." }, { "code": null, "e": 6191, "s": 6145, "text": "var db = Database.Open(\"WebPagesCustomers\");\n" }, { "code": null, "e": 6295, "s": 6191, "text": "Next a simple SQL query is created which will retrieve the FirstName and Marks from the Students table." }, { "code": null, "e": 6358, "s": 6295, "text": "var data = db.Query(\"SELECT FirstName, Marks FROM Students\");\n" }, { "code": null, "e": 6467, "s": 6358, "text": "Then a new chart is created and passes the database query to it by calling the chart's DataBindTable method." }, { "code": null, "e": 6617, "s": 6467, "text": "var myChart = new Chart(width: 600, height: 400)\n .AddTitle(\"Student Marks\")\n .DataBindTable(dataSource: data, xField: \"FirstName\")\n .Write();\n" }, { "code": null, "e": 6650, "s": 6617, "text": "This method takes two parameters" }, { "code": null, "e": 6707, "s": 6650, "text": "The dataSource parameter is for the data from the query." }, { "code": null, "e": 6764, "s": 6707, "text": "The dataSource parameter is for the data from the query." }, { "code": null, "e": 6848, "s": 6764, "text": "The xField parameter lets you set which data column is used for the chart's x-axis." }, { "code": null, "e": 6932, "s": 6848, "text": "The xField parameter lets you set which data column is used for the chart's x-axis." }, { "code": null, "e": 7076, "s": 6932, "text": "Now let’s run this application and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page." }, { "code": null, "e": 7240, "s": 7076, "text": "You can use the AddSeries method instead of DataBindTable and you can also specify the chart type parameter in the AddSeries method as shown in the following code." }, { "code": null, "e": 7585, "s": 7240, "text": "@{\n var db = Database.Open(\"WebPagesCustomers\");\n var data = db.Query(\"SELECT FirstName, Marks FROM Students\");\n var myChart = new Chart(width: 600, height: 400)\n .AddTitle(\"Student Marks\")\n .AddSeries(\"Default\", chartType: \"Pie\",\n xValue: data, xField: \"FirstName\",\n yValues: data, yFields: \"Marks\")\n .Write();\n}" }, { "code": null, "e": 7734, "s": 7585, "text": "Now let’s run the application again and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page." }, { "code": null, "e": 7877, "s": 7734, "text": "You can also change the theme of the chart by simply specifying the theme parameter while creating a chart as explained in the following code." }, { "code": null, "e": 7952, "s": 7877, "text": "var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Green)\n" }, { "code": null, "e": 8102, "s": 7952, "text": "Now let’s run this application again and specify the following url − http://localhost:36905/ChartDataUsingDB and you will see the following web page." }, { "code": null, "e": 8137, "s": 8102, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8151, "s": 8137, "text": " Anadi Sharma" }, { "code": null, "e": 8186, "s": 8151, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8209, "s": 8186, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8243, "s": 8209, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8263, "s": 8243, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8298, "s": 8263, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8315, "s": 8298, "text": " University Code" }, { "code": null, "e": 8350, "s": 8315, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8367, "s": 8350, "text": " University Code" }, { "code": null, "e": 8401, "s": 8367, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 8416, "s": 8401, "text": " Bhrugen Patel" }, { "code": null, "e": 8423, "s": 8416, "text": " Print" }, { "code": null, "e": 8434, "s": 8423, "text": " Add Notes" } ]
Explain in detail about Reference-counting garbage collection in JavaScript?
This is the simplest garbage collection algorithm.This algorithm looks out for those objects which have no references left.An object becomes eligible for garbage collection if it has no references attached to it.The garbage collection is explained in the below example. var obj = { x: { y: 2 } }; // 2 objects created. One is referenced by the other as one of its properties. // Obviously, none can be garbage-collected obj = 1; // what was the 'x' property of the object originally in obj // has zero references to it. It can be garbage collected. When it comes to cycles there are limitations in Reference-counting garbage collection and it is explained in the below example. In the following example,two objects were created and referenced one another there by creating a cycle. After a function call they will go out of scope, so they are effectively useless and could be freed.But the reference-counting algorithm considers that since each of the two objects is referenced at least once, neither can be garbage-collected. function f() { var obj1 = {}; var obj2 = {}; obj1.p = obj2; // o1 references o2 obj2.p = obj1; // o2 references o1. This creates a cycle. } f();
[ { "code": null, "e": 1336, "s": 1062, "text": "This is the simplest garbage collection algorithm.This algorithm looks out for those objects which have no references left.An object becomes eligible for garbage collection if it has no references attached to it.The garbage collection is explained in the below example." }, { "code": null, "e": 1657, "s": 1336, "text": "var obj = {\n x: { y: 2 }\n };\n // 2 objects created. One is referenced by the other as one of its properties.\n // Obviously, none can be garbage-collected\nobj = 1; // what was the 'x' property of the object originally in obj\n // has zero references to it. It can be garbage collected." }, { "code": null, "e": 1786, "s": 1657, "text": "When it comes to cycles there are limitations in Reference-counting garbage collection and it is explained in the below example." }, { "code": null, "e": 2135, "s": 1786, "text": "In the following example,two objects were created and referenced one another there by creating a cycle. After a function call they will go out of scope, so they are effectively useless and could be freed.But the reference-counting algorithm considers that since each of the two objects is referenced at least once, neither can be garbage-collected." }, { "code": null, "e": 2280, "s": 2135, "text": "function f() {\nvar obj1 = {};\nvar obj2 = {};\nobj1.p = obj2; // o1 references o2\nobj2.p = obj1; // o2 references o1. This creates a cycle.\n}\nf();" } ]
Distinct Prime Factors of Array Product - GeeksforGeeks
14 May, 2021 Given an array of integers.Let us say P is the product of elements of the array. Find the number of distinct prime factors of product P. Examples: Input : 1 2 3 4 5 Output : 3 Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120 are 2, 3 and 5. So, the output is 3. Input : 21 30 15 24 16 Output : 4 Explanation: Here P = 21 * 30 * 15 * 24 * 16 = 3628800. Distinct prime divisors of 3628800 are 2, 3, 5 and 7. So, the output is 4. Naive Approach : The simple solution for the problem would be to multiply every number in the array an then find the number of distinct prime factors of the product. But this method can lead to integer overflow. Better Approach : To avoid the overflow instead of multiplying the numbers we can find the prime factors of each element separately and store the prime factors in a set or a map for unique factors. C++ Java Python3 C# Javascript // C++ program to count distinct prime// factors of a number.#include <bits/stdc++.h>using namespace std; // Function to count the number of distinct prime// factors of product of arrayint Distinct_Prime_factors(vector<int> a){ // use set to store distinct factors unordered_set<int> m; // iterate over every element of array for (int i = 0; i < a.size(); i++) { int sq = sqrt(a[i]); // from 2 to square root of number run // a loop and check the numbers which // are factors. for (int j = 2; j <= sq; j++) { if (a[i] % j == 0) { // if j is a factor store it in the set m.insert(j); // divide the number with j till it // is divisible so that only prime factors // are stored while (a[i] % j == 0) { a[i] /= j; } } } // if the number is still greater than 1 then // it is a prime factor, insert in set if (a[i] > 1) { m.insert(a[i]); } } // the number of unique prime factors will // the size of the set return m.size();} // Driver Functionint main(){ vector<int> a = { 1, 2, 3, 4, 5 }; cout << Distinct_Prime_factors(a) << '\n'; return 0;} // Java program to count distinct// prime factors of a number.import java.util.*; class GFG { // Function to count the number // of distinct prime factors of // product of array static int Distinct_Prime_factors(Vector<Integer> a) { // use set to store distinct factors HashSet<Integer> m = new HashSet<Integer>(); // iterate over every element of array for (int i = 0; i < a.size(); i++) { int sq = (int)Math.sqrt(a.get(i)); // from 2 to square root of number // run a loop and check the numbers // which are factors. for (int j = 2; j <= sq; j++) { if (a.get(i) % j == 0) { // if j is a factor store // it in the set m.add(j); // divide the number with j // till it is divisible so // that only prime factors // are stored while (a.get(i) % j == 0) { a.set(i, a.get(i) / j); } } } // if the number is still greater // than 1 then it is a prime factor, // insert in set if (a.get(i) > 1) { m.add(a.get(i)); } } // the number of unique prime // factors will the size of the set return m.size(); } // Driver Code public static void main(String args[]) { Vector<Integer> a = new Vector<Integer>(); a.add(1); a.add(2); a.add(3); a.add(4); a.add(5); System.out.println(Distinct_Prime_factors(a)); }} // This code is contributed by Arnab Kundu # Python3 program to count distinct# prime factors of a numberimport math # Function to count the number of distinct# prime factors of product of arraydef Distinct_Prime_factors( a): # use set to store distinct factors m = [] # iterate over every element of array for i in range (len(a)) : sq = int(math.sqrt(a[i])) # from 2 to square root of number run # a loop and check the numbers which # are factors. for j in range(2, sq + 1) : if (a[i] % j == 0) : # if j is a factor store # it in the set m.append(j) # divide the number with j till it # is divisible so that only prime # factors are stored while (a[i] % j == 0) : a[i] //= j # if the number is still greater # than 1 then it is a prime factor, # insert in set if (a[i] > 2) : m.append(a[i]) # the number of unique prime factors # will the size of the set return len(m) # Driver Codeif __name__ == "__main__": a = [ 1, 2, 3, 4, 5 ] print (Distinct_Prime_factors(a)) # This code is contributed by ita_c // C# program to count distinct// prime factors of a number.using System;using System.Collections.Generic; class GFG { // Function to count the number // of distinct prime factors of // product of array static int Distinct_Prime_factors(List<int> a) { // use set to store distinct factors HashSet<int> m = new HashSet<int>(); // iterate over every element of array for (int i = 0; i < a.Count; i++) { int sq = (int)Math.Sqrt(a[i]); // from 2 to square root of number // run a loop and check the numbers // which are factors. for (int j = 2; j <= sq; j++) { if (a[i] % j == 0) { // if j is a factor store // it in the set m.Add(j); // divide the number with j // till it is divisible so // that only prime factors // are stored while (a[i] % j == 0) { a[i] = a[i] / j; } } } // if the number is still greater // than 1 then it is a prime factor, // insert in set if (a[i] > 1) { m.Add(a[i]); } } // the number of unique prime // factors will the size of the set return m.Count; } // Driver Code public static void Main() { List<int> a = new List<int>(); a.Add(1); a.Add(2); a.Add(3); a.Add(4); a.Add(5); Console.WriteLine(Distinct_Prime_factors(a)); }} // This code is contributed by ihritik <script> // Javascript program to count distinct// prime factors of a number. // Function to count the number// of distinct prime factors of// product of arrayfunction Distinct_Prime_factors(a){ // Use set to store distinct factors let m = new Set(); // Iterate over every element of array for(let i = 0; i < a.length; i++) { let sq = Math.floor(Math.sqrt(a[i])); // From 2 to square root of number // run a loop and check the numbers // which are factors. for(let j = 2; j <= sq; j++) { if (a[i] % j == 0) { // If j is a factor store // it in the set m.add(j); // Divide the number with j // till it is divisible so // that only prime factors // are stored while (a[i] % j == 0) { a[i]= Math.floor(a[i] / j); } } } // If the number is still greater // than 1 then it is a prime factor, // insert in set if (a[i] > 1) { m.add(a[i]); } } // The number of unique prime // factors will the size of the set return m.size;} // Driver Codelet a = [ 1, 2, 3, 4, 5 ];document.write(Distinct_Prime_factors(a)); // This code is contributed by avanitrachhadiya2155 </script> Output : 3 andrew1234 ukasp ihritik Akanksha_Rai avanitrachhadiya2155 cpp-unordered_map prime-factor Arrays Competitive Programming Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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) Python | Using 2D arrays/lists the right way Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Competitive Programming - A Complete Guide Prefix Sum Array - Implementation and Applications in Competitive Programming
[ { "code": null, "e": 24395, "s": 24367, "text": "\n14 May, 2021" }, { "code": null, "e": 24532, "s": 24395, "text": "Given an array of integers.Let us say P is the product of elements of the array. Find the number of distinct prime factors of product P." }, { "code": null, "e": 24543, "s": 24532, "text": "Examples: " }, { "code": null, "e": 24687, "s": 24543, "text": "Input : 1 2 3 4 5 Output : 3 Explanation: Here P = 1 * 2 * 3 * 4 * 5 = 120. Distinct prime divisors of 120 are 2, 3 and 5. So, the output is 3." }, { "code": null, "e": 24852, "s": 24687, "text": "Input : 21 30 15 24 16 Output : 4 Explanation: Here P = 21 * 30 * 15 * 24 * 16 = 3628800. Distinct prime divisors of 3628800 are 2, 3, 5 and 7. So, the output is 4." }, { "code": null, "e": 25064, "s": 24852, "text": "Naive Approach : The simple solution for the problem would be to multiply every number in the array an then find the number of distinct prime factors of the product. But this method can lead to integer overflow." }, { "code": null, "e": 25262, "s": 25064, "text": "Better Approach : To avoid the overflow instead of multiplying the numbers we can find the prime factors of each element separately and store the prime factors in a set or a map for unique factors." }, { "code": null, "e": 25266, "s": 25262, "text": "C++" }, { "code": null, "e": 25271, "s": 25266, "text": "Java" }, { "code": null, "e": 25279, "s": 25271, "text": "Python3" }, { "code": null, "e": 25282, "s": 25279, "text": "C#" }, { "code": null, "e": 25293, "s": 25282, "text": "Javascript" }, { "code": "// C++ program to count distinct prime// factors of a number.#include <bits/stdc++.h>using namespace std; // Function to count the number of distinct prime// factors of product of arrayint Distinct_Prime_factors(vector<int> a){ // use set to store distinct factors unordered_set<int> m; // iterate over every element of array for (int i = 0; i < a.size(); i++) { int sq = sqrt(a[i]); // from 2 to square root of number run // a loop and check the numbers which // are factors. for (int j = 2; j <= sq; j++) { if (a[i] % j == 0) { // if j is a factor store it in the set m.insert(j); // divide the number with j till it // is divisible so that only prime factors // are stored while (a[i] % j == 0) { a[i] /= j; } } } // if the number is still greater than 1 then // it is a prime factor, insert in set if (a[i] > 1) { m.insert(a[i]); } } // the number of unique prime factors will // the size of the set return m.size();} // Driver Functionint main(){ vector<int> a = { 1, 2, 3, 4, 5 }; cout << Distinct_Prime_factors(a) << '\\n'; return 0;}", "e": 26600, "s": 25293, "text": null }, { "code": "// Java program to count distinct// prime factors of a number.import java.util.*; class GFG { // Function to count the number // of distinct prime factors of // product of array static int Distinct_Prime_factors(Vector<Integer> a) { // use set to store distinct factors HashSet<Integer> m = new HashSet<Integer>(); // iterate over every element of array for (int i = 0; i < a.size(); i++) { int sq = (int)Math.sqrt(a.get(i)); // from 2 to square root of number // run a loop and check the numbers // which are factors. for (int j = 2; j <= sq; j++) { if (a.get(i) % j == 0) { // if j is a factor store // it in the set m.add(j); // divide the number with j // till it is divisible so // that only prime factors // are stored while (a.get(i) % j == 0) { a.set(i, a.get(i) / j); } } } // if the number is still greater // than 1 then it is a prime factor, // insert in set if (a.get(i) > 1) { m.add(a.get(i)); } } // the number of unique prime // factors will the size of the set return m.size(); } // Driver Code public static void main(String args[]) { Vector<Integer> a = new Vector<Integer>(); a.add(1); a.add(2); a.add(3); a.add(4); a.add(5); System.out.println(Distinct_Prime_factors(a)); }} // This code is contributed by Arnab Kundu", "e": 28342, "s": 26600, "text": null }, { "code": "# Python3 program to count distinct# prime factors of a numberimport math # Function to count the number of distinct# prime factors of product of arraydef Distinct_Prime_factors( a): # use set to store distinct factors m = [] # iterate over every element of array for i in range (len(a)) : sq = int(math.sqrt(a[i])) # from 2 to square root of number run # a loop and check the numbers which # are factors. for j in range(2, sq + 1) : if (a[i] % j == 0) : # if j is a factor store # it in the set m.append(j) # divide the number with j till it # is divisible so that only prime # factors are stored while (a[i] % j == 0) : a[i] //= j # if the number is still greater # than 1 then it is a prime factor, # insert in set if (a[i] > 2) : m.append(a[i]) # the number of unique prime factors # will the size of the set return len(m) # Driver Codeif __name__ == \"__main__\": a = [ 1, 2, 3, 4, 5 ] print (Distinct_Prime_factors(a)) # This code is contributed by ita_c", "e": 29549, "s": 28342, "text": null }, { "code": "// C# program to count distinct// prime factors of a number.using System;using System.Collections.Generic; class GFG { // Function to count the number // of distinct prime factors of // product of array static int Distinct_Prime_factors(List<int> a) { // use set to store distinct factors HashSet<int> m = new HashSet<int>(); // iterate over every element of array for (int i = 0; i < a.Count; i++) { int sq = (int)Math.Sqrt(a[i]); // from 2 to square root of number // run a loop and check the numbers // which are factors. for (int j = 2; j <= sq; j++) { if (a[i] % j == 0) { // if j is a factor store // it in the set m.Add(j); // divide the number with j // till it is divisible so // that only prime factors // are stored while (a[i] % j == 0) { a[i] = a[i] / j; } } } // if the number is still greater // than 1 then it is a prime factor, // insert in set if (a[i] > 1) { m.Add(a[i]); } } // the number of unique prime // factors will the size of the set return m.Count; } // Driver Code public static void Main() { List<int> a = new List<int>(); a.Add(1); a.Add(2); a.Add(3); a.Add(4); a.Add(5); Console.WriteLine(Distinct_Prime_factors(a)); }} // This code is contributed by ihritik", "e": 31243, "s": 29549, "text": null }, { "code": "<script> // Javascript program to count distinct// prime factors of a number. // Function to count the number// of distinct prime factors of// product of arrayfunction Distinct_Prime_factors(a){ // Use set to store distinct factors let m = new Set(); // Iterate over every element of array for(let i = 0; i < a.length; i++) { let sq = Math.floor(Math.sqrt(a[i])); // From 2 to square root of number // run a loop and check the numbers // which are factors. for(let j = 2; j <= sq; j++) { if (a[i] % j == 0) { // If j is a factor store // it in the set m.add(j); // Divide the number with j // till it is divisible so // that only prime factors // are stored while (a[i] % j == 0) { a[i]= Math.floor(a[i] / j); } } } // If the number is still greater // than 1 then it is a prime factor, // insert in set if (a[i] > 1) { m.add(a[i]); } } // The number of unique prime // factors will the size of the set return m.size;} // Driver Codelet a = [ 1, 2, 3, 4, 5 ];document.write(Distinct_Prime_factors(a)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 32684, "s": 31243, "text": null }, { "code": null, "e": 32694, "s": 32684, "text": "Output : " }, { "code": null, "e": 32696, "s": 32694, "text": "3" }, { "code": null, "e": 32709, "s": 32698, "text": "andrew1234" }, { "code": null, "e": 32715, "s": 32709, "text": "ukasp" }, { "code": null, "e": 32723, "s": 32715, "text": "ihritik" }, { "code": null, "e": 32736, "s": 32723, "text": "Akanksha_Rai" }, { "code": null, "e": 32757, "s": 32736, "text": "avanitrachhadiya2155" }, { "code": null, "e": 32775, "s": 32757, "text": "cpp-unordered_map" }, { "code": null, "e": 32788, "s": 32775, "text": "prime-factor" }, { "code": null, "e": 32795, "s": 32788, "text": "Arrays" }, { "code": null, "e": 32819, "s": 32795, "text": "Competitive Programming" }, { "code": null, "e": 32824, "s": 32819, "text": "Hash" }, { "code": null, "e": 32831, "s": 32824, "text": "Arrays" }, { "code": null, "e": 32836, "s": 32831, "text": "Hash" }, { "code": null, "e": 32934, "s": 32836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32943, "s": 32934, "text": "Comments" }, { "code": null, "e": 32956, "s": 32943, "text": "Old Comments" }, { "code": null, "e": 32979, "s": 32956, "text": "Introduction to Arrays" }, { "code": null, "e": 33011, "s": 32979, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33025, "s": 33011, "text": "Linear Search" }, { "code": null, "e": 33110, "s": 33025, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 33155, "s": 33110, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33198, "s": 33155, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 33239, "s": 33198, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33266, "s": 33239, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 33309, "s": 33266, "text": "Competitive Programming - A Complete Guide" } ]
Compile and Run Java Programs in Sublime Text in Linux - GeeksforGeeks
11 Feb, 2021 Sublime Text is a free minimalist coding editor developed by Sublime HQ for desktop use. This development and IT program enable you to solely focus on your code, leaving all the other types of eye-candy out. Procedure: Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands.Configure the sublime text’s builds to run programsCreate a new build systemSave the build System and giving it a run Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands. Configure the sublime text’s builds to run programs Create a new build system Save the build System and giving it a run Step 1: Prior to entering the command, make sure the Java compiler is Installed on the machine. Now open the terminal and enter the command ‘java -version’ which will tell what version of java is installed on the machine. This command is will let us acknowledge the version and assures java is there installed on the machine. $ java -version If java is installed on your machine then you will see openjdk version number in the message as a response along with other info as pictorially been depicted below. Step 2: Configure the sublime text’s builds to run java programs as if you don’t really want to open sublime text from GUI, just use this command and save yourself some mouse movements. $ subl <file-name> Step 3: Create a new build system that follows the two steps. First click on ‘tools → Build System → New Build System’. By far a new file named untitled.sublime-build opens. Lastly, simply copy and paste the following code into that file. { "shell_cmd": "javac $file_name && java $file_base_name" } The above instruction runs the given command in shell replacing $file_name with your actual file-name and $file_base_name with the file-name without extension( file-name without .java extension) , whenever the code run command ( Ctrl + B ) is invoked in Sublime Text. Step 4: Save the build System and giving it a run. First, give it a name like RunJava.sublime-build by hitting ‘Ctrl + S’ Open a new java file and write some basic code and save it. Then click Tools→Build System → Choose your newly created build file RunJava (in this case). At last to run the program, press Ctrl + B. A new window appears at the bottom which shows output of your code. Do remember that this run window can’t take input. It can just show the output of your code. Java Linux-Unix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples TCP Server-Client implementation in C
[ { "code": null, "e": 23582, "s": 23554, "text": "\n11 Feb, 2021" }, { "code": null, "e": 23790, "s": 23582, "text": "Sublime Text is a free minimalist coding editor developed by Sublime HQ for desktop use. This development and IT program enable you to solely focus on your code, leaving all the other types of eye-candy out." }, { "code": null, "e": 23801, "s": 23790, "text": "Procedure:" }, { "code": null, "e": 24094, "s": 23801, "text": "Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands.Configure the sublime text’s builds to run programsCreate a new build systemSave the build System and giving it a run" }, { "code": null, "e": 24270, "s": 24094, "text": "Open terminal and the specific command are entered there in order to check for the software is there or not. Existence will be displayed out there itself as followed commands." }, { "code": null, "e": 24322, "s": 24270, "text": "Configure the sublime text’s builds to run programs" }, { "code": null, "e": 24348, "s": 24322, "text": "Create a new build system" }, { "code": null, "e": 24390, "s": 24348, "text": "Save the build System and giving it a run" }, { "code": null, "e": 24717, "s": 24390, "text": "Step 1: Prior to entering the command, make sure the Java compiler is Installed on the machine. Now open the terminal and enter the command ‘java -version’ which will tell what version of java is installed on the machine. This command is will let us acknowledge the version and assures java is there installed on the machine. " }, { "code": null, "e": 24733, "s": 24717, "text": "$ java -version" }, { "code": null, "e": 24898, "s": 24733, "text": "If java is installed on your machine then you will see openjdk version number in the message as a response along with other info as pictorially been depicted below." }, { "code": null, "e": 25084, "s": 24898, "text": "Step 2: Configure the sublime text’s builds to run java programs as if you don’t really want to open sublime text from GUI, just use this command and save yourself some mouse movements." }, { "code": null, "e": 25103, "s": 25084, "text": "$ subl <file-name>" }, { "code": null, "e": 25342, "s": 25103, "text": "Step 3: Create a new build system that follows the two steps. First click on ‘tools → Build System → New Build System’. By far a new file named untitled.sublime-build opens. Lastly, simply copy and paste the following code into that file." }, { "code": null, "e": 25406, "s": 25342, "text": "{\n \"shell_cmd\": \"javac $file_name && java $file_base_name\"\n}" }, { "code": null, "e": 25674, "s": 25406, "text": "The above instruction runs the given command in shell replacing $file_name with your actual file-name and $file_base_name with the file-name without extension( file-name without .java extension) , whenever the code run command ( Ctrl + B ) is invoked in Sublime Text." }, { "code": null, "e": 25726, "s": 25674, "text": "Step 4: Save the build System and giving it a run. " }, { "code": null, "e": 25797, "s": 25726, "text": "First, give it a name like RunJava.sublime-build by hitting ‘Ctrl + S’" }, { "code": null, "e": 25857, "s": 25797, "text": "Open a new java file and write some basic code and save it." }, { "code": null, "e": 25950, "s": 25857, "text": "Then click Tools→Build System → Choose your newly created build file RunJava (in this case)." }, { "code": null, "e": 25994, "s": 25950, "text": "At last to run the program, press Ctrl + B." }, { "code": null, "e": 26156, "s": 25994, "text": "A new window appears at the bottom which shows output of your code. Do remember that this run window can’t take input. It can just show the output of your code. " }, { "code": null, "e": 26161, "s": 26156, "text": "Java" }, { "code": null, "e": 26172, "s": 26161, "text": "Linux-Unix" }, { "code": null, "e": 26177, "s": 26172, "text": "Java" }, { "code": null, "e": 26275, "s": 26177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26284, "s": 26275, "text": "Comments" }, { "code": null, "e": 26297, "s": 26284, "text": "Old Comments" }, { "code": null, "e": 26327, "s": 26297, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26342, "s": 26327, "text": "Stream In Java" }, { "code": null, "e": 26363, "s": 26342, "text": "Constructors in Java" }, { "code": null, "e": 26409, "s": 26363, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26428, "s": 26409, "text": "Exceptions in Java" }, { "code": null, "e": 26468, "s": 26428, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 26508, "s": 26468, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 26535, "s": 26508, "text": "grep command in Unix/Linux" }, { "code": null, "e": 26570, "s": 26535, "text": "cut command in Linux with examples" } ]
Using range in switch case in C/C++ - GeeksforGeeks
22 Sep, 2021 You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement. That is the case range extension of the GNU C compiler and not standard C or C++ You can specify a range of consecutive values in a single case label, like this: case low ... high: It can be used for ranges of ASCII character codes like this: case 'A' ... 'Z': You need to Write spaces around the ellipses ... . For example, write this: // Correct - case 1 ... 5: // Wrong - case 1...5: C++ C // C++ program to illustrate// using range in switch case#include <iostream>using namespace std;int main(){ int arr[] = { 1, 5, 15, 20 }; for (int i = 0; i < 4; i++) { switch (arr[i]) { case 1 ... 6: cout << arr[i] <<" in range 1 to 6\n"; break; case 19 ... 20: cout << arr[i] <<" in range 19 to 20\n"; break; default: cout << arr[i] <<" not in range\n"; break; } } return 0;} //This code is contributed by shivanisinghss2110 // C program to illustrate// using range in switch case#include <stdio.h>int main(){ int arr[] = { 1, 5, 15, 20 }; for (int i = 0; i < 4; i++) { switch (arr[i]) { case 1 ... 6: printf("%d in range 1 to 6\n", arr[i]); break; case 19 ... 20: printf("%d in range 19 to 20\n", arr[i]); break; default: printf("%d not in range\n", arr[i]); break; } } return 0;} Output: 1 in range 1 to 6 5 in range 1 to 6 15 not in range 20 in range 19 to 20 Time Complexity: O(n), where n is the size of array arr. Auxiliary Space: O(1)Exercise : You can try above program for char array by modifying char array and case statement.Error conditions: low > high : The compiler gives an error message.Overlapping case values : If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message. low > high : The compiler gives an error message. Overlapping case values : If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message. This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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. subhammahato348 holgerbeer shivanisinghss2110 cpp-switch C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Multidimensional Arrays in C / C++ rand() and srand() in C/C++ Left Shift and Right Shift Operators in C/C++ fork() in C Command line arguments in C/C++ Vector in C++ STL Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) Inheritance in C++ Constructors in C++
[ { "code": null, "e": 24009, "s": 23981, "text": "\n22 Sep, 2021" }, { "code": null, "e": 24162, "s": 24009, "text": "You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement." }, { "code": null, "e": 24243, "s": 24162, "text": "That is the case range extension of the GNU C compiler and not standard C or C++" }, { "code": null, "e": 24324, "s": 24243, "text": "You can specify a range of consecutive values in a single case label, like this:" }, { "code": null, "e": 24343, "s": 24324, "text": "case low ... high:" }, { "code": null, "e": 24405, "s": 24343, "text": "It can be used for ranges of ASCII character codes like this:" }, { "code": null, "e": 24424, "s": 24405, "text": " case 'A' ... 'Z':" }, { "code": null, "e": 24500, "s": 24424, "text": "You need to Write spaces around the ellipses ... . For example, write this:" }, { "code": null, "e": 24557, "s": 24500, "text": "// Correct - case 1 ... 5:\n// Wrong - case 1...5: " }, { "code": null, "e": 24561, "s": 24557, "text": "C++" }, { "code": null, "e": 24563, "s": 24561, "text": "C" }, { "code": "// C++ program to illustrate// using range in switch case#include <iostream>using namespace std;int main(){ int arr[] = { 1, 5, 15, 20 }; for (int i = 0; i < 4; i++) { switch (arr[i]) { case 1 ... 6: cout << arr[i] <<\" in range 1 to 6\\n\"; break; case 19 ... 20: cout << arr[i] <<\" in range 19 to 20\\n\"; break; default: cout << arr[i] <<\" not in range\\n\"; break; } } return 0;} //This code is contributed by shivanisinghss2110", "e": 25114, "s": 24563, "text": null }, { "code": "// C program to illustrate// using range in switch case#include <stdio.h>int main(){ int arr[] = { 1, 5, 15, 20 }; for (int i = 0; i < 4; i++) { switch (arr[i]) { case 1 ... 6: printf(\"%d in range 1 to 6\\n\", arr[i]); break; case 19 ... 20: printf(\"%d in range 19 to 20\\n\", arr[i]); break; default: printf(\"%d not in range\\n\", arr[i]); break; } } return 0;}", "e": 25595, "s": 25114, "text": null }, { "code": null, "e": 25604, "s": 25595, "text": "Output: " }, { "code": null, "e": 25677, "s": 25604, "text": "1 in range 1 to 6\n5 in range 1 to 6\n15 not in range\n20 in range 19 to 20" }, { "code": null, "e": 25734, "s": 25677, "text": "Time Complexity: O(n), where n is the size of array arr." }, { "code": null, "e": 25869, "s": 25734, "text": "Auxiliary Space: O(1)Exercise : You can try above program for char array by modifying char array and case statement.Error conditions: " }, { "code": null, "e": 26085, "s": 25869, "text": "low > high : The compiler gives an error message.Overlapping case values : If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message." }, { "code": null, "e": 26135, "s": 26085, "text": "low > high : The compiler gives an error message." }, { "code": null, "e": 26302, "s": 26135, "text": "Overlapping case values : If the value of a case label is within a case range that has already been used in the switch statement, the compiler gives an error message." }, { "code": null, "e": 26723, "s": 26302, "text": "This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to 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": 26739, "s": 26723, "text": "subhammahato348" }, { "code": null, "e": 26750, "s": 26739, "text": "holgerbeer" }, { "code": null, "e": 26769, "s": 26750, "text": "shivanisinghss2110" }, { "code": null, "e": 26780, "s": 26769, "text": "cpp-switch" }, { "code": null, "e": 26791, "s": 26780, "text": "C Language" }, { "code": null, "e": 26795, "s": 26791, "text": "C++" }, { "code": null, "e": 26799, "s": 26795, "text": "CPP" }, { "code": null, "e": 26897, "s": 26799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26906, "s": 26897, "text": "Comments" }, { "code": null, "e": 26919, "s": 26906, "text": "Old Comments" }, { "code": null, "e": 26954, "s": 26919, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26982, "s": 26954, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27028, "s": 26982, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27040, "s": 27028, "text": "fork() in C" }, { "code": null, "e": 27072, "s": 27040, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27090, "s": 27072, "text": "Vector in C++ STL" }, { "code": null, "e": 27136, "s": 27090, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 27179, "s": 27136, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27198, "s": 27179, "text": "Inheritance in C++" } ]
8 Advanced Python Logging Features that You Shouldn’t Miss | by Xiaoxu Gao | Towards Data Science
Logging is a very important unit in software development. It helps developers have a better understanding of the execution of the program and reason about defects and unexpected failures. A log message can store information like the current status of a program or where the program is running. If an error occurs, developers can quickly find the line of code that causes the issue and act upon that. Python provides a quite powerful and flexible built-in logging module with many advanced features. In this article, I want to share 8 advanced features that will benefit us in developing the software. Before looking at more advanced features, let’s make sure we have a basic understanding on logging module. Logger The instance that we create to generate logs is called logger. It’s instantiated via logger = logging.getLogger(__name__). The best practice is to use __name__ as the logger name which includes the package name and module name. The name will appear in the log message which helps the developers quickly find out where the log is generated. Formatter & Handler Every logger has a number of configurations that can be modified. More advanced configurations will be discussed later, but the most common ones are formatter and handler. Formatter specifies the structure of the log message. Each log message is a LogRecord object with a number of attributes (module name is one of them). When we define a formatter, we can decide how the log message should look like with these attributes and possibly with customized attributes. The default formatter looks like this: severity:logger name:message# e.g: WARNING:root:Program starts! A customized formatter with more attributes can look like this: "%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s"# 2020-07-26 23:37:15,374 - [INFO] - __main__ - (main.py).main(18) - Program starts! Handler specifies the destination of log messages. A log message can be sent to more than one destination. The logging module actually provides quite a few standard handlers. The most popular ones are FileHandler which sends logs to a file and StreamHandler which sends logs to streams such as sys.stderr or sys.stdout. A logger instance supports 0 or more handlers. If no handlers are defined, then it will send logs to sys.stderr. If more than 1 handler are defined, then the destination is dependent on the level of the log message and and the level of the handler. For example, I have a FileHandler with level WARNING and a StreamHandler with level INFO. If I write an error log message, then the message will be sent to both sys.stdout and the log file. Example: In this example, we created a main.py, package1.py and app_logger.py. app_logger.py contains a function get_logger that returns a logger instance. The logger instance comes with a custom formatter and 2 handlers: StreamHandler with INFO level and FileHandler with WARNING level. It is important to set the basic level to INFO or DEBUG (the default logging level is WARNING), otherwise any logs lower than WARNING level will be filtered out. Both main.py and package1.py creates uses get_logger to create their own loggers. WARNING logs are sent to both console output (sys.stdout) and the log file, but INFO logs are only sent to console output. If you can fully understand what is going on in this example and why then we are good to go for more advanced features. As I mentioned previously, the LogRecord has a number of attributes, developers can pick up the most important attributes and put them in the formatter. In addition to that, the logging module also provides the possibilities to add user-defined attributes to the LogRecord. One way is to use LoggerAdapter. When you create an adapter, you pass the logger instance and your attributes (in dictionary) to it. This class provides the same interface as Logger, so you can still call methods like logger.info. New attribute with fixed value If you want to have a kind of fixed value attribute in the log message such as application name, then you can use the default LoggerAdapter class and get attribute value when you create the logger. Don’t forget to add this attribute in the formatter, you are free to choose the position of it. In the following code, I add the attribute app, this value is defined when I create the logger. New attribute with dynamic value In other situations, you might want dynamic attributes, for instance, a kind of dynamic ID. Then you can extend the basic LoggerAdapter and create your own. process() method is where the extra attributes are appended to the log message. In the following code, I add a dynamic attribute id which can be different in each log message. In this case, you don’t need to add the attribute in the formatter. Another way to add dynamic user-defined attributes is using custom Filter. Filters provide extra logic to determine which log messages to output. It is a step after checking the basic logging level, but before passing the log message to handlers. In addition to determining whether the log message should move forward, we can also insert new attributes in the method filter(). In this example, we add a new attribute color in filter() whose value is determined based on the level name of the log message. In this case, the attribute name again should be added in the formatter. Logging module is actually implemented in a thread-safe way, so we don’t need extra efforts. The code below shows that MainThread and WorkThread are sharing the same logger instance without race condition problem. There is also a built-in attribute threadName for the formatter. Under the hood, the logging module uses threading.RLock() pretty much everywhere. The differences between RLock from Lock are: Lock can only be acquired once and cannot be acquired anymore until it’s released. On the other hand, RLock can be acquired multiple times before release, but it should be released the same number of times.Lock can be released by any thread, but RLock can only be released by the same thread which acquires it. Lock can only be acquired once and cannot be acquired anymore until it’s released. On the other hand, RLock can be acquired multiple times before release, but it should be released the same number of times. Lock can be released by any thread, but RLock can only be released by the same thread which acquires it. Any handler which extends from class Handler has a method handle() to emit records. This is a code block of Handler.handle(). As you can see, the handler will acquire and release the lock before and after emitting the record. emit() method can be implemented differently in different handlers. Although logging module is thread-safe, it’s not process-safe. If you want multiple processes to write to the same log file, then you have to manually take care of the access to your file. According to the logging Cookbook, there are several options. QueueHandler + “consumer” process One option is using QueueHandler. The idea is to create a multiprocessing.Queue instance and share it among multiple processes. In the example below, we have 2 “producer” processes which send logs to the queue and a “consumer” process reading logs from the queue and write them into the log file. The logs in the queue will probably have different levels, therefore in log_processor, we use logger.log(record.levelno, record.msg) instead of logger.info() or logger.warning(). In the end, we send a signal to let log_processor stop. Sharing a queue instance among multiple processes or threads is not a new thing, but logging module kinds of helping us handle this situation. QueueHandler + QueueListener In logging.handlers module, there is a special class called QueueListener. This class creates a listener instance with a log message queue and a list of handlers to handle log records. QueueListener can replace the listener process we created in the previous example with less code. SocketHandler Another solution provided by the Cookbook is sending logs from multiple processes to a SocketHandler and have a separate process which implements a socket server that reads logs and send to the destination. The documents has a quite detailed implementation. All of these solutions basically follow the same principle: sending logs from different processes to a centralized place, either a queue or a remote server. The receiver on the other side is responsible for writing log records into destinations. So far, we’ve mentioned a number of handlers implemented by logging module. Another useful built-in handler is NullHandler. The implementation of NullHandler is basically nothing. Nevertheless, it helps developers distinguish library logs from application logs. This is the implementation of NullHandler. Why do we need to distinguish library logs from application logs? According to the author of logging module, Vinay Sajip: A third party library which uses logging should not spew logging output by default which may not be wanted by a developer/user of an application which uses it. The best practice is to not emit library logs by default and let the user of the library determine whether they want to receive and handle logs in the application. As a library developer, we only need one line of code inside __init__.py to add NullHandler. In subpackages and submodules, the loggers keep as usual. When we install this package in our application via pip install, we won’t see the logs from the library by default. The way to make these logs visible is adding handlers to the library logger in your application. # your application logging.getLogger("package").addHandler(logging.StreamHandler()) If the library doesn’t use NullHandler, but you want to disable the library logs, then you can set logging.getLogger("package").propagate = False. If propagate is set to False, then logs will not be passed to the handlers. RotatingFileHandler supports log file rotation, which gives the handler the ability to rotate log files based on its maximum size. 2 parameters should be defined here: maxBytes and backupCount. maxBytes tells the handler when to rotate the log. backupCount is the number of log files, each extended log file has a suffix “.1”, “.2” at the end of filename. If the current log message is about to let the log file exceed maximum size, then the handler will close the current file and open the next file. This is an example very much similar to the Cookbook. You should get 6 log files. Another file rotation handler is TimeRotatingFileHandler, which allows developers to create rotating logs based on elapsed time. The time conditions include: second, minute, hour, day, w0-w6 (0=Monday) and midnight (rollover at midnight). In the following example, we rotate log file every second with 5 backup files. Each backup file has a timestamp as the suffix. In many cases, we use logger.error() or logger.exception() when handling exceptions. But what if the logger itself raises an exception, what would happen to the program? Well, it depends. The logger error is handled when the handler calls emit(), which means any exception related to formatting or writing is caught by the handler rather than being raised. More specifically, handleError() method will print out the trackback to stderr and the program will continue. If you have a custom handler extending from Handler class, you can implement your own handleError(). In this example, the second log message has too many arguments. So in the console output, we received trackback and the program could still continue. However, if the exception happens outside of emit(), then the exception might be raised and the program would stop. For example, in the code below, we add an extra attribute id in logger.info() without handling it in LoggerAdapter. This error is not handled and causes the program to stop. The last point I want to share is about configuring your logger. There are 3 ways to configure a logger. use code The most straightforward option is to use code to configure your logger, just like all the examples we’ve seen so far in this article. But the disadvantage of this option is that any modification requires a change in the source code. use dictConfig The second option is to write configuration in a dictionary and use logging.config.dictConfig to read it. You can also save the dictionary to a JSON file and read from there. The advantage is that it can be loaded as an external configuration, but it can be error-prone due to its structure. use fileConfig Last but not least, the third option is to use logging.config.fileConfig. The configuration is written into a separate .ini file. It’s possible to update the configuration during the runtime via a configuration server. Cookbook shows an example of both client side and server side. The configuration is updated through a socket connection, and on the client side, we use c = logging.config.listen(PORT) c.start() to receive the latest configuration. I hope these logging tips and tricks can help you set up a nice logging framework around your application without hurting the performance. If you have anything to share, please leave your comments below!
[ { "code": null, "e": 572, "s": 172, "text": "Logging is a very important unit in software development. It helps developers have a better understanding of the execution of the program and reason about defects and unexpected failures. A log message can store information like the current status of a program or where the program is running. If an error occurs, developers can quickly find the line of code that causes the issue and act upon that." }, { "code": null, "e": 773, "s": 572, "text": "Python provides a quite powerful and flexible built-in logging module with many advanced features. In this article, I want to share 8 advanced features that will benefit us in developing the software." }, { "code": null, "e": 880, "s": 773, "text": "Before looking at more advanced features, let’s make sure we have a basic understanding on logging module." }, { "code": null, "e": 887, "s": 880, "text": "Logger" }, { "code": null, "e": 1227, "s": 887, "text": "The instance that we create to generate logs is called logger. It’s instantiated via logger = logging.getLogger(__name__). The best practice is to use __name__ as the logger name which includes the package name and module name. The name will appear in the log message which helps the developers quickly find out where the log is generated." }, { "code": null, "e": 1247, "s": 1227, "text": "Formatter & Handler" }, { "code": null, "e": 1419, "s": 1247, "text": "Every logger has a number of configurations that can be modified. More advanced configurations will be discussed later, but the most common ones are formatter and handler." }, { "code": null, "e": 1751, "s": 1419, "text": "Formatter specifies the structure of the log message. Each log message is a LogRecord object with a number of attributes (module name is one of them). When we define a formatter, we can decide how the log message should look like with these attributes and possibly with customized attributes. The default formatter looks like this:" }, { "code": null, "e": 1815, "s": 1751, "text": "severity:logger name:message# e.g: WARNING:root:Program starts!" }, { "code": null, "e": 1879, "s": 1815, "text": "A customized formatter with more attributes can look like this:" }, { "code": null, "e": 2064, "s": 1879, "text": "\"%(asctime)s - [%(levelname)s] - %(name)s - (%(filename)s).%(funcName)s(%(lineno)d) - %(message)s\"# 2020-07-26 23:37:15,374 - [INFO] - __main__ - (main.py).main(18) - Program starts!" }, { "code": null, "e": 2633, "s": 2064, "text": "Handler specifies the destination of log messages. A log message can be sent to more than one destination. The logging module actually provides quite a few standard handlers. The most popular ones are FileHandler which sends logs to a file and StreamHandler which sends logs to streams such as sys.stderr or sys.stdout. A logger instance supports 0 or more handlers. If no handlers are defined, then it will send logs to sys.stderr. If more than 1 handler are defined, then the destination is dependent on the level of the log message and and the level of the handler." }, { "code": null, "e": 2823, "s": 2633, "text": "For example, I have a FileHandler with level WARNING and a StreamHandler with level INFO. If I write an error log message, then the message will be sent to both sys.stdout and the log file." }, { "code": null, "e": 2832, "s": 2823, "text": "Example:" }, { "code": null, "e": 3355, "s": 2832, "text": "In this example, we created a main.py, package1.py and app_logger.py. app_logger.py contains a function get_logger that returns a logger instance. The logger instance comes with a custom formatter and 2 handlers: StreamHandler with INFO level and FileHandler with WARNING level. It is important to set the basic level to INFO or DEBUG (the default logging level is WARNING), otherwise any logs lower than WARNING level will be filtered out. Both main.py and package1.py creates uses get_logger to create their own loggers." }, { "code": null, "e": 3598, "s": 3355, "text": "WARNING logs are sent to both console output (sys.stdout) and the log file, but INFO logs are only sent to console output. If you can fully understand what is going on in this example and why then we are good to go for more advanced features." }, { "code": null, "e": 3872, "s": 3598, "text": "As I mentioned previously, the LogRecord has a number of attributes, developers can pick up the most important attributes and put them in the formatter. In addition to that, the logging module also provides the possibilities to add user-defined attributes to the LogRecord." }, { "code": null, "e": 4103, "s": 3872, "text": "One way is to use LoggerAdapter. When you create an adapter, you pass the logger instance and your attributes (in dictionary) to it. This class provides the same interface as Logger, so you can still call methods like logger.info." }, { "code": null, "e": 4134, "s": 4103, "text": "New attribute with fixed value" }, { "code": null, "e": 4524, "s": 4134, "text": "If you want to have a kind of fixed value attribute in the log message such as application name, then you can use the default LoggerAdapter class and get attribute value when you create the logger. Don’t forget to add this attribute in the formatter, you are free to choose the position of it. In the following code, I add the attribute app, this value is defined when I create the logger." }, { "code": null, "e": 4557, "s": 4524, "text": "New attribute with dynamic value" }, { "code": null, "e": 4958, "s": 4557, "text": "In other situations, you might want dynamic attributes, for instance, a kind of dynamic ID. Then you can extend the basic LoggerAdapter and create your own. process() method is where the extra attributes are appended to the log message. In the following code, I add a dynamic attribute id which can be different in each log message. In this case, you don’t need to add the attribute in the formatter." }, { "code": null, "e": 5335, "s": 4958, "text": "Another way to add dynamic user-defined attributes is using custom Filter. Filters provide extra logic to determine which log messages to output. It is a step after checking the basic logging level, but before passing the log message to handlers. In addition to determining whether the log message should move forward, we can also insert new attributes in the method filter()." }, { "code": null, "e": 5536, "s": 5335, "text": "In this example, we add a new attribute color in filter() whose value is determined based on the level name of the log message. In this case, the attribute name again should be added in the formatter." }, { "code": null, "e": 5815, "s": 5536, "text": "Logging module is actually implemented in a thread-safe way, so we don’t need extra efforts. The code below shows that MainThread and WorkThread are sharing the same logger instance without race condition problem. There is also a built-in attribute threadName for the formatter." }, { "code": null, "e": 5942, "s": 5815, "text": "Under the hood, the logging module uses threading.RLock() pretty much everywhere. The differences between RLock from Lock are:" }, { "code": null, "e": 6253, "s": 5942, "text": "Lock can only be acquired once and cannot be acquired anymore until it’s released. On the other hand, RLock can be acquired multiple times before release, but it should be released the same number of times.Lock can be released by any thread, but RLock can only be released by the same thread which acquires it." }, { "code": null, "e": 6460, "s": 6253, "text": "Lock can only be acquired once and cannot be acquired anymore until it’s released. On the other hand, RLock can be acquired multiple times before release, but it should be released the same number of times." }, { "code": null, "e": 6565, "s": 6460, "text": "Lock can be released by any thread, but RLock can only be released by the same thread which acquires it." }, { "code": null, "e": 6859, "s": 6565, "text": "Any handler which extends from class Handler has a method handle() to emit records. This is a code block of Handler.handle(). As you can see, the handler will acquire and release the lock before and after emitting the record. emit() method can be implemented differently in different handlers." }, { "code": null, "e": 7110, "s": 6859, "text": "Although logging module is thread-safe, it’s not process-safe. If you want multiple processes to write to the same log file, then you have to manually take care of the access to your file. According to the logging Cookbook, there are several options." }, { "code": null, "e": 7144, "s": 7110, "text": "QueueHandler + “consumer” process" }, { "code": null, "e": 7441, "s": 7144, "text": "One option is using QueueHandler. The idea is to create a multiprocessing.Queue instance and share it among multiple processes. In the example below, we have 2 “producer” processes which send logs to the queue and a “consumer” process reading logs from the queue and write them into the log file." }, { "code": null, "e": 7819, "s": 7441, "text": "The logs in the queue will probably have different levels, therefore in log_processor, we use logger.log(record.levelno, record.msg) instead of logger.info() or logger.warning(). In the end, we send a signal to let log_processor stop. Sharing a queue instance among multiple processes or threads is not a new thing, but logging module kinds of helping us handle this situation." }, { "code": null, "e": 7848, "s": 7819, "text": "QueueHandler + QueueListener" }, { "code": null, "e": 8131, "s": 7848, "text": "In logging.handlers module, there is a special class called QueueListener. This class creates a listener instance with a log message queue and a list of handlers to handle log records. QueueListener can replace the listener process we created in the previous example with less code." }, { "code": null, "e": 8145, "s": 8131, "text": "SocketHandler" }, { "code": null, "e": 8403, "s": 8145, "text": "Another solution provided by the Cookbook is sending logs from multiple processes to a SocketHandler and have a separate process which implements a socket server that reads logs and send to the destination. The documents has a quite detailed implementation." }, { "code": null, "e": 8649, "s": 8403, "text": "All of these solutions basically follow the same principle: sending logs from different processes to a centralized place, either a queue or a remote server. The receiver on the other side is responsible for writing log records into destinations." }, { "code": null, "e": 8911, "s": 8649, "text": "So far, we’ve mentioned a number of handlers implemented by logging module. Another useful built-in handler is NullHandler. The implementation of NullHandler is basically nothing. Nevertheless, it helps developers distinguish library logs from application logs." }, { "code": null, "e": 8954, "s": 8911, "text": "This is the implementation of NullHandler." }, { "code": null, "e": 9020, "s": 8954, "text": "Why do we need to distinguish library logs from application logs?" }, { "code": null, "e": 9076, "s": 9020, "text": "According to the author of logging module, Vinay Sajip:" }, { "code": null, "e": 9236, "s": 9076, "text": "A third party library which uses logging should not spew logging output by default which may not be wanted by a developer/user of an application which uses it." }, { "code": null, "e": 9400, "s": 9236, "text": "The best practice is to not emit library logs by default and let the user of the library determine whether they want to receive and handle logs in the application." }, { "code": null, "e": 9667, "s": 9400, "text": "As a library developer, we only need one line of code inside __init__.py to add NullHandler. In subpackages and submodules, the loggers keep as usual. When we install this package in our application via pip install, we won’t see the logs from the library by default." }, { "code": null, "e": 9764, "s": 9667, "text": "The way to make these logs visible is adding handlers to the library logger in your application." }, { "code": null, "e": 9848, "s": 9764, "text": "# your application logging.getLogger(\"package\").addHandler(logging.StreamHandler())" }, { "code": null, "e": 10071, "s": 9848, "text": "If the library doesn’t use NullHandler, but you want to disable the library logs, then you can set logging.getLogger(\"package\").propagate = False. If propagate is set to False, then logs will not be passed to the handlers." }, { "code": null, "e": 10573, "s": 10071, "text": "RotatingFileHandler supports log file rotation, which gives the handler the ability to rotate log files based on its maximum size. 2 parameters should be defined here: maxBytes and backupCount. maxBytes tells the handler when to rotate the log. backupCount is the number of log files, each extended log file has a suffix “.1”, “.2” at the end of filename. If the current log message is about to let the log file exceed maximum size, then the handler will close the current file and open the next file." }, { "code": null, "e": 10655, "s": 10573, "text": "This is an example very much similar to the Cookbook. You should get 6 log files." }, { "code": null, "e": 10894, "s": 10655, "text": "Another file rotation handler is TimeRotatingFileHandler, which allows developers to create rotating logs based on elapsed time. The time conditions include: second, minute, hour, day, w0-w6 (0=Monday) and midnight (rollover at midnight)." }, { "code": null, "e": 11021, "s": 10894, "text": "In the following example, we rotate log file every second with 5 backup files. Each backup file has a timestamp as the suffix." }, { "code": null, "e": 11209, "s": 11021, "text": "In many cases, we use logger.error() or logger.exception() when handling exceptions. But what if the logger itself raises an exception, what would happen to the program? Well, it depends." }, { "code": null, "e": 11589, "s": 11209, "text": "The logger error is handled when the handler calls emit(), which means any exception related to formatting or writing is caught by the handler rather than being raised. More specifically, handleError() method will print out the trackback to stderr and the program will continue. If you have a custom handler extending from Handler class, you can implement your own handleError()." }, { "code": null, "e": 11739, "s": 11589, "text": "In this example, the second log message has too many arguments. So in the console output, we received trackback and the program could still continue." }, { "code": null, "e": 12029, "s": 11739, "text": "However, if the exception happens outside of emit(), then the exception might be raised and the program would stop. For example, in the code below, we add an extra attribute id in logger.info() without handling it in LoggerAdapter. This error is not handled and causes the program to stop." }, { "code": null, "e": 12134, "s": 12029, "text": "The last point I want to share is about configuring your logger. There are 3 ways to configure a logger." }, { "code": null, "e": 12143, "s": 12134, "text": "use code" }, { "code": null, "e": 12377, "s": 12143, "text": "The most straightforward option is to use code to configure your logger, just like all the examples we’ve seen so far in this article. But the disadvantage of this option is that any modification requires a change in the source code." }, { "code": null, "e": 12392, "s": 12377, "text": "use dictConfig" }, { "code": null, "e": 12684, "s": 12392, "text": "The second option is to write configuration in a dictionary and use logging.config.dictConfig to read it. You can also save the dictionary to a JSON file and read from there. The advantage is that it can be loaded as an external configuration, but it can be error-prone due to its structure." }, { "code": null, "e": 12699, "s": 12684, "text": "use fileConfig" }, { "code": null, "e": 12829, "s": 12699, "text": "Last but not least, the third option is to use logging.config.fileConfig. The configuration is written into a separate .ini file." }, { "code": null, "e": 13149, "s": 12829, "text": "It’s possible to update the configuration during the runtime via a configuration server. Cookbook shows an example of both client side and server side. The configuration is updated through a socket connection, and on the client side, we use c = logging.config.listen(PORT) c.start() to receive the latest configuration." } ]
Entity Framework - Code First Migration
Entity Framework 4.3 includes a new Code First Migrations feature that allows you to incrementally evolve the database schema as your model changes over time. For most developers, this is a big improvement over the database initializer options from the 4.1 and 4.2 releases that required you to manually update the database or drop and recreate it when your model changed. Before Entity Framework 4.3, if you already have data (other than seed data) or existing Stored Procedures, triggers, etc. in your database, these strategies used to drop the entire database and recreate it, so you would lose the data and other DB objects. Before Entity Framework 4.3, if you already have data (other than seed data) or existing Stored Procedures, triggers, etc. in your database, these strategies used to drop the entire database and recreate it, so you would lose the data and other DB objects. With migration, it will automatically update the database schema, when your model changes without losing any existing data or other database objects. With migration, it will automatically update the database schema, when your model changes without losing any existing data or other database objects. It uses a new database initializer called MigrateDatabaseToLatestVersion. It uses a new database initializer called MigrateDatabaseToLatestVersion. There are two kinds of Migration − Automated Migration Code based Migration Automated Migration was first introduced in Entity framework 4.3. In automated migration you don't need to process database migration manually in the code file. For example, for each change you will also need to change in your domain classes. But with automated migration you just have to run a command in Package Manager Console to get done this. Let’s take a look at the following step-by-step process of automated migration. When you use Code First approach, you don't have a database for you application. In this example we will be starting with our 3 basic classes such as Student, Course and Enrollment as shown in the following code. public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } public class Course { public int CourseID { get; set; } public string Title { get; set; } [Index] public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } Following is the context class. public class MyContext : DbContext { public MyContext() : base("MyContextDB") {} public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } Before running the application, you need to enable automated migration. Step 1 − Open Package Manger Console from Tools → NuGet Package Manger → Package Manger Console. Step 2 − To enable automated migration run the following command in Package Manager Console. PM> enable-migrations -EnableAutomaticMigrations:$true Step 3 − Once the command runs successfully, it creates an internal sealed Configuration class in the Migration folder of your project as shown in the following code. namespace EFCodeFirstDemo.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<EFCodeFirstDemo.MyContext> { public Configuration() { AutomaticMigrationsEnabled = true; ContextKey = "EFCodeFirstDemo.MyContext"; } protected override void Seed(EFCodeFirstDemo.MyContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // context.People.AddOrUpdate( // p ⇒ p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); } } } Step 4 − Set the database initializer in the context class with the new DB initialization strategy MigrateDatabaseToLatestVersion. public class MyContext : DbContext { public MyContext() : base("MyContextDB") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, EFCodeFirstDemo.Migrations.Configuration>("MyContextDB")); } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } Step 5 − You have set up automated migration. When you execute your application, then it will automatically take care of migration, when you change the model. Step 6 − As you can see that one system table __MigrationHistory is also created in your database with other tables. In __MigrationHistory, automated migration maintains the history of database changes. Step 7 − When you add another entity class as your domain class and execute your application, then it will create the table in your database. Let’s add the following StudentLogIn class. public class StudentLogIn { [Key, ForeignKey("Student")] public int ID { get; set; } public string EmailID { get; set; } public string Password { get; set; } public virtual Student Student { get; set; } } Step 8 − Don’t forget to add the DBSet for the above mentioned class in your context class as shown in the following code. public virtual DbSet<StudentLogIn> StudentsLogIn { get; set; } Step 9 − Run your application again and you will see that StudentsLogIn table is added to your database. The above steps mentioned for automated migrations will only work for your entity. For example, to add another entity class or remove the existing entity class it will successfully migrate. But if you add or remove any property to your entity class then it will throw an exception. Step 10 − To handle the property migration you need to set AutomaticMigrationDataLossAllowed = true in the configuration class constructor. public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "EFCodeFirstDemo.MyContext"; } When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. Code-based migration is useful when you want more control on the migration. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data. The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. To deploy the application, you'll have to enable Migrations. The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. To deploy the application, you'll have to enable Migrations. Here is the basic rule to migrate changes in the database − Enable Migrations Add Migration Update Database Let’s take a look at the following step-by-step process of code-base migration. When you use code first approach, you don't have a database for you application. In this example we will be starting again with our 3 basic classes such as Student, Course and Enrollment as shown in the following code. public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } public class Course { public int CourseID { get; set; } public string Title { get; set; } [Index] public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } Following is the context class. public class MyContext : DbContext { public MyContext() : base("MyContextDB") { Database.SetInitializer(new MigrateDatabaseToLatestVersion< MyContext, EFCodeFirstDemo.Migrations.Configuration>("MyContextDB")); } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } } Step 1 − Before running the application you need to enable migration. Step 2 − Open Package Manager Console from Tools → NuGet Package Manger → Package Manger Console. Step 3 − Migration is already enabled, now add migration in your application by executing the following command. PM> add-migration "UniDB Schema" Step 4 − When the command is successfully executed then you will see a new file has been created in the Migration folder with the name of the parameter you passed to the command with a timestamp prefix as shown in the following image. Step 5 − You can create or update the database using the “update-database” command. PM> Update-Database -Verbose The "-Verbose" flag specifies to show the SQL Statements being applied to the target database in the console. Step 6 − Let’s add one more property ‘Age’ in the student class and then execute the update statement. public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public int Age { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } When you execute PM → Update-Database –Verbose, when the command is successfully executed you will see that the new column Age is added in your database. We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3405, "s": 3032, "text": "Entity Framework 4.3 includes a new Code First Migrations feature that allows you to incrementally evolve the database schema as your model changes over time. For most developers, this is a big improvement over the database initializer options from the 4.1 and 4.2 releases that required you to manually update the database or drop and recreate it when your model changed." }, { "code": null, "e": 3662, "s": 3405, "text": "Before Entity Framework 4.3, if you already have data (other than seed data) or existing Stored Procedures, triggers, etc. in your database, these strategies used to drop the entire database and recreate it, so you would lose the data and other DB objects." }, { "code": null, "e": 3919, "s": 3662, "text": "Before Entity Framework 4.3, if you already have data (other than seed data) or existing Stored Procedures, triggers, etc. in your database, these strategies used to drop the entire database and recreate it, so you would lose the data and other DB objects." }, { "code": null, "e": 4069, "s": 3919, "text": "With migration, it will automatically update the database schema, when your model changes without losing any existing data or other database objects." }, { "code": null, "e": 4219, "s": 4069, "text": "With migration, it will automatically update the database schema, when your model changes without losing any existing data or other database objects." }, { "code": null, "e": 4293, "s": 4219, "text": "It uses a new database initializer called MigrateDatabaseToLatestVersion." }, { "code": null, "e": 4367, "s": 4293, "text": "It uses a new database initializer called MigrateDatabaseToLatestVersion." }, { "code": null, "e": 4402, "s": 4367, "text": "There are two kinds of Migration −" }, { "code": null, "e": 4422, "s": 4402, "text": "Automated Migration" }, { "code": null, "e": 4443, "s": 4422, "text": "Code based Migration" }, { "code": null, "e": 4791, "s": 4443, "text": "Automated Migration was first introduced in Entity framework 4.3. In automated migration you don't need to process database migration manually in the code file. For example, for each change you will also need to change in your domain classes. But with automated migration you just have to run a command in Package Manager Console to get done this." }, { "code": null, "e": 4871, "s": 4791, "text": "Let’s take a look at the following step-by-step process of automated migration." }, { "code": null, "e": 4952, "s": 4871, "text": "When you use Code First approach, you don't have a database for you application." }, { "code": null, "e": 5084, "s": 4952, "text": "In this example we will be starting with our 3 basic classes such as Student, Course and Enrollment as shown in the following code." }, { "code": null, "e": 5839, "s": 5084, "text": "public class Enrollment {\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\t\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n\n}\n\npublic class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n}\n\npublic class Course {\n public int CourseID { get; set; }\n public string Title { get; set; }\n [Index]\n public int Credits { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n}" }, { "code": null, "e": 5871, "s": 5839, "text": "Following is the context class." }, { "code": null, "e": 6129, "s": 5871, "text": "public class MyContext : DbContext {\n public MyContext() : base(\"MyContextDB\") {}\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n}" }, { "code": null, "e": 6201, "s": 6129, "text": "Before running the application, you need to enable automated migration." }, { "code": null, "e": 6298, "s": 6201, "text": "Step 1 − Open Package Manger Console from Tools → NuGet Package Manger → Package Manger Console." }, { "code": null, "e": 6391, "s": 6298, "text": "Step 2 − To enable automated migration run the following command in Package Manager Console." }, { "code": null, "e": 6446, "s": 6391, "text": "PM> enable-migrations -EnableAutomaticMigrations:$true" }, { "code": null, "e": 6613, "s": 6446, "text": "Step 3 − Once the command runs successfully, it creates an internal sealed Configuration class in the Migration folder of your project as shown in the following code." }, { "code": null, "e": 7563, "s": 6613, "text": "namespace EFCodeFirstDemo.Migrations {\n\n using System;\n using System.Data.Entity;\n using System.Data.Entity.Migrations;\n using System.Linq;\n\t\n internal sealed class Configuration : DbMigrationsConfiguration<EFCodeFirstDemo.MyContext> {\n\n public Configuration() {\n AutomaticMigrationsEnabled = true;\n ContextKey = \"EFCodeFirstDemo.MyContext\";\n }\n\n protected override void Seed(EFCodeFirstDemo.MyContext context) {\n\n // This method will be called after migrating to the latest version.\n // You can use the DbSet<T>.AddOrUpdate() helper extension method\n // to avoid creating duplicate seed data. E.g.\n\n // context.People.AddOrUpdate(\n // p ⇒ p.FullName, \n // new Person { FullName = \"Andrew Peters\" }, \n // new Person { FullName = \"Brice Lambson\" }, \n // new Person { FullName = \"Rowan Miller\" }\n // );\n }\n }\n}" }, { "code": null, "e": 7694, "s": 7563, "text": "Step 4 − Set the database initializer in the context class with the new DB initialization strategy MigrateDatabaseToLatestVersion." }, { "code": null, "e": 8104, "s": 7694, "text": "public class MyContext : DbContext {\n\n public MyContext() : base(\"MyContextDB\") {\n Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, \n EFCodeFirstDemo.Migrations.Configuration>(\"MyContextDB\"));\n }\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n\n}" }, { "code": null, "e": 8263, "s": 8104, "text": "Step 5 − You have set up automated migration. When you execute your application, then it will automatically take care of migration, when you change the model." }, { "code": null, "e": 8466, "s": 8263, "text": "Step 6 − As you can see that one system table __MigrationHistory is also created in your database with other tables. In __MigrationHistory, automated migration maintains the history of database changes." }, { "code": null, "e": 8652, "s": 8466, "text": "Step 7 − When you add another entity class as your domain class and execute your application, then it will create the table in your database. Let’s add the following StudentLogIn class." }, { "code": null, "e": 8874, "s": 8652, "text": "public class StudentLogIn {\n [Key, ForeignKey(\"Student\")]\n public int ID { get; set; }\n public string EmailID { get; set; }\n public string Password { get; set; }\n\t\n public virtual Student Student { get; set; }\n}" }, { "code": null, "e": 8997, "s": 8874, "text": "Step 8 − Don’t forget to add the DBSet for the above mentioned class in your context class as shown in the following code." }, { "code": null, "e": 9060, "s": 8997, "text": "public virtual DbSet<StudentLogIn> StudentsLogIn { get; set; }" }, { "code": null, "e": 9165, "s": 9060, "text": "Step 9 − Run your application again and you will see that StudentsLogIn table is added to your database." }, { "code": null, "e": 9447, "s": 9165, "text": "The above steps mentioned for automated migrations will only work for your entity. For example, to add another entity class or remove the existing entity class it will successfully migrate. But if you add or remove any property to your entity class then it will throw an exception." }, { "code": null, "e": 9587, "s": 9447, "text": "Step 10 − To handle the property migration you need to set AutomaticMigrationDataLossAllowed = true in the configuration class constructor." }, { "code": null, "e": 9742, "s": 9587, "text": "public Configuration() {\n AutomaticMigrationsEnabled = true;\n AutomaticMigrationDataLossAllowed = true;\n ContextKey = \"EFCodeFirstDemo.MyContext\";\n}" }, { "code": null, "e": 10089, "s": 9742, "text": "When you develop a new application, your data model changes frequently, and each time the model changes, it gets out of sync with the database. You have configured the Entity Framework to automatically drop and re-create the database each time you change the data model. Code-based migration is useful when you want more control on the migration." }, { "code": null, "e": 10326, "s": 10089, "text": "When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data." }, { "code": null, "e": 10563, "s": 10326, "text": "When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data." }, { "code": null, "e": 10781, "s": 10563, "text": "The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. To deploy the application, you'll have to enable Migrations." }, { "code": null, "e": 10999, "s": 10781, "text": "The Code First Migrations feature solves this problem by enabling Code First to update the database schema instead of dropping and re-creating the database. To deploy the application, you'll have to enable Migrations." }, { "code": null, "e": 11059, "s": 10999, "text": "Here is the basic rule to migrate changes in the database −" }, { "code": null, "e": 11077, "s": 11059, "text": "Enable Migrations" }, { "code": null, "e": 11091, "s": 11077, "text": "Add Migration" }, { "code": null, "e": 11107, "s": 11091, "text": "Update Database" }, { "code": null, "e": 11187, "s": 11107, "text": "Let’s take a look at the following step-by-step process of code-base migration." }, { "code": null, "e": 11268, "s": 11187, "text": "When you use code first approach, you don't have a database for you application." }, { "code": null, "e": 11406, "s": 11268, "text": "In this example we will be starting again with our 3 basic classes such as Student, Course and Enrollment as shown in the following code." }, { "code": null, "e": 12161, "s": 11406, "text": "public class Enrollment {\n public int EnrollmentID { get; set; }\n public int CourseID { get; set; }\n public int StudentID { get; set; }\n public Grade? Grade { get; set; }\n\t\n public virtual Course Course { get; set; }\n public virtual Student Student { get; set; }\n\n}\n\npublic class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n}\n\npublic class Course {\n public int CourseID { get; set; }\n public string Title { get; set; }\n [Index]\n public int Credits { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n}" }, { "code": null, "e": 12193, "s": 12161, "text": "Following is the context class." }, { "code": null, "e": 12603, "s": 12193, "text": "public class MyContext : DbContext {\n\n public MyContext() : base(\"MyContextDB\") {\n Database.SetInitializer(new MigrateDatabaseToLatestVersion<\n MyContext, EFCodeFirstDemo.Migrations.Configuration>(\"MyContextDB\"));\n }\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n\n}" }, { "code": null, "e": 12673, "s": 12603, "text": "Step 1 − Before running the application you need to enable migration." }, { "code": null, "e": 12771, "s": 12673, "text": "Step 2 − Open Package Manager Console from Tools → NuGet Package Manger → Package Manger Console." }, { "code": null, "e": 12884, "s": 12771, "text": "Step 3 − Migration is already enabled, now add migration in your application by executing the following command." }, { "code": null, "e": 12918, "s": 12884, "text": "PM> add-migration \"UniDB Schema\"\n" }, { "code": null, "e": 13153, "s": 12918, "text": "Step 4 − When the command is successfully executed then you will see a new file has been created in the Migration folder with the name of the parameter you passed to the command with a timestamp prefix as shown in the following image." }, { "code": null, "e": 13237, "s": 13153, "text": "Step 5 − You can create or update the database using the “update-database” command." }, { "code": null, "e": 13267, "s": 13237, "text": "PM> Update-Database -Verbose\n" }, { "code": null, "e": 13377, "s": 13267, "text": "The \"-Verbose\" flag specifies to show the SQL Statements being applied to the target database in the console." }, { "code": null, "e": 13480, "s": 13377, "text": "Step 6 − Let’s add one more property ‘Age’ in the student class and then execute the update statement." }, { "code": null, "e": 13771, "s": 13480, "text": "public class Student {\n public int ID { get; set; }\n public string LastName { get; set; }\n public string FirstMidName { get; set; }\n public int Age { get; set; }\n public DateTime EnrollmentDate { get; set; }\n\t\n public virtual ICollection<Enrollment> Enrollments { get; set; }\n\n}" }, { "code": null, "e": 13925, "s": 13771, "text": "When you execute PM → Update-Database –Verbose, when the command is successfully executed you will see that the new column Age is added in your database." }, { "code": null, "e": 14024, "s": 13925, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 14057, "s": 14024, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 14075, "s": 14057, "text": " Trevoir Williams" }, { "code": null, "e": 14110, "s": 14075, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 14123, "s": 14110, "text": " Nilay Mehta" }, { "code": null, "e": 14158, "s": 14123, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 14174, "s": 14158, "text": " TELCOMA Global" }, { "code": null, "e": 14209, "s": 14174, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 14227, "s": 14209, "text": " Mustafa Radaideh" }, { "code": null, "e": 14234, "s": 14227, "text": " Print" }, { "code": null, "e": 14245, "s": 14234, "text": " Add Notes" } ]
jQuery - stopPropagation() Method
The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object). Here is the simple syntax to use this method − event.stopPropagation() Here is the description of all the parameters used by this method − NA NA Following is a simple example a simple showing the usage of this method. This example demonstrate how you can prevent other event handlers from being called − <html> <head> <title>the title</title> <script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"> </script> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("div").click(function(event){ alert("This is : " + $(this).text()); // Comment the following to see the difference event.stopPropagation(); }); }); </script> <style> div{ margin:10px;padding:12px; border:2px solid #666; width:160px; } </style> </head> <body> <p>Click on any box to see the effect:</p> <div id="div1" style="background-color:blue;"> OUTER BOX <div id="div2" style="background-color:red;"> INNER BOX </div> </div> </body> </html> To understand it in better way you can Try it yourself. Advertisements 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2469, "s": 2322, "text": "The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. " }, { "code": null, "e": 2589, "s": 2469, "text": "You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object)." }, { "code": null, "e": 2636, "s": 2589, "text": "Here is the simple syntax to use this method −" }, { "code": null, "e": 2662, "s": 2636, "text": "event.stopPropagation() \n" }, { "code": null, "e": 2730, "s": 2662, "text": "Here is the description of all the parameters used by this method −" }, { "code": null, "e": 2733, "s": 2730, "text": "NA" }, { "code": null, "e": 2736, "s": 2733, "text": "NA" }, { "code": null, "e": 2895, "s": 2736, "text": "Following is a simple example a simple showing the usage of this method. This example demonstrate how you can prevent other event handlers from being called −" }, { "code": null, "e": 3707, "s": 2895, "text": "<html>\n<head>\n<title>the title</title>\n <script type=\"text/javascript\" \n src=\"/jquery/jquery-1.3.2.min.js\">\n </script>\n <script type=\"text/javascript\" language=\"javascript\">\n \n $(document).ready(function() {\n\n $(\"div\").click(function(event){\n alert(\"This is : \" + $(this).text());\n // Comment the following to see the difference\n event.stopPropagation();\n });\n\n });\n\n </script>\n <style>\n div{ margin:10px;padding:12px;\n border:2px solid #666;\n width:160px;\n }\n </style>\n</head>\n<body>\n <p>Click on any box to see the effect:</p>\n <div id=\"div1\" style=\"background-color:blue;\">\n OUTER BOX\n <div id=\"div2\" style=\"background-color:red;\">\n INNER BOX\n </div> \n </div>\n</body>\n</html>\n" }, { "code": null, "e": 3763, "s": 3707, "text": "To understand it in better way you can Try it yourself." }, { "code": null, "e": 3780, "s": 3763, "text": "\nAdvertisements\n" }, { "code": null, "e": 3813, "s": 3780, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 3827, "s": 3813, "text": " Mahesh Kumar" }, { "code": null, "e": 3862, "s": 3827, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3876, "s": 3862, "text": " Pratik Singh" }, { "code": null, "e": 3911, "s": 3876, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3928, "s": 3911, "text": " Frahaan Hussain" }, { "code": null, "e": 3961, "s": 3928, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 3989, "s": 3961, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4022, "s": 3989, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4043, "s": 4022, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4075, "s": 4043, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4092, "s": 4075, "text": " Laurence Svekis" }, { "code": null, "e": 4099, "s": 4092, "text": " Print" }, { "code": null, "e": 4110, "s": 4099, "text": " Add Notes" } ]
Types of References in Java
There are four different kinds of references based on the way in which the data is garbage collected. Strong references Weak references Soft references Phantom references It is the default type of reference object. An object that has active strong reference can’t be garbage collected. It is possible only if the variable that is strongly referenced points to null. Let us see an example − class Demo { //Some functionality } public class Demo_example{ public static void main(String[] args){ Demo my_inst = new Demo(); my_inst = null; } } They are not default class of reference object, hence need to be explicitly specified. It is generally used with WeakHashmap, so as to reference entry objects. Such weak references are marked for garbage collection by the Java Virtual Machine. Such references are created using the ‘java.lang.ref.WeakReference’ class. Let us see an example − Live Demo import java.lang.ref.WeakReference; class Demo{ public void display_msg(){ System.out.println("Hello"); } } public class Demo_sample{ public static void main(String[] args){ Demo inst = new Demo(); inst.display_msg(); WeakReference<Demo> my_weak_ref = new WeakReference<Demo>(inst); inst = null; inst = my_weak_ref.get(); inst.display_msg(); } Hello Hello A class named Demo has a function named ‘display_msg’. This function displays a relevant message. In another class named ‘Demo_sample’, the main function is defined, and an instance of Demo class is created. The ‘display_msg’ function is called on the instance. A weakReference to the Demo class is created, and the Demo insatne is assigned to null, and the function is called on it again. The relevant output is displayed on the console.
[ { "code": null, "e": 1164, "s": 1062, "text": "There are four different kinds of references based on the way in which the data is garbage collected." }, { "code": null, "e": 1182, "s": 1164, "text": "Strong references" }, { "code": null, "e": 1198, "s": 1182, "text": "Weak references" }, { "code": null, "e": 1214, "s": 1198, "text": "Soft references" }, { "code": null, "e": 1233, "s": 1214, "text": "Phantom references" }, { "code": null, "e": 1452, "s": 1233, "text": "It is the default type of reference object. An object that has active strong reference can’t be garbage\ncollected. It is possible only if the variable that is strongly referenced points to null.\nLet us see an example −" }, { "code": null, "e": 1623, "s": 1452, "text": "class Demo {\n //Some functionality\n}\npublic class Demo_example{\n public static void main(String[] args){\n Demo my_inst = new Demo();\n my_inst = null;\n }\n}" }, { "code": null, "e": 1942, "s": 1623, "text": "They are not default class of reference object, hence need to be explicitly specified. It is generally\nused with WeakHashmap, so as to reference entry objects. Such weak references are marked for\ngarbage collection by the Java Virtual Machine. Such references are created using the\n‘java.lang.ref.WeakReference’ class." }, { "code": null, "e": 1966, "s": 1942, "text": "Let us see an example −" }, { "code": null, "e": 1977, "s": 1966, "text": " Live Demo" }, { "code": null, "e": 2372, "s": 1977, "text": "import java.lang.ref.WeakReference;\nclass Demo{\n public void display_msg(){\n System.out.println(\"Hello\");\n }\n}\npublic class Demo_sample{\n public static void main(String[] args){\n Demo inst = new Demo();\n inst.display_msg();\n WeakReference<Demo> my_weak_ref = new WeakReference<Demo>(inst);\n inst = null;\n inst = my_weak_ref.get();\n inst.display_msg();\n}" }, { "code": null, "e": 2384, "s": 2372, "text": "Hello\nHello" }, { "code": null, "e": 2823, "s": 2384, "text": "A class named Demo has a function named ‘display_msg’. This function displays a relevant message.\nIn another class named ‘Demo_sample’, the main function is defined, and an instance of Demo class\nis created. The ‘display_msg’ function is called on the instance. A weakReference to the Demo class\nis created, and the Demo insatne is assigned to null, and the function is called on it again. The\nrelevant output is displayed on the console." } ]
Apache Derby - Tools
Apache Derby provides you tools such as sysinfo, ij and, dblook. Using this tool, you can get information about Java and Derby environment. Browse through the bin folder of Derby installation directory and execute the sysinfo command as shown below − C:\Users\MY_USER>cd %DERBY_HOME%/bin C:\Derby\bin>sysinfo On executing, it gives you system information about java and derby as given below − ------------------ Java Information ------------------ Java Version: 1.8.0_101 Java Vendor: Oracle Corporation Java home: C:\Program Files\Java\jdk1.8.0_101\jre Java classpath: C:\Users\Tutorialspoint\Google Drive\Office\Derby\derby_zip\New folder\db-derby-10.12.1.1- bin\lib;C:\EXAMPLES_\Task\jars\*;C:\EXAMPLES\jars\mysql-connector-java-5.1.40- bin.jar;C:\Users\Tutorialspoint\Google Drive\Office\37.Junit Update\jars;C:\Program Files\Apache Software Foundation\Tomcat 8.5\lib\*;C:\Derby\lib\derby.jar;C:\Derby\lib\derbyclient.jar;C:\Derby\lib\derb yLocale_cs.jar;C:\Derby\lib\derbyLocale_de_DE.jar;C:\Derby\lib\derbyLocale_es.j ar;C:\Derby\lib\derbyLocale_fr.jar;C:\Derby\lib\derbyLocale_hu.jar;C:\Derby\lib \derbyLocale_it.jar;C:\Derby\lib\derbyLocale_ja_JP.jar;C:\Derby\lib\derbyLocale _ko_KR.jar;C:\Derby\lib\derbyLocale_pl.jar;C:\Derby\lib\derbyLocale_pt_BR.jar;C :\Derby\lib\derbyLocale_ru.jar;C:\Derby\lib\derbyLocale_zh_CN.jar;C:\Derby\lib\ derbyLocale_zh_TW.jar;C:\Derby\lib\derbynet.jar;C:\Derby\lib\derbyoptionaltools .jar;C:\Derby\lib\derbyrun.jar;C:\Derby\lib\derbytools.jar;;C:\Derby/lib/derby. jar;C:\Derby/lib/derbynet.jar;C:\Derby/lib/derbyclient.jar;C:\Derby/lib/derbyto ols.jar;C:\Derby/lib/derbyoptionaltools.jar OS name: Windows 10 OS architecture: amd64 OS version: 10.0 Java user name: Tutorialspoint Java user home: C:\Users\Tutorialspoint Java user dir: C:\Derby\bin java.specification.name: Java Platform API Specification java.specification.version: 1.8 java.runtime.version: 1.8.0_101-b13 --------- Derby Information -------- [C:\Derby\lib\derby.jar] 10.14.2.0 - (1828579) [C:\Derby\lib\derbytools.jar] 10.14.2.0 - (1828579) [C:\Derby\lib\derbynet.jar] 10.14.2.0 - (1828579) [C:\Derby\lib\derbyclient.jar] 10.14.2.0 - (1828579) [C:\Derby\lib\derbyoptionaltools.jar] 10.14.2.0 - (1828579) ------------------------------------------------------ ----------------- Locale Information ----------------- Current Locale : [English/United States [en_US]] Found support for locale: [cs] version: 10.14.2.0 - (1828579) Found support for locale: [de_DE] version: 10.14.2.0 - (1828579) Found support for locale: [es] version: 10.14.2.0 - (1828579) Found support for locale: [fr] version: 10.14.2.0 - (1828579) Found support for locale: [hu] version: 10.14.2.0 - (1828579) Found support for locale: [it] version: 10.14.2.0 - (1828579) Found support for locale: [ja_JP] version: 10.14.2.0 - (1828579) Found support for locale: [ko_KR] version: 10.14.2.0 - (1828579) Found support for locale: [pl] version: 10.14.2.0 - (1828579) Found support for locale: [pt_BR] version: 10.14.2.0 - (1828579) Found support for locale: [ru] version: 10.14.2.0 - (1828579) Found support for locale: [zh_CN] version: 10.14.2.0 - (1828579) Found support for locale: [zh_TW] version: 10.14.2.0 - (1828579) ------------------------------------------------------ ------------------------------------------------------ Using this tool, you can run scripts and queries of apache Derby. Browse through the bin folder of Derby installation directory and execute the ij command as shown below − C:\Users\MY_USER>cd %DERBY_HOME%/bin C:\Derby\bin>ij This will give you ij shell where you can execute derby command and scripts, as shown below − ij version 10.14 ij> Using help command, you can get the list of commands supported by this shell. C:\Derby\bin>cd %DERBY_HOME%/bin C:\Derby\bin>ij ij version 10.14 ij> help; Supported commands include: PROTOCOL 'JDBC protocol' [ AS ident ]; -- sets a default or named protocol DRIVER 'class for driver'; -- loads the named class CONNECT 'url for database' [ PROTOCOL namedProtocol ] [ AS connectionName ]; -- connects to database URL -- and may assign identifier SET CONNECTION connectionName; -- switches to the specified connection SHOW CONNECTIONS; -- lists all connections AUTOCOMMIT [ ON | OFF ]; -- sets autocommit mode for the connection DISCONNECT [ CURRENT | connectionName | ALL ]; -- drop current, named, or all connections; -- the default is CURRENT SHOW SCHEMAS; -- lists all schemas in the current database SHOW [ TABLES | VIEWS | PROCEDURES | FUNCTIONS | SYNONYMS ] { IN schema }; -- lists tables, views, procedures, functions or synonyms SHOW INDEXES { IN schema | FROM table }; -- lists indexes in a schema, or for a table SHOW ROLES; -- lists all defined roles in the database, sorted SHOW ENABLED_ROLES; -- lists the enabled roles for the current -- connection (to see current role use -- VALUES CURRENT_ROLE), sorted SHOW SETTABLE_ROLES; -- lists the roles which can be set for the -- current connection, sorted DESCRIBE name; -- lists columns in the named table COMMIT; -- commits the current transaction ROLLBACK; -- rolls back the current transaction PREPARE name AS 'SQL-J text'; -- prepares the SQL-J text EXECUTE { name | 'SQL-J text' } [ USING { name | 'SQL-J text' } ] ; -- executes the statement with parameter -- values from the USING result set row REMOVE name; -- removes the named previously prepared statement RUN 'filename'; -- run commands from the named file ELAPSEDTIME [ ON | OFF ]; -- sets elapsed time mode for ij MAXIMUMDISPLAYWIDTH integerValue; -- sets the maximum display width for -- each column to integerValue ASYNC name 'SQL-J text'; -- run the command in another thread WAIT FOR name; -- wait for result of ASYNC'd command HOLDFORCONNECTION; -- sets holdability for a connection to HOLD -- (i.e. ResultSet.HOLD_CURSORS_OVER_COMMIT) NOHOLDFORCONNECTION; -- sets holdability for a connection to NO HOLD -- (i.e. ResultSet.CLOSE_CURSORS_AT_COMMIT) GET [SCROLL INSENSITIVE] [WITH { HOLD | NOHOLD }] CURSOR name AS 'SQL-J query'; -- gets a cursor (JDBC result set) on the query -- the default is a forward-only cursor with holdability NEXT name; -- gets the next row from the named cursor FIRST name; -- gets the first row from the named scroll cursor LAST name; -- gets the last row from the named scroll cursor PREVIOUS name; -- gets the previous row from the named scroll cursor ABSOLUTE integer name; -- positions the named scroll cursor at the absolute row number -- (A negative number denotes position from the last row.) RELATIVE integer name; -- positions the named scroll cursor relative to the current row -- (integer is number of rows) AFTER LAST name; -- positions the named scroll cursor after the last row BEFORE FIRST name; -- positions the named scroll cursor before the first row GETCURRENTROWNUMBER name; -- returns the row number for the current position of the named scroll cursor -- (0 is returned when the cursor is not positioned on a row.) CLOSE name; -- closes the named cursor LOCALIZEDDISPLAY [ ON | OFF ]; -- controls locale sensitive data representation EXIT; -- exits ij HELP; -- shows this message Any unrecognized commands are treated as potential SQL-J commands and executed directly. This tool is used to generate Data Definition Language. Browse through the bin folder of Derby installation directory and execute the dblook command as shown below − C:\Users\MY_USER>cd %DERBY_HOME%/bin C:\Derby\bin>dblook -d myURL Where, myURL is the connection URL of the database for which you need to generate DDL. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2245, "s": 2180, "text": "Apache Derby provides you tools such as sysinfo, ij and, dblook." }, { "code": null, "e": 2320, "s": 2245, "text": "Using this tool, you can get information about Java and Derby environment." }, { "code": null, "e": 2431, "s": 2320, "text": "Browse through the bin folder of Derby installation directory and execute the sysinfo command as shown below −" }, { "code": null, "e": 2490, "s": 2431, "text": "C:\\Users\\MY_USER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>sysinfo\n" }, { "code": null, "e": 2574, "s": 2490, "text": "On executing, it gives you system information about java and derby as given below −" }, { "code": null, "e": 5499, "s": 2574, "text": "------------------ Java Information ------------------\nJava Version: 1.8.0_101\nJava Vendor: Oracle Corporation\nJava home: C:\\Program Files\\Java\\jdk1.8.0_101\\jre\nJava classpath: C:\\Users\\Tutorialspoint\\Google\nDrive\\Office\\Derby\\derby_zip\\New folder\\db-derby-10.12.1.1-\nbin\\lib;C:\\EXAMPLES_\\Task\\jars\\*;C:\\EXAMPLES\\jars\\mysql-connector-java-5.1.40-\nbin.jar;C:\\Users\\Tutorialspoint\\Google Drive\\Office\\37.Junit\nUpdate\\jars;C:\\Program Files\\Apache Software Foundation\\Tomcat\n8.5\\lib\\*;C:\\Derby\\lib\\derby.jar;C:\\Derby\\lib\\derbyclient.jar;C:\\Derby\\lib\\derb\nyLocale_cs.jar;C:\\Derby\\lib\\derbyLocale_de_DE.jar;C:\\Derby\\lib\\derbyLocale_es.j\nar;C:\\Derby\\lib\\derbyLocale_fr.jar;C:\\Derby\\lib\\derbyLocale_hu.jar;C:\\Derby\\lib\n\\derbyLocale_it.jar;C:\\Derby\\lib\\derbyLocale_ja_JP.jar;C:\\Derby\\lib\\derbyLocale\n_ko_KR.jar;C:\\Derby\\lib\\derbyLocale_pl.jar;C:\\Derby\\lib\\derbyLocale_pt_BR.jar;C\n:\\Derby\\lib\\derbyLocale_ru.jar;C:\\Derby\\lib\\derbyLocale_zh_CN.jar;C:\\Derby\\lib\\\nderbyLocale_zh_TW.jar;C:\\Derby\\lib\\derbynet.jar;C:\\Derby\\lib\\derbyoptionaltools\n.jar;C:\\Derby\\lib\\derbyrun.jar;C:\\Derby\\lib\\derbytools.jar;;C:\\Derby/lib/derby.\njar;C:\\Derby/lib/derbynet.jar;C:\\Derby/lib/derbyclient.jar;C:\\Derby/lib/derbyto\nols.jar;C:\\Derby/lib/derbyoptionaltools.jar\nOS name: Windows 10\nOS architecture: amd64\nOS version: 10.0\nJava user name: Tutorialspoint\nJava user home: C:\\Users\\Tutorialspoint\nJava user dir: C:\\Derby\\bin\njava.specification.name: Java Platform API Specification\njava.specification.version: 1.8\njava.runtime.version: 1.8.0_101-b13\n--------- Derby Information --------\n[C:\\Derby\\lib\\derby.jar] 10.14.2.0 - (1828579)\n[C:\\Derby\\lib\\derbytools.jar] 10.14.2.0 - (1828579)\n[C:\\Derby\\lib\\derbynet.jar] 10.14.2.0 - (1828579)\n[C:\\Derby\\lib\\derbyclient.jar] 10.14.2.0 - (1828579)\n[C:\\Derby\\lib\\derbyoptionaltools.jar] 10.14.2.0 - (1828579)\n------------------------------------------------------\n----------------- Locale Information -----------------\nCurrent Locale : [English/United States [en_US]]\nFound support for locale: [cs]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [de_DE]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [es]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [fr]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [hu]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [it]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [ja_JP]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [ko_KR]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [pl]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [pt_BR]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [ru]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [zh_CN]\n version: 10.14.2.0 - (1828579)\nFound support for locale: [zh_TW]\n version: 10.14.2.0 - (1828579)\n------------------------------------------------------\n------------------------------------------------------\n" }, { "code": null, "e": 5565, "s": 5499, "text": "Using this tool, you can run scripts and queries of apache Derby." }, { "code": null, "e": 5671, "s": 5565, "text": "Browse through the bin folder of Derby installation directory and execute the ij command\nas shown below −" }, { "code": null, "e": 5725, "s": 5671, "text": "C:\\Users\\MY_USER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>ij\n" }, { "code": null, "e": 5819, "s": 5725, "text": "This will give you ij shell where you can execute derby command and scripts, as shown\nbelow −" }, { "code": null, "e": 5841, "s": 5819, "text": "ij version 10.14\nij>\n" }, { "code": null, "e": 5919, "s": 5841, "text": "Using help command, you can get the list of commands supported by this shell." }, { "code": null, "e": 9443, "s": 5919, "text": "C:\\Derby\\bin>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>ij\nij version 10.14\nij> help;\nSupported commands include:\n PROTOCOL 'JDBC protocol' [ AS ident ];\n -- sets a default or named protocol\n DRIVER 'class for driver'; -- loads the named class\n CONNECT 'url for database' [ PROTOCOL namedProtocol ] [ AS connectionName ];\n -- connects to database URL\n -- and may assign identifier\n SET CONNECTION connectionName; -- switches to the specified connection\n SHOW CONNECTIONS; -- lists all connections\n AUTOCOMMIT [ ON | OFF ]; -- sets autocommit mode for the connection\n DISCONNECT [ CURRENT | connectionName | ALL ];\n -- drop current, named, or all connections;\n-- the default is CURRENT\n SHOW SCHEMAS; -- lists all schemas in the current database\n SHOW [ TABLES | VIEWS | PROCEDURES | FUNCTIONS | SYNONYMS ] { IN schema };\n -- lists tables, views, procedures, functions or\nsynonyms\n SHOW INDEXES { IN schema | FROM table };\n -- lists indexes in a schema, or for a table\n SHOW ROLES; -- lists all defined roles in the database,\nsorted\n SHOW ENABLED_ROLES; -- lists the enabled roles for the current\n -- connection (to see current role use\n -- VALUES CURRENT_ROLE), sorted\n SHOW SETTABLE_ROLES; -- lists the roles which can be set for the\n -- current connection, sorted\n DESCRIBE name; -- lists columns in the named table\n COMMIT; -- commits the current transaction\n ROLLBACK; -- rolls back the current transaction\n PREPARE name AS 'SQL-J text'; -- prepares the SQL-J text\n EXECUTE { name | 'SQL-J text' } [ USING { name | 'SQL-J text' } ] ;\n -- executes the statement with parameter\n-- values from the USING result set row\n REMOVE name; -- removes the named previously prepared\nstatement\n RUN 'filename'; -- run commands from the named file\n ELAPSEDTIME [ ON | OFF ]; -- sets elapsed time mode for ij\n MAXIMUMDISPLAYWIDTH integerValue;\n -- sets the maximum display width for\n-- each column to integerValue\n ASYNC name 'SQL-J text'; -- run the command in another thread\n WAIT FOR name; -- wait for result of ASYNC'd command\n HOLDFORCONNECTION; -- sets holdability for a connection to HOLD\n -- (i.e. ResultSet.HOLD_CURSORS_OVER_COMMIT)\n NOHOLDFORCONNECTION; -- sets holdability for a connection to NO HOLD\n -- (i.e. ResultSet.CLOSE_CURSORS_AT_COMMIT)\n GET [SCROLL INSENSITIVE] [WITH { HOLD | NOHOLD }] CURSOR name AS 'SQL-J\nquery';\n -- gets a cursor (JDBC result set) on the query\n-- the default is a forward-only cursor with\nholdability\n NEXT name; -- gets the next row from the named cursor\n FIRST name; -- gets the first row from the named scroll\ncursor\n LAST name; -- gets the last row from the named scroll\ncursor\n PREVIOUS name; -- gets the previous row from the named scroll\ncursor\n ABSOLUTE integer name; -- positions the named scroll cursor at the\nabsolute row number\n -- (A negative number denotes position from the\nlast row.)\n RELATIVE integer name; -- positions the named scroll cursor relative to\nthe current row\n -- (integer is number of rows)\n AFTER LAST name; -- positions the named scroll cursor after the\nlast row\n BEFORE FIRST name; -- positions the named scroll cursor before the\nfirst row\n GETCURRENTROWNUMBER name; -- returns the row number for the current\nposition of the named scroll cursor\n -- (0 is returned when the cursor is not\npositioned on a row.)\n CLOSE name; -- closes the named cursor\n LOCALIZEDDISPLAY [ ON | OFF ];\n -- controls locale sensitive data representation\n EXIT; -- exits ij\n HELP; -- shows this message\nAny unrecognized commands are treated as potential SQL-J commands and executed\ndirectly.\n" }, { "code": null, "e": 9499, "s": 9443, "text": "This tool is used to generate Data Definition Language." }, { "code": null, "e": 9609, "s": 9499, "text": "Browse through the bin folder of Derby installation directory and execute the dblook command as shown below −" }, { "code": null, "e": 9676, "s": 9609, "text": "C:\\Users\\MY_USER>cd %DERBY_HOME%/bin\nC:\\Derby\\bin>dblook -d myURL\n" }, { "code": null, "e": 9763, "s": 9676, "text": "Where, myURL is the connection URL of the database for which you need to generate DDL." }, { "code": null, "e": 9798, "s": 9763, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9817, "s": 9798, "text": " Arnab Chakraborty" }, { "code": null, "e": 9852, "s": 9817, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9873, "s": 9852, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 9906, "s": 9873, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 9919, "s": 9906, "text": " Nilay Mehta" }, { "code": null, "e": 9954, "s": 9919, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9972, "s": 9954, "text": " Bigdata Engineer" }, { "code": null, "e": 10005, "s": 9972, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 10023, "s": 10005, "text": " Bigdata Engineer" }, { "code": null, "e": 10056, "s": 10023, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 10074, "s": 10056, "text": " Bigdata Engineer" }, { "code": null, "e": 10081, "s": 10074, "text": " Print" }, { "code": null, "e": 10092, "s": 10081, "text": " Add Notes" } ]
Chunking an array in JavaScript
We are required to write a function chunk() that takes in an array arr of string / number literals as the first argument and a number n as second argument. We are required to return an array of n subarrays, each of which contains at most arr.length / n elements. And the distribution of elements should be like this − The first element goes in the first subarray, second in second, third in third and so on. Once we have one element in each subarray, we again start with filling the first subarray with its second element. Similarly, when all subarrays have two elements only after that we fill the third element in the first array and so on. For example − // if the input array is: const input = [1, 2, 3, 4, 5, 6]; //then the output should be: const output = [ [1, 4], [2, 5], [3, 6] ]; Let’s write the code for this function, we will Array.prototype.reduce() method over the original array to construct the desired array. The code for this will be − const input = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const chunk = (arr, size) => { return arr.reduce((acc, val, ind) => { const subIndex = ind % size; if(!Array.isArray(acc[subIndex])){ acc[subIndex] = [val]; } else { acc[subIndex].push(val); }; return acc; }, []); }; console.log(chunk(input, 4)); The output in the console will be − [ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]
[ { "code": null, "e": 1218, "s": 1062, "text": "We are required to write a function chunk() that takes in an array arr of string / number literals\nas the first argument and a number n as second argument." }, { "code": null, "e": 1380, "s": 1218, "text": "We are required to return an array of n subarrays, each of which contains at most arr.length / n\nelements. And the distribution of elements should be like this −" }, { "code": null, "e": 1705, "s": 1380, "text": "The first element goes in the first subarray, second in second, third in third and so on. Once we\nhave one element in each subarray, we again start with filling the first subarray with its second\nelement. Similarly, when all subarrays have two elements only after that we fill the third element\nin the first array and so on." }, { "code": null, "e": 1719, "s": 1705, "text": "For example −" }, { "code": null, "e": 1860, "s": 1719, "text": "// if the input array is:\nconst input = [1, 2, 3, 4, 5, 6];\n//then the output should be:\nconst output = [\n [1, 4],\n [2, 5],\n [3, 6]\n];" }, { "code": null, "e": 2024, "s": 1860, "text": "Let’s write the code for this function, we will Array.prototype.reduce() method over the original\narray to construct the desired array. The code for this will be −" }, { "code": null, "e": 2368, "s": 2024, "text": "const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];\nconst chunk = (arr, size) => {\n return arr.reduce((acc, val, ind) => {\n const subIndex = ind % size;\n if(!Array.isArray(acc[subIndex])){\n acc[subIndex] = [val];\n } else {\n acc[subIndex].push(val);\n };\n return acc;\n }, []);\n};\nconsole.log(chunk(input, 4));" }, { "code": null, "e": 2404, "s": 2368, "text": "The output in the console will be −" }, { "code": null, "e": 2450, "s": 2404, "text": "[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]" } ]
Fetch API - GeeksforGeeks
27 Oct, 2021 For long XMLHttpRequest is being used by web developer’s trusted “amigo”. XMLHttpRequest has enabled ajax and a whole new kind of interactive exposure. However, it is being slowly succeeded by the Fetch API. These both deliver the same work i.e. fetching data asynchronously from a different network, but the Fetch API is Promise based. This provides a more cleaner and more concise syntax.The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve response of the request. Basic Syntax: fetch(url) //call the fetch function passing the url of the API as a parameter .then(function(){ //code for handling data from API }); .catch(function(){ //code when the server returns any error }); NOTE: By default, fetch() will not send or receive any cookies from the server, resulting in unauthenticated requests.Below are list of methods which can be used when we get a response on what we want to do with the information: clone(): for creating a clone of response.redirect(): for creating strong response with different url.arrayBuffer(): we return a Promise that resolves with an ArrayBuffer.formData(): also returns a Promise that resolves with a FormDataObject.blob(): same as above only that resolves with a blob.text(): this resolves with a string.json(): it resolves promise with JSON. clone(): for creating a clone of response. redirect(): for creating strong response with different url. arrayBuffer(): we return a Promise that resolves with an ArrayBuffer. formData(): also returns a Promise that resolves with a FormDataObject. blob(): same as above only that resolves with a blob. text(): this resolves with a string. json(): it resolves promise with JSON. Request: A Request object represents the request part of a fetch call. By passing fetch a Request you can make advanced and customized requests: method: GET, POST, PUTurl: URL of the requestheaders: Headers objectreferrer: referrer of the requestmode: cors, no-cors, same-origincredentials: should cookies go with the request? omit, same-origincache: cache mode (default, reload, no-cache) method: GET, POST, PUT url: URL of the request headers: Headers object referrer: referrer of the request mode: cors, no-cors, same-origin credentials: should cookies go with the request? omit, same-origin cache: cache mode (default, reload, no-cache) LOADING JSON We cannot block the user interface waiting until the request completes. That is why fetch() method returns a Promise. A promise is actually an object which represents a future result. The then() method is used to wait for the response from the server-side and log it to the console.Below code snippet explains the above logic: javascript fetch('https://www.reddit.com/r/javascript/top/.json?limit=5').then(res=>res.json()).then(json=>console.log(json)); Async...await This provides a more concise way to process Promises. Its functionality is that we can mark a function as async, then wait for the promise to finish with the await, and access the result as a normal object.Simple example demonstrating how async...await can be used: javascript async function demo(subject){ const URL='https://www.reddit.com/r/javascript/top/.json?limit=5'; const Res= fetch(URL); const response= await Res; const json= await response.json(); console.log(json);}demo('javascript'); HANDLING ERRORS: What if we ask the server for a non-existing resource that requires permissions/authorization? With fetch(), we can handle application-level errors like 404 responses.Although Fetch API is superseding XMLHttpRequest still a beginner needs to learn XMLHttpRequest to make more effective use of Fetch API.Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API rajeev0719singh Picked Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ? Node.js fs.readFileSync() Method File uploading in React.js How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24516, "s": 24488, "text": "\n27 Oct, 2021" }, { "code": null, "e": 25119, "s": 24516, "text": "For long XMLHttpRequest is being used by web developer’s trusted “amigo”. XMLHttpRequest has enabled ajax and a whole new kind of interactive exposure. However, it is being slowly succeeded by the Fetch API. These both deliver the same work i.e. fetching data asynchronously from a different network, but the Fetch API is Promise based. This provides a more cleaner and more concise syntax.The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve response of the request. Basic Syntax: " }, { "code": null, "e": 25323, "s": 25119, "text": " fetch(url) //call the fetch function passing the url of the API as a parameter\n.then(function(){\n //code for handling data from API\n});\n.catch(function(){\n //code when the server returns any error\n});" }, { "code": null, "e": 25554, "s": 25323, "text": "NOTE: By default, fetch() will not send or receive any cookies from the server, resulting in unauthenticated requests.Below are list of methods which can be used when we get a response on what we want to do with the information: " }, { "code": null, "e": 25924, "s": 25554, "text": "clone(): for creating a clone of response.redirect(): for creating strong response with different url.arrayBuffer(): we return a Promise that resolves with an ArrayBuffer.formData(): also returns a Promise that resolves with a FormDataObject.blob(): same as above only that resolves with a blob.text(): this resolves with a string.json(): it resolves promise with JSON." }, { "code": null, "e": 25967, "s": 25924, "text": "clone(): for creating a clone of response." }, { "code": null, "e": 26028, "s": 25967, "text": "redirect(): for creating strong response with different url." }, { "code": null, "e": 26098, "s": 26028, "text": "arrayBuffer(): we return a Promise that resolves with an ArrayBuffer." }, { "code": null, "e": 26170, "s": 26098, "text": "formData(): also returns a Promise that resolves with a FormDataObject." }, { "code": null, "e": 26224, "s": 26170, "text": "blob(): same as above only that resolves with a blob." }, { "code": null, "e": 26261, "s": 26224, "text": "text(): this resolves with a string." }, { "code": null, "e": 26300, "s": 26261, "text": "json(): it resolves promise with JSON." }, { "code": null, "e": 26447, "s": 26300, "text": "Request: A Request object represents the request part of a fetch call. By passing fetch a Request you can make advanced and customized requests: " }, { "code": null, "e": 26692, "s": 26447, "text": "method: GET, POST, PUTurl: URL of the requestheaders: Headers objectreferrer: referrer of the requestmode: cors, no-cors, same-origincredentials: should cookies go with the request? omit, same-origincache: cache mode (default, reload, no-cache)" }, { "code": null, "e": 26715, "s": 26692, "text": "method: GET, POST, PUT" }, { "code": null, "e": 26739, "s": 26715, "text": "url: URL of the request" }, { "code": null, "e": 26763, "s": 26739, "text": "headers: Headers object" }, { "code": null, "e": 26797, "s": 26763, "text": "referrer: referrer of the request" }, { "code": null, "e": 26830, "s": 26797, "text": "mode: cors, no-cors, same-origin" }, { "code": null, "e": 26897, "s": 26830, "text": "credentials: should cookies go with the request? omit, same-origin" }, { "code": null, "e": 26943, "s": 26897, "text": "cache: cache mode (default, reload, no-cache)" }, { "code": null, "e": 27285, "s": 26943, "text": "LOADING JSON We cannot block the user interface waiting until the request completes. That is why fetch() method returns a Promise. A promise is actually an object which represents a future result. The then() method is used to wait for the response from the server-side and log it to the console.Below code snippet explains the above logic: " }, { "code": null, "e": 27296, "s": 27285, "text": "javascript" }, { "code": "fetch('https://www.reddit.com/r/javascript/top/.json?limit=5').then(res=>res.json()).then(json=>console.log(json));", "e": 27412, "s": 27296, "text": null }, { "code": null, "e": 27694, "s": 27412, "text": "Async...await This provides a more concise way to process Promises. Its functionality is that we can mark a function as async, then wait for the promise to finish with the await, and access the result as a normal object.Simple example demonstrating how async...await can be used: " }, { "code": null, "e": 27705, "s": 27694, "text": "javascript" }, { "code": "async function demo(subject){ const URL='https://www.reddit.com/r/javascript/top/.json?limit=5'; const Res= fetch(URL); const response= await Res; const json= await response.json(); console.log(json);}demo('javascript');", "e": 27936, "s": 27705, "text": null }, { "code": null, "e": 28327, "s": 27936, "text": "HANDLING ERRORS: What if we ask the server for a non-existing resource that requires permissions/authorization? With fetch(), we can handle application-level errors like 404 responses.Although Fetch API is superseding XMLHttpRequest still a beginner needs to learn XMLHttpRequest to make more effective use of Fetch API.Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API " }, { "code": null, "e": 28343, "s": 28327, "text": "rajeev0719singh" }, { "code": null, "e": 28350, "s": 28343, "text": "Picked" }, { "code": null, "e": 28367, "s": 28350, "text": "Web Technologies" }, { "code": null, "e": 28465, "s": 28367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28474, "s": 28465, "text": "Comments" }, { "code": null, "e": 28487, "s": 28474, "text": "Old Comments" }, { "code": null, "e": 28529, "s": 28487, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28572, "s": 28529, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28617, "s": 28572, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28678, "s": 28617, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28750, "s": 28678, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28808, "s": 28750, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 28868, "s": 28808, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 28901, "s": 28868, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 28928, "s": 28901, "text": "File uploading in React.js" } ]
Basic Input and Output in C - GeeksforGeeks
12 Jul, 2021 C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output. The scanf() method, in C, reads the value from the console as per the type specified. Syntax: scanf(“%X”, &variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory. The printf() method, in C, prints the value passed as the parameter to it, on the console screen. Syntax: printf(“%X”, variableOfXType); where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory. The basic type in C includes types like int, float, char, etc. Inorder to input or output the specific type, the X in the above syntax is changed with the specific format specifier of that type. The Syntax for input and output for these are: Integer:Input: scanf("%d", &intVariable); Output: printf("%d", intVariable); Input: scanf("%d", &intVariable); Output: printf("%d", intVariable); Float:Input: scanf("%f", &floatVariable); Output: printf("%f", floatVariable); Input: scanf("%f", &floatVariable); Output: printf("%f", floatVariable); Character:Input: scanf("%c", &charVariable); Output: printf("%c", charVariable); Input: scanf("%c", &charVariable); Output: printf("%c", charVariable); Please refer Format specifiers in C for more examples. // C program to show input and output #include <stdio.h> int main(){ // Declare the variables int num; char ch; float f; // --- Integer --- // Input the integer printf("Enter the integer: "); scanf("%d", &num); // Output the integer printf("\nEntered integer is: %d", num); // --- Float --- // Input the float printf("\n\nEnter the float: "); scanf("%f", &f); // Output the float printf("\nEntered float is: %f", f); // --- Character --- // Input the Character printf("\n\nEnter the Character: "); scanf("%c", &ch); // Output the Character printf("\nEntered integer is: %c", ch); return 0;} Enter the integer: 10 Entered integer is: 10 Enter the float: 2.5 Entered float is: 2.500000 Enter the Character: A Entered Character is: A The advanced type in C includes type like String. In order to input or output the string type, the X in the above syntax is changed with the %s format specifier. The Syntax for input and output for String is: Input: scanf("%s", stringVariable); Output: printf("%s", stringVariable); Example: // C program to show input and output #include <stdio.h> int main(){ // Declare string variable // as character array char str[50]; // --- String --- // To read a word // Input the Word printf("Enter the Word: "); scanf("%s\n", str); // Output the Word printf("\nEntered Word is: %s", str); // --- String --- // To read a Sentence // Input the Sentence printf("\n\nEnter the Sentence: "); scanf("%[^\n]\ns", str); // Output the String printf("\nEntered Sentence is: %s", str); return 0;} Enter the Word: GeeksForGeeks Entered Word is: GeeksForGeeks Enter the Sentence: Geeks For Geeks Entered Sentence is: Geeks For Geeks c-input-output C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Arrow operator -> in C/C++ with Examples Understanding "extern" keyword in C Storage Classes in C Smart Pointers in C++ and How to Use Them Switch Statement in C/C++
[ { "code": null, "e": 24233, "s": 24205, "text": "\n12 Jul, 2021" }, { "code": null, "e": 24398, "s": 24233, "text": "C language has standard libraries that allow input and output in a program. The stdio.h or standard input output library in C that has methods for input and output." }, { "code": null, "e": 24484, "s": 24398, "text": "The scanf() method, in C, reads the value from the console as per the type specified." }, { "code": null, "e": 24492, "s": 24484, "text": "Syntax:" }, { "code": null, "e": 24523, "s": 24492, "text": "scanf(“%X”, &variableOfXType);" }, { "code": null, "e": 24630, "s": 24523, "text": "where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable" }, { "code": null, "e": 24634, "s": 24630, "text": "and" }, { "code": null, "e": 24772, "s": 24634, "text": "& is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory." }, { "code": null, "e": 24870, "s": 24772, "text": "The printf() method, in C, prints the value passed as the parameter to it, on the console screen." }, { "code": null, "e": 24878, "s": 24870, "text": "Syntax:" }, { "code": null, "e": 24909, "s": 24878, "text": "printf(“%X”, variableOfXType);" }, { "code": null, "e": 25016, "s": 24909, "text": "where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable" }, { "code": null, "e": 25020, "s": 25016, "text": "and" }, { "code": null, "e": 25158, "s": 25020, "text": "& is the address operator in C, which tells the compiler to change the real value of this variable, stored at this address in the memory." }, { "code": null, "e": 25353, "s": 25158, "text": "The basic type in C includes types like int, float, char, etc. Inorder to input or output the specific type, the X in the above syntax is changed with the specific format specifier of that type." }, { "code": null, "e": 25400, "s": 25353, "text": "The Syntax for input and output for these are:" }, { "code": null, "e": 25478, "s": 25400, "text": "Integer:Input: scanf(\"%d\", &intVariable);\nOutput: printf(\"%d\", intVariable);\n" }, { "code": null, "e": 25548, "s": 25478, "text": "Input: scanf(\"%d\", &intVariable);\nOutput: printf(\"%d\", intVariable);\n" }, { "code": null, "e": 25628, "s": 25548, "text": "Float:Input: scanf(\"%f\", &floatVariable);\nOutput: printf(\"%f\", floatVariable);\n" }, { "code": null, "e": 25702, "s": 25628, "text": "Input: scanf(\"%f\", &floatVariable);\nOutput: printf(\"%f\", floatVariable);\n" }, { "code": null, "e": 25784, "s": 25702, "text": "Character:Input: scanf(\"%c\", &charVariable);\nOutput: printf(\"%c\", charVariable);\n" }, { "code": null, "e": 25856, "s": 25784, "text": "Input: scanf(\"%c\", &charVariable);\nOutput: printf(\"%c\", charVariable);\n" }, { "code": null, "e": 25911, "s": 25856, "text": "Please refer Format specifiers in C for more examples." }, { "code": "// C program to show input and output #include <stdio.h> int main(){ // Declare the variables int num; char ch; float f; // --- Integer --- // Input the integer printf(\"Enter the integer: \"); scanf(\"%d\", &num); // Output the integer printf(\"\\nEntered integer is: %d\", num); // --- Float --- // Input the float printf(\"\\n\\nEnter the float: \"); scanf(\"%f\", &f); // Output the float printf(\"\\nEntered float is: %f\", f); // --- Character --- // Input the Character printf(\"\\n\\nEnter the Character: \"); scanf(\"%c\", &ch); // Output the Character printf(\"\\nEntered integer is: %c\", ch); return 0;}", "e": 26595, "s": 25911, "text": null }, { "code": null, "e": 26738, "s": 26595, "text": "Enter the integer: 10\nEntered integer is: 10\n\nEnter the float: 2.5\nEntered float is: 2.500000\n\nEnter the Character: A\nEntered Character is: A\n" }, { "code": null, "e": 26900, "s": 26738, "text": "The advanced type in C includes type like String. In order to input or output the string type, the X in the above syntax is changed with the %s format specifier." }, { "code": null, "e": 26947, "s": 26900, "text": "The Syntax for input and output for String is:" }, { "code": null, "e": 27022, "s": 26947, "text": "Input: scanf(\"%s\", stringVariable);\nOutput: printf(\"%s\", stringVariable);\n" }, { "code": null, "e": 27031, "s": 27022, "text": "Example:" }, { "code": "// C program to show input and output #include <stdio.h> int main(){ // Declare string variable // as character array char str[50]; // --- String --- // To read a word // Input the Word printf(\"Enter the Word: \"); scanf(\"%s\\n\", str); // Output the Word printf(\"\\nEntered Word is: %s\", str); // --- String --- // To read a Sentence // Input the Sentence printf(\"\\n\\nEnter the Sentence: \"); scanf(\"%[^\\n]\\ns\", str); // Output the String printf(\"\\nEntered Sentence is: %s\", str); return 0;}", "e": 27591, "s": 27031, "text": null }, { "code": null, "e": 27727, "s": 27591, "text": "Enter the Word: GeeksForGeeks\nEntered Word is: GeeksForGeeks\n\nEnter the Sentence: Geeks For Geeks\nEntered Sentence is: Geeks For Geeks\n" }, { "code": null, "e": 27742, "s": 27727, "text": "c-input-output" }, { "code": null, "e": 27753, "s": 27742, "text": "C Language" }, { "code": null, "e": 27851, "s": 27753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27860, "s": 27851, "text": "Comments" }, { "code": null, "e": 27873, "s": 27860, "text": "Old Comments" }, { "code": null, "e": 27911, "s": 27873, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27937, "s": 27911, "text": "Exception Handling in C++" }, { "code": null, "e": 27957, "s": 27937, "text": "Multithreading in C" }, { "code": null, "e": 27979, "s": 27957, "text": "'this' pointer in C++" }, { "code": null, "e": 28017, "s": 27979, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28058, "s": 28017, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28094, "s": 28058, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 28115, "s": 28094, "text": "Storage Classes in C" }, { "code": null, "e": 28157, "s": 28115, "text": "Smart Pointers in C++ and How to Use Them" } ]
Context api in React.js
The React context api is safe to use in production with the version 16.3 or latest. The reason for adding context api is to avoid the passing of props if there is a chain of children components. Without the use of context api, we have to pass the props through all the intermediate components. The other alternative solution is to use third party library such as Redux for maintaining a central store. App.js → props for books → BookList.js → passing the books as props again → Book.js With the increase in number of children components, the chain of passing the props goes on. With context api, react provides a provider consumer approach to solve this issue. Creating the context: BaseContext.js import React from 'react'; // this is the same to the createStore method of Redux const BaseContext = React.createContext(); export default BaseContext; import BaseContext from './BaseContext'; class BookProvider extends Component { state = { books: { book1: { name: 'React', price: 500 }, book2: { name: 'Angular', price: 450 } } }; render() { return ( <BaseContext.Provider value={{ books: this.state.books, incrementPrice: selectedID => { const books = Object.assign({}, this.state.books); books[selectedID].price =books[selectedID].price + 1; this.setState({ books }); }, decrementPrice: selectedID => { const books = Object.assign({}, this.state.books); books[selectedID].price =books[selectedID].price - 1; this.setState({ books }); } }} > {this.props.children} </BaseContext.Provider> ); } } class App extends Component { render() { return ( <BookProvider> <div className="App"> <header className="App-header"> <h1 className="App-title">Welcome to my book store</h1> </header> <ProductBookList /> </div> </BookProvider> ); } } In the children component, we can use the consumer − const Books = () => ( <BaseContext.Consumer> {context => ( <Fragment> <h4>Books:</h4> {Object.keys(context.books).map(bookID => ( <Car key={bookID} name={context.books[bookID].name} price={context.books[bookID].price} incrementPrice={() =>context.incrementPrice(bookID)} decrementPrice={() =>context.decrementPrice(bookID)} /> ))} </Fragment> )} </BaseContext.Consumer> ); With the use of context api we can avoid the props drilling in React children components.
[ { "code": null, "e": 1257, "s": 1062, "text": "The React context api is safe to use in production with the version 16.3 or latest. The reason for adding context api is to avoid the passing of props if there is a chain of children components." }, { "code": null, "e": 1464, "s": 1257, "text": "Without the use of context api, we have to pass the props through all the intermediate components. The other alternative solution is to use third party library such as Redux for maintaining a central store." }, { "code": null, "e": 1548, "s": 1464, "text": "App.js → props for books → BookList.js → passing the books as props again → Book.js" }, { "code": null, "e": 1640, "s": 1548, "text": "With the increase in number of children components, the chain of passing the props goes on." }, { "code": null, "e": 1723, "s": 1640, "text": "With context api, react provides a provider consumer approach to solve this issue." }, { "code": null, "e": 1913, "s": 1723, "text": "Creating the context:\nBaseContext.js\nimport React from 'react';\n// this is the same to the createStore method of Redux\nconst BaseContext = React.createContext();\nexport default BaseContext;" }, { "code": null, "e": 2934, "s": 1913, "text": "import BaseContext from './BaseContext';\nclass BookProvider extends Component {\n state = {\n books: {\n book1: { name: 'React', price: 500 },\n book2: { name: 'Angular', price: 450 }\n }\n };\n render() {\n return (\n <BaseContext.Provider\n value={{\n books: this.state.books,\n incrementPrice: selectedID => {\n const books = Object.assign({}, this.state.books);\n books[selectedID].price =books[selectedID].price + 1;\n this.setState({\n books\n });\n },\n decrementPrice: selectedID => {\n const books = Object.assign({}, this.state.books);\n books[selectedID].price =books[selectedID].price - 1;\n this.setState({\n books\n });\n }\n }}\n >\n {this.props.children}\n </BaseContext.Provider>\n );\n }\n}" }, { "code": null, "e": 3292, "s": 2934, "text": "class App extends Component {\n render() {\n return (\n <BookProvider>\n <div className=\"App\">\n <header className=\"App-header\">\n <h1 className=\"App-title\">Welcome to my book store</h1>\n </header>\n <ProductBookList />\n </div>\n </BookProvider>\n );\n }\n}" }, { "code": null, "e": 3345, "s": 3292, "text": "In the children component, we can use the consumer −" }, { "code": null, "e": 3910, "s": 3345, "text": "const Books = () => (\n <BaseContext.Consumer>\n {context => (\n <Fragment>\n <h4>Books:</h4>\n {Object.keys(context.books).map(bookID => (\n <Car\n key={bookID}\n name={context.books[bookID].name}\n price={context.books[bookID].price}\n incrementPrice={() =>context.incrementPrice(bookID)}\n decrementPrice={() =>context.decrementPrice(bookID)}\n />\n ))}\n </Fragment>\n )}\n </BaseContext.Consumer>\n);" }, { "code": null, "e": 4000, "s": 3910, "text": "With the use of context api we can avoid the props drilling in React children components." } ]
ASP.NET Core - Project.Json
In this chapter, we will discuss the project.json file. This file is using JavaScript object notation to store configuration information and it is this file that is really the heart of a .NET application. Without this file, you would not have an ASP.NET Core project. Here, we will discuss some of the most important features of this file. Let us double-click on the project.json file. Currently, the default code implementation in project.json file is as follows − { "dependencies": { "Microsoft.NETCore.App": { "version": "1.0.0", "type": "platform" }, "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0" }, "tools": { "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final" }, "frameworks": { "netcoreapp1.0": { "imports": ["dotnet5.6", "portable-net45+win8"] } }, "buildOptions": { "emitEntryPoint": true, "preserveCompilationContext": true }, "runtimeOptions": { "configProperties": { "System.GC.Server": true } }, "publishOptions": { "include": ["wwwroot", "web.config" ] }, "scripts": { "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ] } } As we see, we have version information at the top of this file. This is the version number your application will use when you build it. The version is 1.0.0, but the most important part of this file is the dependencies. The version is 1.0.0, but the most important part of this file is the dependencies. If your application is going to do any useful work, then you will need libraries and frameworks to do that work, such storing and retrieving data to/from a database or render complicated HTML. If your application is going to do any useful work, then you will need libraries and frameworks to do that work, such storing and retrieving data to/from a database or render complicated HTML. With this version of ASP.NET Core, the dependencies are all managed via the NuGet package manager. With this version of ASP.NET Core, the dependencies are all managed via the NuGet package manager. NuGet has been around the .NET space for a few years, but now the primary way to manage all your dependencies is by using libraries and frameworks that are wrapped as NuGet packages. NuGet has been around the .NET space for a few years, but now the primary way to manage all your dependencies is by using libraries and frameworks that are wrapped as NuGet packages. All of the top-level NuGet packages your application needs will be stored in this project.json file. All of the top-level NuGet packages your application needs will be stored in this project.json file. "Microsoft.AspNetCore.Diagnostics": "1.0.0", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", "Microsoft.Extensions.Logging.Console": "1.0.0 You can see we have some dependencies in this file and the exact dependencies will probably change by the final release of ASP.NET. When you want to add a new dependency, say like the ASP.NET MVC framework, you easily type into this project.json file, and you will also get some IntelliSense help including not just the package name but also the version numbers as shown in the following screenshot. You can also use the UI by right-clicking on References in the Solution Explorer and then, select Manage NuGet packages. You can now see the currently installed packages. Those packages are the same ones that are in your project.json file and you can also go to the Browser and add other packages, including pre-released packages, let us say, the MVC framework installed into this project. If you install this package right now by using the Install button, then this package would be stored in project.json. The frameworks section is another important part of project.json, this section tells ASP.NET as to which of the .NET frameworks your application can use. "frameworks": { "netcoreapp1.0": { "imports": [ "dotnet5.6", "portable-net45+win8" ] } }, In this case, you will see that "netcoreapp1.0" is the framework used in the project, you can also include the full .NET Framework which is installed when you install Visual Studio. It is the same .NET Framework that is included with many versions of the Windows Operating System. It is the same .NET Framework that is included with many versions of the Windows Operating System. It is the .NET Framework that has been around for 15 years, and it includes the frameworks that do everything from web programming to desktop programming. It is the .NET Framework that has been around for 15 years, and it includes the frameworks that do everything from web programming to desktop programming. It is a huge framework that works only on Windows. It is a huge framework that works only on Windows. “netcoreapp1.0” is the .NET Core framework. It is a cross-platform framework and can work on various platforms, not just Windows but also OS X and Linux. “netcoreapp1.0” is the .NET Core framework. It is a cross-platform framework and can work on various platforms, not just Windows but also OS X and Linux. This framework has fewer features than the full .NET framework, but it does have all the features that we need for ASP.NET Core web development. This framework has fewer features than the full .NET framework, but it does have all the features that we need for ASP.NET Core web development. 51 Lectures 5.5 hours Anadi Sharma 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 40 Lectures 2.5 hours University Code 138 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2847, "s": 2461, "text": "In this chapter, we will discuss the project.json file. This file is using JavaScript object notation to store configuration information and it is this file that is really the heart of a .NET application. Without this file, you would not have an ASP.NET Core project. Here, we will discuss some of the most important features of this file. Let us double-click on the project.json file." }, { "code": null, "e": 2927, "s": 2847, "text": "Currently, the default code implementation in project.json file is as follows −" }, { "code": null, "e": 3919, "s": 2927, "text": "{\n \"dependencies\": {\n \"Microsoft.NETCore.App\": {\n \"version\": \"1.0.0\",\n \"type\": \"platform\"\n },\n \"Microsoft.AspNetCore.Diagnostics\": \"1.0.0\",\n \"Microsoft.AspNetCore.Server.IISIntegration\": \"1.0.0\",\n \"Microsoft.AspNetCore.Server.Kestrel\": \"1.0.0\",\n \"Microsoft.Extensions.Logging.Console\": \"1.0.0\"\n },\n \"tools\": {\n \"Microsoft.AspNetCore.Server.IISIntegration.Tools\": \"1.0.0-preview2-final\"\n },\n \"frameworks\": {\n \"netcoreapp1.0\": {\n \"imports\": [\"dotnet5.6\", \"portable-net45+win8\"]\n }\n },\n \"buildOptions\": {\n \"emitEntryPoint\": true,\n \"preserveCompilationContext\": true\n },\n \"runtimeOptions\": {\n \"configProperties\": {\n \"System.GC.Server\": true\n }\n },\n \"publishOptions\": {\n \"include\": [\"wwwroot\", \"web.config\" ]\n },\n \"scripts\": {\n \"postpublish\": [ \"dotnet publish-iis --publish-folder %publish:OutputPath%\n --framework %publish:FullTargetFramework%\" ]\n }\n}" }, { "code": null, "e": 4055, "s": 3919, "text": "As we see, we have version information at the top of this file. This is the version number your application will use when you build it." }, { "code": null, "e": 4139, "s": 4055, "text": "The version is 1.0.0, but the most important part of this file is the dependencies." }, { "code": null, "e": 4223, "s": 4139, "text": "The version is 1.0.0, but the most important part of this file is the dependencies." }, { "code": null, "e": 4416, "s": 4223, "text": "If your application is going to do any useful work, then you will need libraries and frameworks to do that work, such storing and retrieving data to/from a database or render complicated HTML." }, { "code": null, "e": 4609, "s": 4416, "text": "If your application is going to do any useful work, then you will need libraries and frameworks to do that work, such storing and retrieving data to/from a database or render complicated HTML." }, { "code": null, "e": 4708, "s": 4609, "text": "With this version of ASP.NET Core, the dependencies are all managed via the NuGet package manager." }, { "code": null, "e": 4807, "s": 4708, "text": "With this version of ASP.NET Core, the dependencies are all managed via the NuGet package manager." }, { "code": null, "e": 4990, "s": 4807, "text": "NuGet has been around the .NET space for a few years, but now the primary way to manage all your dependencies is by using libraries and frameworks that are wrapped as NuGet packages." }, { "code": null, "e": 5173, "s": 4990, "text": "NuGet has been around the .NET space for a few years, but now the primary way to manage all your dependencies is by using libraries and frameworks that are wrapped as NuGet packages." }, { "code": null, "e": 5274, "s": 5173, "text": "All of the top-level NuGet packages your application needs will be stored in this project.json file." }, { "code": null, "e": 5375, "s": 5274, "text": "All of the top-level NuGet packages your application needs will be stored in this project.json file." }, { "code": null, "e": 5574, "s": 5375, "text": "\"Microsoft.AspNetCore.Diagnostics\": \"1.0.0\", \n\"Microsoft.AspNetCore.Server.IISIntegration\": \"1.0.0\", \n\"Microsoft.AspNetCore.Server.Kestrel\": \"1.0.0\", \n\"Microsoft.Extensions.Logging.Console\": \"1.0.0\n" }, { "code": null, "e": 5974, "s": 5574, "text": "You can see we have some dependencies in this file and the exact dependencies will probably change by the final release of ASP.NET. When you want to add a new dependency, say like the ASP.NET MVC framework, you easily type into this project.json file, and you will also get some IntelliSense help including not just the package name but also the version numbers as shown in the following screenshot." }, { "code": null, "e": 6145, "s": 5974, "text": "You can also use the UI by right-clicking on References in the Solution Explorer and then, select Manage NuGet packages. You can now see the currently installed packages." }, { "code": null, "e": 6364, "s": 6145, "text": "Those packages are the same ones that are in your project.json file and you can also go to the Browser and add other packages, including pre-released packages, let us say, the MVC framework installed into this project." }, { "code": null, "e": 6636, "s": 6364, "text": "If you install this package right now by using the Install button, then this package would be stored in project.json. The frameworks section is another important part of project.json, this section tells ASP.NET as to which of the .NET frameworks your application can use." }, { "code": null, "e": 6769, "s": 6636, "text": "\"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": [ \n \"dotnet5.6\", \n \"portable-net45+win8\" \n ] \n } \n}," }, { "code": null, "e": 6951, "s": 6769, "text": "In this case, you will see that \"netcoreapp1.0\" is the framework used in the project, you can also include the full .NET Framework which is installed when you install Visual Studio." }, { "code": null, "e": 7050, "s": 6951, "text": "It is the same .NET Framework that is included with many versions of the Windows Operating System." }, { "code": null, "e": 7149, "s": 7050, "text": "It is the same .NET Framework that is included with many versions of the Windows Operating System." }, { "code": null, "e": 7304, "s": 7149, "text": "It is the .NET Framework that has been around for 15 years, and it includes the frameworks that do everything from web programming to desktop programming." }, { "code": null, "e": 7459, "s": 7304, "text": "It is the .NET Framework that has been around for 15 years, and it includes the frameworks that do everything from web programming to desktop programming." }, { "code": null, "e": 7510, "s": 7459, "text": "It is a huge framework that works only on Windows." }, { "code": null, "e": 7561, "s": 7510, "text": "It is a huge framework that works only on Windows." }, { "code": null, "e": 7715, "s": 7561, "text": "“netcoreapp1.0” is the .NET Core framework. It is a cross-platform framework and can work on various platforms, not just Windows but also OS X and Linux." }, { "code": null, "e": 7869, "s": 7715, "text": "“netcoreapp1.0” is the .NET Core framework. It is a cross-platform framework and can work on various platforms, not just Windows but also OS X and Linux." }, { "code": null, "e": 8014, "s": 7869, "text": "This framework has fewer features than the full .NET framework, but it does have all the features that we need for ASP.NET Core web development." }, { "code": null, "e": 8159, "s": 8014, "text": "This framework has fewer features than the full .NET framework, but it does have all the features that we need for ASP.NET Core web development." }, { "code": null, "e": 8194, "s": 8159, "text": "\n 51 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8208, "s": 8194, "text": " Anadi Sharma" }, { "code": null, "e": 8243, "s": 8208, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8266, "s": 8243, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 8300, "s": 8266, "text": "\n 42 Lectures \n 18 hours \n" }, { "code": null, "e": 8320, "s": 8300, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 8355, "s": 8320, "text": "\n 57 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8372, "s": 8355, "text": " University Code" }, { "code": null, "e": 8407, "s": 8372, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8424, "s": 8407, "text": " University Code" }, { "code": null, "e": 8458, "s": 8424, "text": "\n 138 Lectures \n 9 hours \n" }, { "code": null, "e": 8473, "s": 8458, "text": " Bhrugen Patel" }, { "code": null, "e": 8480, "s": 8473, "text": " Print" }, { "code": null, "e": 8491, "s": 8480, "text": " Add Notes" } ]
ML - Neural Network Implementation in C++ From Scratch - GeeksforGeeks
11 Mar, 2022 What are we going to do here? This article explains how to create a super-fast Artificial Neural Network that can crunch millions of data points within seconds! even milliseconds. Artificial Intelligence and Machine Learning are nowadays one of the most trending topics among computer geeks. Data scientists are being hired by tech giants for their excellence in these fields. Why use C++ Now, if you have already implemented a neural network model in some other programming language then you might have noticed ( If you have a low-end PC ) that your models work pretty slow on even small datasets. When you began learning about Neural Networks you might have googled Which language is best for machine learning? and the obvious answer you get is Python or R is best for machine learning, other languages are hard so you must not waste your time on them!. Now, if the user starts programming, they face the problem of time and resource consumption. So, this article shows how to a super fast neural network.Prerequisites: Basic knowledge about what are classes and how they work. Use a linear algebra library called Eigen Some basic read/write operations in C++ Some basic knowledge about linear algebra as we are using a library for that Eigen 101: Eigen by its core is a library for super fast linear algebra operations and it’s the fastest and easiest one out there. Some resources to learn the basics of Eigen. Getting started! Eigen Matrix class While learning Eigen you will encounter one of the most powerful feature of C++ – Template Metaprogramming. It is recommended not to get deviated from the track right now ( if you are new to C++ ) and assume those as basic parameters to a function! However if you are really obsessed with learning new and powerful things then here’s a good article and a video for it. Writing the Neural Network class Before going further I assume that you know what a Neural Network is and how does it learn. If not, then I do recommend you the following pages to take a look at! Basics of Neural Networks Forward and Backpropagation in neural networks Code : The Neural Network Class CPP // NeuralNetwork.hpp#include <eigen3/Eigen/Eigen>#include <iostream>#include <vector> // use typedefs for future ease for changing data types like : float to doubletypedef float Scalar;typedef Eigen::MatrixXf Matrix;typedef Eigen::RowVectorXf RowVector;typedef Eigen::VectorXf ColVector; // neural network implementation class!class NeuralNetwork {public: // constructor NeuralNetwork(std::vector<uint> topology, Scalar learningRate = Scalar(0.005)); // function for forward propagation of data void propagateForward(RowVector& input); // function for backward propagation of errors made by neurons void propagateBackward(RowVector& output); // function to calculate errors made by neurons in each layer void calcErrors(RowVector& output); // function to update the weights of connections void updateWeights(); // function to train the neural network give an array of data points void train(std::vector<RowVector*> data); // storage objects for working of neural network /* use pointers when using std::vector<Class> as std::vector<Class> calls destructor of Class as soon as it is pushed back! when we use pointers it can't do that, besides it also makes our neural network class less heavy!! It would be nice if you can use smart pointers instead of usual ones like this */ std::vector<RowVector*> neuronLayers; // stores the different layers of out network std::vector<RowVector*> cacheLayers; // stores the unactivated (activation fn not yet applied) values of layers std::vector<RowVector*> deltas; // stores the error contribution of each neurons std::vector<Matrix*> weights; // the connection weights itself Scalar learningRate;}; Next, we move ahead by implementing each function one by one... But first, create two files (NeuralNetwork.cpp and NeuralNetwork.hpp) and write the above NeuralNetwork class code yourself in the “NeuralNetwork.hpp”. The following line of code must be copied in the “NeuralNetwork.cpp” file.Code: Constructor for the Neural Network Class CPP // constructor of neural network classNeuralNetwork::NeuralNetwork(std::vector<uint> topology, Scalar learningRate){ this->topology = topology; this->learningRate = learningRate; for (uint i = 0; i < topology.size(); i++) { // initialize neuron layers if (i == topology.size() - 1) neuronLayers.push_back(new RowVector(topology[i])); else neuronLayers.push_back(new RowVector(topology[i] + 1)); // initialize cache and delta vectors cacheLayers.push_back(new RowVector(neuronLayers.size())); deltas.push_back(new RowVector(neuronLayers.size())); // vector.back() gives the handle to recently added element // coeffRef gives the reference of value at that place // (using this as we are using pointers here) if (i != topology.size() - 1) { neuronLayers.back()->coeffRef(topology[i]) = 1.0; cacheLayers.back()->coeffRef(topology[i]) = 1.0; } // initialize weights matrix if (i > 0) { if (i != topology.size() - 1) { weights.push_back(new Matrix(topology[i - 1] + 1, topology[i] + 1)); weights.back()->setRandom(); weights.back()->col(topology[i]).setZero(); weights.back()->coeffRef(topology[i - 1], topology[i]) = 1.0; } else { weights.push_back(new Matrix(topology[i - 1] + 1, topology[i])); weights.back()->setRandom(); } } }}; Explanation of constructor function – Initializing the neurons, cache and deltas The topology vector describes how many neurons we have in each layer, and the size of this vector is equal to a number of layers in the neural network. Each layer in the neural network is an array of neurons, we store each of these layers as a vector such that each element in this vector stores the activation value of neuron in that layer (note that an array of these layers is the neural network itself. Now in line 8, we add an extra bias neuron to each layer except in the output layer (line 7). The cache and delta vector is of the same dimensions as that of the neuronLayer vector. We are using vectors here as layers and not a 2D matrix as we are doing SGD and not batch or mini-batch gradient descent. Now, a cache is just another name of the sum of weighted inputs from the previous layer. A notation that we will use for dimensions of a matrix is: [m n] denotes a matrix having m rows and n columns. Initializing Weights matrix Initializing weights matrix is a bit tricky! (mathematically). Pay very serious attention to whatever you read for the next few lines as this will explain how we want to use the weights matrix through this article. I assume that you know how layers are interconnected in a neural network. CURRENT_LAYER represents the layer which is taking input and PREV_LAYER and FWD_LAYER represents a layer back and a layer front of the CURRENT_LAYER. c-th column in the weights matrix represents the connection of c-th neuron in CURRENT_LAYER to all the neurons in the PREV_LAYER. r-th element of c-th column in the weights matrix represents the connection of c-th neuron in CURRENT_LAYER to r-th neuron in the PREV_LAYER. r-th row in the weights matrix represents the connection of all the neurons in the PREV_LAYER to r-th neuron in CURRENT_LAYER. c-th element of r-th row in the weights matrix represents connection of c-th neuron in PREV_LAYER to r-th neuron in CURRENT_LAYER. Points 1 and 2 will be used when we use weights matrix in normal sense, but points 3 and 4 will be used when we use weights matrix in transposed sense (a(i, j)=a(j, I)) Now, remember we have an extra bias neuron in the previous layer. If we do a simple matrix product of neuronsLayer vector of PREV_LAYER and weights matrix of CURRENT_LAYER, we will get the new neuronsLayer vector of CURRENT_LAYER. What we have to do now is modify our weights matrix in a manner so that the bias neuron of CURRENT_LAYER remains unaffected by matrix multiplication! For that we set all the element of last column of weights matrix to 0 (line 26) except that last element (line 27).Code: Feed Forward Algorithm CPP void NeuralNetwork::propagateForward(RowVector& input){ // set the input to input layer // block returns a part of the given vector or matrix // block takes 4 arguments : startRow, startCol, blockRows, blockCols neuronLayers.front()->block(0, 0, 1, neuronLayers.front()->size() - 1) = input; // propagate the data forward and then // apply the activation function to your network // unaryExpr applies the given function to all elements of CURRENT_LAYER for (uint i = 1; i < topology.size(); i++) { // already explained above (*neuronLayers[i]) = (*neuronLayers[i - 1]) * (*weights[i - 1]); neuronLayers[i]->block(0, 0, 1, topology[i]).unaryExpr(std::ptr_fun(activationFunction)); }} Explanation of feed forward algorithm: C-th element (neuron) of the CURRENT_LAYER takes it’s input by taking a dot product between neuronLayers vector of PREV_LAYER and the C-th column. This way, it takes the inputs multiplied by weight and this also automatically adds up the bias term. The last column of weights matrix is initialized by setting all elements to 0 except the last element (set to 1), what this means is that the bias neuron of CURRENT_LAYER takes input from bias neuron of PREV_LAYER only.Calculating Errors: CPP void NeuralNetwork::calcErrors(RowVector& output){ // calculate the errors made by neurons of last layer (*deltas.back()) = output - (*neuronLayers.back()); // error calculation of hidden layers is different // we will begin by the last hidden layer // and we will continue till the first hidden layer for (uint i = topology.size() - 2; i > 0; i--) { (*deltas[i]) = (*deltas[i + 1]) * (weights[i]->transpose()); }} Code: Updating the weights CPP void NeuralNetwork::updateWeights(){ // topology.size()-1 = weights.size() for (uint i = 0; i < topology.size() - 1; i++) { // in this loop we are iterating over the different layers (from first hidden to output layer) // if this layer is the output layer, there is no bias neuron there, number of neurons specified = number of cols // if this layer not the output layer, there is a bias neuron and number of neurons specified = number of cols -1 if (i != topology.size() - 2) { for (uint c = 0; c < weights[i]->cols() - 1; c++) { for (uint r = 0; r < weights[i]->rows(); r++) { weights[i]->coeffRef(r, c) += learningRate * deltas[i + 1]->coeffRef(c) * activationFunctionDerivative(cacheLayers[i + 1]->coeffRef(c)) * neuronLayers[i]->coeffRef(r); } } } else { for (uint c = 0; c < weights[i]->cols(); c++) { for (uint r = 0; r < weights[i]->rows(); r++) { weights[i]->coeffRef(r, c) += learningRate * deltas[i + 1]->coeffRef(c) * activationFunctionDerivative(cacheLayers[i + 1]->coeffRef(c)) * neuronLayers[i]->coeffRef(r); } } } }} Backpropagation Algorithm: CPP void NeuralNetwork::propagateBackward(RowVector& output){ calcErrors(output); updateWeights();} Code: Activation Function CPP Scalar activationFunction(Scalar x){ return tanhf(x);} Scalar activationFunctionDerivative(Scalar x){ return 1 - tanhf(x) * tanhf(x);}// you can use your own code here! Code: Training neural network CPP void NeuralNetwork::train(std::vector<RowVector*> input_data, std::vector<RowVector*> output_data){ for (uint i = 0; i < input_data.size(); i++) { std::cout << "Input to neural network is : " << *input_data[i] << std::endl; propagateForward(*input_data[i]); std::cout << "Expected output is : " << *output_data[i] << std::endl; std::cout << "Output produced is : " << *neuronLayers.back() << std::endl; propagateBackward(*output_data[i]); std::cout << "MSE : " << std::sqrt((*deltas.back()).dot((*deltas.back())) / deltas.back()->size()) << std::endl; }} Code: Loading data CPP void ReadCSV(std::string filename, std::vector<RowVector*>& data){ data.clear(); std::ifstream file(filename); std::string line, word; // determine number of columns in file getline(file, line, '\n'); std::stringstream ss(line); std::vector<Scalar> parsed_vec; while (getline(ss, word, ', ')) { parsed_vec.push_back(Scalar(std::stof(&word[0]))); } uint cols = parsed_vec.size(); data.push_back(new RowVector(cols)); for (uint i = 0; i < cols; i++) { data.back()->coeffRef(1, i) = parsed_vec[i]; } // read the file if (file.is_open()) { while (getline(file, line, '\n')) { std::stringstream ss(line); data.push_back(new RowVector(1, cols)); uint i = 0; while (getline(ss, word, ', ')) { data.back()->coeffRef(i) = Scalar(std::stof(&word[0])); i++; } } }} The user can read csv files using this code and paste this in the neural network class but be careful, the declarations and definitions must be kept in separate files (NeuralNetwork.cpp and NeuralNetwork.h). Save all the files and be with me for a few minutes!Code: Generate Some Noise i.e. training data CPP void genData(std::string filename){ std::ofstream file1(filename + "-in"); std::ofstream file2(filename + "-out"); for (uint r = 0; r < 1000; r++) { Scalar x = rand() / Scalar(RAND_MAX); Scalar y = rand() / Scalar(RAND_MAX); file1 << x << ", " << y << std::endl; file2 << 2 * x + 10 + y << std::endl; } file1.close(); file2.close();} Code: Implementation of the neural network. CPP // main.cpp // don't forget to include out neural network#include "NeuralNetwork.hpp" //... data generator code here typedef std::vector<RowVector*> data;int main(){ NeuralNetwork n({ 2, 3, 1 }); data in_dat, out_dat; genData("test"); ReadCSV("test-in", in_dat); ReadCSV("test-out", out_dat); n.train(in_dat, out_dat); return 0;} To compile the program, open your linux terminal and type : g++ main.cpp NeuralNetwork.cpp -o main && ./mainRun this command. Try experimenting with the number of data points in that genData function. surindertarika1234 kapoorsagar226 rkbhola5 emiliotonix C++ Programs Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C++ Program for QuickSort cin in C++ CSV file management using C++ Check if given number is perfect square Shallow Copy and Deep Copy in C++ Naive Bayes Classifiers Linear Regression (Python Implementation) Removing stop words with NLTK in Python ML | Linear Regression Agents in Artificial Intelligence
[ { "code": null, "e": 24570, "s": 24542, "text": "\n11 Mar, 2022" }, { "code": null, "e": 25594, "s": 24570, "text": "What are we going to do here? This article explains how to create a super-fast Artificial Neural Network that can crunch millions of data points within seconds! even milliseconds. Artificial Intelligence and Machine Learning are nowadays one of the most trending topics among computer geeks. Data scientists are being hired by tech giants for their excellence in these fields. Why use C++ Now, if you have already implemented a neural network model in some other programming language then you might have noticed ( If you have a low-end PC ) that your models work pretty slow on even small datasets. When you began learning about Neural Networks you might have googled Which language is best for machine learning? and the obvious answer you get is Python or R is best for machine learning, other languages are hard so you must not waste your time on them!. Now, if the user starts programming, they face the problem of time and resource consumption. So, this article shows how to a super fast neural network.Prerequisites: " }, { "code": null, "e": 25652, "s": 25594, "text": "Basic knowledge about what are classes and how they work." }, { "code": null, "e": 25694, "s": 25652, "text": "Use a linear algebra library called Eigen" }, { "code": null, "e": 25734, "s": 25694, "text": "Some basic read/write operations in C++" }, { "code": null, "e": 25811, "s": 25734, "text": "Some basic knowledge about linear algebra as we are using a library for that" }, { "code": null, "e": 25989, "s": 25811, "text": "Eigen 101: Eigen by its core is a library for super fast linear algebra operations and it’s the fastest and easiest one out there. Some resources to learn the basics of Eigen. " }, { "code": null, "e": 26006, "s": 25989, "text": "Getting started!" }, { "code": null, "e": 26025, "s": 26006, "text": "Eigen Matrix class" }, { "code": null, "e": 26592, "s": 26025, "text": "While learning Eigen you will encounter one of the most powerful feature of C++ – Template Metaprogramming. It is recommended not to get deviated from the track right now ( if you are new to C++ ) and assume those as basic parameters to a function! However if you are really obsessed with learning new and powerful things then here’s a good article and a video for it. Writing the Neural Network class Before going further I assume that you know what a Neural Network is and how does it learn. If not, then I do recommend you the following pages to take a look at! " }, { "code": null, "e": 26618, "s": 26592, "text": "Basics of Neural Networks" }, { "code": null, "e": 26665, "s": 26618, "text": "Forward and Backpropagation in neural networks" }, { "code": null, "e": 26699, "s": 26665, "text": "Code : The Neural Network Class " }, { "code": null, "e": 26703, "s": 26699, "text": "CPP" }, { "code": "// NeuralNetwork.hpp#include <eigen3/Eigen/Eigen>#include <iostream>#include <vector> // use typedefs for future ease for changing data types like : float to doubletypedef float Scalar;typedef Eigen::MatrixXf Matrix;typedef Eigen::RowVectorXf RowVector;typedef Eigen::VectorXf ColVector; // neural network implementation class!class NeuralNetwork {public: // constructor NeuralNetwork(std::vector<uint> topology, Scalar learningRate = Scalar(0.005)); // function for forward propagation of data void propagateForward(RowVector& input); // function for backward propagation of errors made by neurons void propagateBackward(RowVector& output); // function to calculate errors made by neurons in each layer void calcErrors(RowVector& output); // function to update the weights of connections void updateWeights(); // function to train the neural network give an array of data points void train(std::vector<RowVector*> data); // storage objects for working of neural network /* use pointers when using std::vector<Class> as std::vector<Class> calls destructor of Class as soon as it is pushed back! when we use pointers it can't do that, besides it also makes our neural network class less heavy!! It would be nice if you can use smart pointers instead of usual ones like this */ std::vector<RowVector*> neuronLayers; // stores the different layers of out network std::vector<RowVector*> cacheLayers; // stores the unactivated (activation fn not yet applied) values of layers std::vector<RowVector*> deltas; // stores the error contribution of each neurons std::vector<Matrix*> weights; // the connection weights itself Scalar learningRate;};", "e": 28448, "s": 26703, "text": null }, { "code": null, "e": 28787, "s": 28448, "text": "Next, we move ahead by implementing each function one by one... But first, create two files (NeuralNetwork.cpp and NeuralNetwork.hpp) and write the above NeuralNetwork class code yourself in the “NeuralNetwork.hpp”. The following line of code must be copied in the “NeuralNetwork.cpp” file.Code: Constructor for the Neural Network Class " }, { "code": null, "e": 28791, "s": 28787, "text": "CPP" }, { "code": "// constructor of neural network classNeuralNetwork::NeuralNetwork(std::vector<uint> topology, Scalar learningRate){ this->topology = topology; this->learningRate = learningRate; for (uint i = 0; i < topology.size(); i++) { // initialize neuron layers if (i == topology.size() - 1) neuronLayers.push_back(new RowVector(topology[i])); else neuronLayers.push_back(new RowVector(topology[i] + 1)); // initialize cache and delta vectors cacheLayers.push_back(new RowVector(neuronLayers.size())); deltas.push_back(new RowVector(neuronLayers.size())); // vector.back() gives the handle to recently added element // coeffRef gives the reference of value at that place // (using this as we are using pointers here) if (i != topology.size() - 1) { neuronLayers.back()->coeffRef(topology[i]) = 1.0; cacheLayers.back()->coeffRef(topology[i]) = 1.0; } // initialize weights matrix if (i > 0) { if (i != topology.size() - 1) { weights.push_back(new Matrix(topology[i - 1] + 1, topology[i] + 1)); weights.back()->setRandom(); weights.back()->col(topology[i]).setZero(); weights.back()->coeffRef(topology[i - 1], topology[i]) = 1.0; } else { weights.push_back(new Matrix(topology[i - 1] + 1, topology[i])); weights.back()->setRandom(); } } }};", "e": 30311, "s": 28791, "text": null }, { "code": null, "e": 31622, "s": 30311, "text": "Explanation of constructor function – Initializing the neurons, cache and deltas The topology vector describes how many neurons we have in each layer, and the size of this vector is equal to a number of layers in the neural network. Each layer in the neural network is an array of neurons, we store each of these layers as a vector such that each element in this vector stores the activation value of neuron in that layer (note that an array of these layers is the neural network itself. Now in line 8, we add an extra bias neuron to each layer except in the output layer (line 7). The cache and delta vector is of the same dimensions as that of the neuronLayer vector. We are using vectors here as layers and not a 2D matrix as we are doing SGD and not batch or mini-batch gradient descent. Now, a cache is just another name of the sum of weighted inputs from the previous layer. A notation that we will use for dimensions of a matrix is: [m n] denotes a matrix having m rows and n columns. Initializing Weights matrix Initializing weights matrix is a bit tricky! (mathematically). Pay very serious attention to whatever you read for the next few lines as this will explain how we want to use the weights matrix through this article. I assume that you know how layers are interconnected in a neural network. " }, { "code": null, "e": 31772, "s": 31622, "text": "CURRENT_LAYER represents the layer which is taking input and PREV_LAYER and FWD_LAYER represents a layer back and a layer front of the CURRENT_LAYER." }, { "code": null, "e": 31902, "s": 31772, "text": "c-th column in the weights matrix represents the connection of c-th neuron in CURRENT_LAYER to all the neurons in the PREV_LAYER." }, { "code": null, "e": 32044, "s": 31902, "text": "r-th element of c-th column in the weights matrix represents the connection of c-th neuron in CURRENT_LAYER to r-th neuron in the PREV_LAYER." }, { "code": null, "e": 32171, "s": 32044, "text": "r-th row in the weights matrix represents the connection of all the neurons in the PREV_LAYER to r-th neuron in CURRENT_LAYER." }, { "code": null, "e": 32302, "s": 32171, "text": "c-th element of r-th row in the weights matrix represents connection of c-th neuron in PREV_LAYER to r-th neuron in CURRENT_LAYER." }, { "code": null, "e": 32471, "s": 32302, "text": "Points 1 and 2 will be used when we use weights matrix in normal sense, but points 3 and 4 will be used when we use weights matrix in transposed sense (a(i, j)=a(j, I))" }, { "code": null, "e": 32998, "s": 32471, "text": "Now, remember we have an extra bias neuron in the previous layer. If we do a simple matrix product of neuronsLayer vector of PREV_LAYER and weights matrix of CURRENT_LAYER, we will get the new neuronsLayer vector of CURRENT_LAYER. What we have to do now is modify our weights matrix in a manner so that the bias neuron of CURRENT_LAYER remains unaffected by matrix multiplication! For that we set all the element of last column of weights matrix to 0 (line 26) except that last element (line 27).Code: Feed Forward Algorithm " }, { "code": null, "e": 33002, "s": 32998, "text": "CPP" }, { "code": "void NeuralNetwork::propagateForward(RowVector& input){ // set the input to input layer // block returns a part of the given vector or matrix // block takes 4 arguments : startRow, startCol, blockRows, blockCols neuronLayers.front()->block(0, 0, 1, neuronLayers.front()->size() - 1) = input; // propagate the data forward and then // apply the activation function to your network // unaryExpr applies the given function to all elements of CURRENT_LAYER for (uint i = 1; i < topology.size(); i++) { // already explained above (*neuronLayers[i]) = (*neuronLayers[i - 1]) * (*weights[i - 1]); neuronLayers[i]->block(0, 0, 1, topology[i]).unaryExpr(std::ptr_fun(activationFunction)); }}", "e": 33738, "s": 33002, "text": null }, { "code": null, "e": 34267, "s": 33738, "text": "Explanation of feed forward algorithm: C-th element (neuron) of the CURRENT_LAYER takes it’s input by taking a dot product between neuronLayers vector of PREV_LAYER and the C-th column. This way, it takes the inputs multiplied by weight and this also automatically adds up the bias term. The last column of weights matrix is initialized by setting all elements to 0 except the last element (set to 1), what this means is that the bias neuron of CURRENT_LAYER takes input from bias neuron of PREV_LAYER only.Calculating Errors: " }, { "code": null, "e": 34271, "s": 34267, "text": "CPP" }, { "code": "void NeuralNetwork::calcErrors(RowVector& output){ // calculate the errors made by neurons of last layer (*deltas.back()) = output - (*neuronLayers.back()); // error calculation of hidden layers is different // we will begin by the last hidden layer // and we will continue till the first hidden layer for (uint i = topology.size() - 2; i > 0; i--) { (*deltas[i]) = (*deltas[i + 1]) * (weights[i]->transpose()); }}", "e": 34715, "s": 34271, "text": null }, { "code": null, "e": 34744, "s": 34715, "text": "Code: Updating the weights " }, { "code": null, "e": 34748, "s": 34744, "text": "CPP" }, { "code": "void NeuralNetwork::updateWeights(){ // topology.size()-1 = weights.size() for (uint i = 0; i < topology.size() - 1; i++) { // in this loop we are iterating over the different layers (from first hidden to output layer) // if this layer is the output layer, there is no bias neuron there, number of neurons specified = number of cols // if this layer not the output layer, there is a bias neuron and number of neurons specified = number of cols -1 if (i != topology.size() - 2) { for (uint c = 0; c < weights[i]->cols() - 1; c++) { for (uint r = 0; r < weights[i]->rows(); r++) { weights[i]->coeffRef(r, c) += learningRate * deltas[i + 1]->coeffRef(c) * activationFunctionDerivative(cacheLayers[i + 1]->coeffRef(c)) * neuronLayers[i]->coeffRef(r); } } } else { for (uint c = 0; c < weights[i]->cols(); c++) { for (uint r = 0; r < weights[i]->rows(); r++) { weights[i]->coeffRef(r, c) += learningRate * deltas[i + 1]->coeffRef(c) * activationFunctionDerivative(cacheLayers[i + 1]->coeffRef(c)) * neuronLayers[i]->coeffRef(r); } } } }}", "e": 35981, "s": 34748, "text": null }, { "code": null, "e": 36010, "s": 35981, "text": "Backpropagation Algorithm: " }, { "code": null, "e": 36014, "s": 36010, "text": "CPP" }, { "code": "void NeuralNetwork::propagateBackward(RowVector& output){ calcErrors(output); updateWeights();}", "e": 36116, "s": 36014, "text": null }, { "code": null, "e": 36144, "s": 36116, "text": "Code: Activation Function " }, { "code": null, "e": 36148, "s": 36144, "text": "CPP" }, { "code": "Scalar activationFunction(Scalar x){ return tanhf(x);} Scalar activationFunctionDerivative(Scalar x){ return 1 - tanhf(x) * tanhf(x);}// you can use your own code here!", "e": 36323, "s": 36148, "text": null }, { "code": null, "e": 36355, "s": 36323, "text": "Code: Training neural network " }, { "code": null, "e": 36359, "s": 36355, "text": "CPP" }, { "code": "void NeuralNetwork::train(std::vector<RowVector*> input_data, std::vector<RowVector*> output_data){ for (uint i = 0; i < input_data.size(); i++) { std::cout << \"Input to neural network is : \" << *input_data[i] << std::endl; propagateForward(*input_data[i]); std::cout << \"Expected output is : \" << *output_data[i] << std::endl; std::cout << \"Output produced is : \" << *neuronLayers.back() << std::endl; propagateBackward(*output_data[i]); std::cout << \"MSE : \" << std::sqrt((*deltas.back()).dot((*deltas.back())) / deltas.back()->size()) << std::endl; }}", "e": 36962, "s": 36359, "text": null }, { "code": null, "e": 36983, "s": 36962, "text": "Code: Loading data " }, { "code": null, "e": 36987, "s": 36983, "text": "CPP" }, { "code": "void ReadCSV(std::string filename, std::vector<RowVector*>& data){ data.clear(); std::ifstream file(filename); std::string line, word; // determine number of columns in file getline(file, line, '\\n'); std::stringstream ss(line); std::vector<Scalar> parsed_vec; while (getline(ss, word, ', ')) { parsed_vec.push_back(Scalar(std::stof(&word[0]))); } uint cols = parsed_vec.size(); data.push_back(new RowVector(cols)); for (uint i = 0; i < cols; i++) { data.back()->coeffRef(1, i) = parsed_vec[i]; } // read the file if (file.is_open()) { while (getline(file, line, '\\n')) { std::stringstream ss(line); data.push_back(new RowVector(1, cols)); uint i = 0; while (getline(ss, word, ', ')) { data.back()->coeffRef(i) = Scalar(std::stof(&word[0])); i++; } } }}", "e": 37903, "s": 36987, "text": null }, { "code": null, "e": 38209, "s": 37903, "text": "The user can read csv files using this code and paste this in the neural network class but be careful, the declarations and definitions must be kept in separate files (NeuralNetwork.cpp and NeuralNetwork.h). Save all the files and be with me for a few minutes!Code: Generate Some Noise i.e. training data " }, { "code": null, "e": 38213, "s": 38209, "text": "CPP" }, { "code": "void genData(std::string filename){ std::ofstream file1(filename + \"-in\"); std::ofstream file2(filename + \"-out\"); for (uint r = 0; r < 1000; r++) { Scalar x = rand() / Scalar(RAND_MAX); Scalar y = rand() / Scalar(RAND_MAX); file1 << x << \", \" << y << std::endl; file2 << 2 * x + 10 + y << std::endl; } file1.close(); file2.close();}", "e": 38593, "s": 38213, "text": null }, { "code": null, "e": 38639, "s": 38593, "text": "Code: Implementation of the neural network. " }, { "code": null, "e": 38643, "s": 38639, "text": "CPP" }, { "code": "// main.cpp // don't forget to include out neural network#include \"NeuralNetwork.hpp\" //... data generator code here typedef std::vector<RowVector*> data;int main(){ NeuralNetwork n({ 2, 3, 1 }); data in_dat, out_dat; genData(\"test\"); ReadCSV(\"test-in\", in_dat); ReadCSV(\"test-out\", out_dat); n.train(in_dat, out_dat); return 0;}", "e": 38994, "s": 38643, "text": null }, { "code": null, "e": 39196, "s": 38994, "text": "To compile the program, open your linux terminal and type : g++ main.cpp NeuralNetwork.cpp -o main && ./mainRun this command. Try experimenting with the number of data points in that genData function. " }, { "code": null, "e": 39215, "s": 39196, "text": "surindertarika1234" }, { "code": null, "e": 39230, "s": 39215, "text": "kapoorsagar226" }, { "code": null, "e": 39239, "s": 39230, "text": "rkbhola5" }, { "code": null, "e": 39251, "s": 39239, "text": "emiliotonix" }, { "code": null, "e": 39264, "s": 39251, "text": "C++ Programs" }, { "code": null, "e": 39281, "s": 39264, "text": "Machine Learning" }, { "code": null, "e": 39298, "s": 39281, "text": "Machine Learning" }, { "code": null, "e": 39396, "s": 39298, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39422, "s": 39396, "text": "C++ Program for QuickSort" }, { "code": null, "e": 39433, "s": 39422, "text": "cin in C++" }, { "code": null, "e": 39463, "s": 39433, "text": "CSV file management using C++" }, { "code": null, "e": 39503, "s": 39463, "text": "Check if given number is perfect square" }, { "code": null, "e": 39537, "s": 39503, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 39561, "s": 39537, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 39603, "s": 39561, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 39643, "s": 39603, "text": "Removing stop words with NLTK in Python" }, { "code": null, "e": 39666, "s": 39643, "text": "ML | Linear Regression" } ]
Maximum adjacent difference in an array in its sorted form - GeeksforGeeks
24 Jun, 2021 Given an array, find the maximum difference between its two consecutive elements in its sorted form.Examples: Input: arr[] = {1, 10, 5} Output: 5 Sorted array would be {1, 5, 10} and maximum adjacent difference would be 10 - 5 = 5 Input: arr[] = {2, 4, 8, 11} Output: 4 Naive Solution: First sort the array, then traverse it and keep track of the maximum difference between adjacent elements. The time complexity of this method is O(nlogn). Efficient Solution:This solution is based on the idea of Pigeonhole sorting. No need to sort the array, just have to fill the buckets and keep track of the maximum and minimum value of each bucket. If found an empty bucket, The maximum gap would be the difference of maximum value in the previous bucket – minimum value in the next bucket. As we want to almost sort these so that, we can have maximum gap. Also for any ith element, the value of (arr[i]-min_value)/(max_value-min_value) keeps increasing as arr[i] keeps increasing and this value always varies from 0 to 1. As we want to put the sorted results in bucket of size n. We multiply this value by (n-1) hence make a variable delta = (max_value – min_value)/(n-1). Now in maxBucket or minBucket, all the value at any index j before index any i will always less than the value at index i, minBucket[j]<minBucket[i] for j<i. It is possible that two different arr[i], might have same value of (arr[i]-min_value)/delta, therefore we are making 2 different buckets maxBucket and minBucket. As we have find the max difference between consecutive values, we must consider the max possible value upto to previous index as prev_val and the minBucket[i] for current index i, and ans will be max of ans and minBucket[i]-prev_val. Let us solve the above example by this approach. Working Example: Input: arr[] = {1, 10, 5} Output: 5 Step1: Find max_val and min_val max_val = 10, min_val = 1 Step2: Calculate delta delta = (max_val – min_val)/(n-1) delta = (10-1)/(3-1) = 4.5 Step3: Initialize buckets, maxBucket={INT_MIN}, minBucket={INT_MAX} Step4: For any index i, calculate index arr[i] in bucket and update in buckets, in = (arr[i]-min_val)/delta maxBucket[in]=max(maxBucket[in],arr[i]) minBucket[in]=min(minBucket[in],arr[i]) for all index in arr in values are => 0,2,0 maxBucket=[5,INT_MIN,10] minBucket=[1,INT_MAX,10] Step5: Hence ans is max of minBucket[i]-(max of value upto previous index) in this case for i=2: max_gap = max(max_gap,minBucket[2] – max(maxBucket[1],maxBucket[0])) max_gap = 10-5=5 This is just for presenting the concept, all other basic validations are in the main code. Below is the code for the above approach: C++ Java Python3 C# Javascript // CPP program to find maximum adjacent difference// between two adjacent after sorting.#include <bits/stdc++.h>using namespace std; int maxSortedAdjacentDiff(int* arr, int n){ // Find maximum and minimum in arr[] int maxVal = arr[0], minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = max(maxVal, arr[i]); minVal = min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. int maxBucket[n - 1]; int minBucket[n - 1]; fill_n(maxBucket, n - 1, INT_MIN); fill_n(minBucket, n - 1, INT_MAX); // Expected gap for every bucket. float delta = (float)(maxVal - minVal) / (float)(n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) continue; // Finding index of bucket. int index = (float)(floor(arr[i] - minVal) / delta); maxBucket[index] = max(maxBucket[index], arr[i]); minBucket[index] = min(minBucket[index], arr[i]); } // Finding maximum difference between maximum value // of previous bucket minus minimum of current bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == INT_MAX) continue; max_gap = max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = max(max_gap, maxVal - prev_val); return max_gap;} int main(){ int arr[] = { 1, 10, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSortedAdjacentDiff(arr, n) << endl; return 0;} // Java program for the above approachimport java.util.Arrays; // Java program to find maximum adjacent difference// between two adjacent after sorting.class GFG { static int maxSortedAdjacentDiff(int[] arr, int n) { // Find maximum and minimum in arr[] int maxVal = arr[0]; int minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = Math.max(maxVal, arr[i]); minVal = Math.min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. int maxBucket[] = new int[n - 1]; int minBucket[] = new int[n - 1]; Arrays.fill(maxBucket, 0, n - 1, Integer.MIN_VALUE); Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE); // Expected gap for every bucket. float delta = (float)(maxVal - minVal) / (float)(n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) { continue; } // Finding index of bucket. int index = (int)(Math.round((arr[i] - minVal) / delta)); // Filling/Updating maximum value of bucket if (maxBucket[index] == Integer.MIN_VALUE) { maxBucket[index] = arr[i]; } else { maxBucket[index] = Math.max(maxBucket[index], arr[i]); } // Filling/Updating minimum value of bucket if (minBucket[index] == Integer.MAX_VALUE) { minBucket[index] = arr[i]; } else { minBucket[index] = Math.min(minBucket[index], arr[i]); } } // Finding maximum difference between maximum value // of previous bucket minus minimum of current // bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == Integer.MAX_VALUE) { continue; } max_gap = Math.max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.max(max_gap, maxVal - prev_val); return max_gap; } // Driver program to run the case public static void main(String[] args) { int arr[] = { 1, 10, 5 }; int n = arr.length; System.out.println(maxSortedAdjacentDiff(arr, n)); }} # Python3 program to find maximum adjacent# difference between two adjacent after sorting. def maxSortedAdjacentDiff(arr, n): # Find maximum and minimum in arr[] maxVal, minVal = arr[0], arr[0] for i in range(1, n): maxVal = max(maxVal, arr[i]) minVal = min(minVal, arr[i]) # Arrays to store maximum and minimum # values in n-1 buckets of differences. maxBucket = [INT_MIN] * (n - 1) minBucket = [INT_MAX] * (n - 1) # Expected gap for every bucket. delta = (maxVal - minVal) // (n - 1) # Traversing through array elements and # filling in appropriate bucket if bucket # is empty. Else updating bucket values. for i in range(0, n): if arr[i] == maxVal or arr[i] == minVal: continue # Finding index of bucket. index = (arr[i] - minVal) // delta # Filling/Updating maximum value # of bucket if maxBucket[index] == INT_MIN: maxBucket[index] = arr[i] else: maxBucket[index] = max(maxBucket[index], arr[i]) # Filling/Updating minimum value of bucket if minBucket[index] == INT_MAX: minBucket[index] = arr[i] else: minBucket[index] = min(minBucket[index], arr[i]) # Finding maximum difference between # maximum value of previous bucket # minus minimum of current bucket. prev_val, max_gap = minVal, 0 for i in range(0, n - 1): if minBucket[i] == INT_MAX: continue max_gap = max(max_gap, minBucket[i] - prev_val) prev_val = maxBucket[i] max_gap = max(max_gap, maxVal - prev_val) return max_gap # Driver Codeif __name__ == "__main__": arr = [1, 10, 5] n = len(arr) INT_MIN, INT_MAX = float('-inf'), float('inf') print(maxSortedAdjacentDiff(arr, n)) # This code is contributed by Rituraj Jain // C# program to find maximum// adjacent difference between// two adjacent after sorting.using System;using System.Linq; class GFG{static int maxSortedAdjacentDiff(int[] arr, int n){ // Find maximum and minimum in arr[] int maxVal = arr[0]; int minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = Math.Max(maxVal, arr[i]); minVal = Math.Min(minVal, arr[i]); } // Arrays to store maximum and // minimum values in n-1 buckets // of differences. int []maxBucket = new int[n - 1]; int []minBucket = new int[n - 1]; maxBucket = maxBucket.Select(i => int.MinValue).ToArray(); minBucket = minBucket.Select(i => int.MaxValue).ToArray(); // maxBucket.Fill(int.MinValue); // Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE); // Expected gap for every bucket. float delta = (float) (maxVal - minVal) / (float) (n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) { continue; } // Finding index of bucket. int index = (int) (Math.Round((arr[i] - minVal) / delta)); // Filling/Updating maximum value of bucket if (maxBucket[index] == int.MinValue) { maxBucket[index] = arr[i]; } else { maxBucket[index] = Math.Max(maxBucket[index], arr[i]); } // Filling/Updating minimum value of bucket if (minBucket[index] == int.MaxValue) { minBucket[index] = arr[i]; } else { minBucket[index] = Math.Min(minBucket[index], arr[i]); } } // Finding maximum difference between // maximum value of previous bucket // minus minimum of current bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == int.MaxValue) { continue; } max_gap = Math.Max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.Max(max_gap, maxVal - prev_val); return max_gap;} // Driver Codepublic static void Main(){ int []arr = {1, 10, 5}; int n = arr.Length; Console.Write(maxSortedAdjacentDiff(arr, n));}} // This code contributed by 29AjayKumar <script> // JavaScript program to find maximum adjacent difference// between two adjacent after sorting. function maxSortedAdjacentDiff(arr, n){ // Find maximum and minimum in arr[] var maxVal = arr[0], minVal = arr[0]; for (var i = 1; i < n; i++) { maxVal = Math.max(maxVal, arr[i]); minVal = Math.min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. var maxBucket = Array(n-1).fill(-1000000000); var minBucket = Array(n-1).fill(1000000000); // Expected gap for every bucket. var delta = (maxVal - minVal) / (n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (var i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) continue; // Finding index of bucket. var index = Math.floor((arr[i] - minVal) / delta); maxBucket[index] = Math.max(maxBucket[index], arr[i]); minBucket[index] = Math.min(minBucket[index], arr[i]); } // Finding maximum difference between maximum value // of previous bucket minus minimum of current bucket. var prev_val = minVal; var max_gap = 0; for (var i = 0; i < n - 1; i++) { if (minBucket[i] == 1000000000) continue; max_gap = Math.max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.max(max_gap, maxVal - prev_val); return max_gap;} var arr = [1, 10, 5];var n = arr.length;document.write( maxSortedAdjacentDiff(arr, n)); </script> 5 Time complexity: O(n) Auxiliary Space: O(n) Rajput-Ji 29AjayKumar rituraj_jain nehal sharma 2701gouravgoel rrrtnx khushboogoyal499 Pigeonhole Principle Arrays Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Python | Using 2D arrays/lists the right way Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1 Program to find largest element in an array Search an element in a sorted and rotated array
[ { "code": null, "e": 24174, "s": 24146, "text": "\n24 Jun, 2021" }, { "code": null, "e": 24285, "s": 24174, "text": "Given an array, find the maximum difference between its two consecutive elements in its sorted form.Examples: " }, { "code": null, "e": 24447, "s": 24285, "text": "Input: arr[] = {1, 10, 5}\nOutput: 5\nSorted array would be {1, 5, 10} and\nmaximum adjacent difference would be \n10 - 5 = 5\n\nInput: arr[] = {2, 4, 8, 11}\nOutput: 4" }, { "code": null, "e": 24463, "s": 24447, "text": "Naive Solution:" }, { "code": null, "e": 24618, "s": 24463, "text": "First sort the array, then traverse it and keep track of the maximum difference between adjacent elements. The time complexity of this method is O(nlogn)." }, { "code": null, "e": 24958, "s": 24618, "text": "Efficient Solution:This solution is based on the idea of Pigeonhole sorting. No need to sort the array, just have to fill the buckets and keep track of the maximum and minimum value of each bucket. If found an empty bucket, The maximum gap would be the difference of maximum value in the previous bucket – minimum value in the next bucket." }, { "code": null, "e": 25661, "s": 24958, "text": "As we want to almost sort these so that, we can have maximum gap. Also for any ith element, the value of (arr[i]-min_value)/(max_value-min_value) keeps increasing as arr[i] keeps increasing and this value always varies from 0 to 1. As we want to put the sorted results in bucket of size n. We multiply this value by (n-1) hence make a variable delta = (max_value – min_value)/(n-1). Now in maxBucket or minBucket, all the value at any index j before index any i will always less than the value at index i, minBucket[j]<minBucket[i] for j<i. It is possible that two different arr[i], might have same value of (arr[i]-min_value)/delta, therefore we are making 2 different buckets maxBucket and minBucket." }, { "code": null, "e": 25895, "s": 25661, "text": "As we have find the max difference between consecutive values, we must consider the max possible value upto to previous index as prev_val and the minBucket[i] for current index i, and ans will be max of ans and minBucket[i]-prev_val." }, { "code": null, "e": 25944, "s": 25895, "text": "Let us solve the above example by this approach." }, { "code": null, "e": 25961, "s": 25944, "text": "Working Example:" }, { "code": null, "e": 25987, "s": 25961, "text": "Input: arr[] = {1, 10, 5}" }, { "code": null, "e": 25997, "s": 25987, "text": "Output: 5" }, { "code": null, "e": 26030, "s": 25997, "text": "Step1: Find max_val and min_val " }, { "code": null, "e": 26056, "s": 26030, "text": "max_val = 10, min_val = 1" }, { "code": null, "e": 26079, "s": 26056, "text": "Step2: Calculate delta" }, { "code": null, "e": 26113, "s": 26079, "text": "delta = (max_val – min_val)/(n-1)" }, { "code": null, "e": 26140, "s": 26113, "text": "delta = (10-1)/(3-1) = 4.5" }, { "code": null, "e": 26208, "s": 26140, "text": "Step3: Initialize buckets, maxBucket={INT_MIN}, minBucket={INT_MAX}" }, { "code": null, "e": 26288, "s": 26208, "text": "Step4: For any index i, calculate index arr[i] in bucket and update in buckets," }, { "code": null, "e": 26316, "s": 26288, "text": "in = (arr[i]-min_val)/delta" }, { "code": null, "e": 26356, "s": 26316, "text": "maxBucket[in]=max(maxBucket[in],arr[i])" }, { "code": null, "e": 26396, "s": 26356, "text": "minBucket[in]=min(minBucket[in],arr[i])" }, { "code": null, "e": 26440, "s": 26396, "text": "for all index in arr in values are => 0,2,0" }, { "code": null, "e": 26465, "s": 26440, "text": "maxBucket=[5,INT_MIN,10]" }, { "code": null, "e": 26490, "s": 26465, "text": "minBucket=[1,INT_MAX,10]" }, { "code": null, "e": 26565, "s": 26490, "text": "Step5: Hence ans is max of minBucket[i]-(max of value upto previous index)" }, { "code": null, "e": 26656, "s": 26565, "text": "in this case for i=2: max_gap = max(max_gap,minBucket[2] – max(maxBucket[1],maxBucket[0]))" }, { "code": null, "e": 26673, "s": 26656, "text": "max_gap = 10-5=5" }, { "code": null, "e": 26764, "s": 26673, "text": "This is just for presenting the concept, all other basic validations are in the main code." }, { "code": null, "e": 26806, "s": 26764, "text": "Below is the code for the above approach:" }, { "code": null, "e": 26810, "s": 26806, "text": "C++" }, { "code": null, "e": 26815, "s": 26810, "text": "Java" }, { "code": null, "e": 26823, "s": 26815, "text": "Python3" }, { "code": null, "e": 26826, "s": 26823, "text": "C#" }, { "code": null, "e": 26837, "s": 26826, "text": "Javascript" }, { "code": "// CPP program to find maximum adjacent difference// between two adjacent after sorting.#include <bits/stdc++.h>using namespace std; int maxSortedAdjacentDiff(int* arr, int n){ // Find maximum and minimum in arr[] int maxVal = arr[0], minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = max(maxVal, arr[i]); minVal = min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. int maxBucket[n - 1]; int minBucket[n - 1]; fill_n(maxBucket, n - 1, INT_MIN); fill_n(minBucket, n - 1, INT_MAX); // Expected gap for every bucket. float delta = (float)(maxVal - minVal) / (float)(n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) continue; // Finding index of bucket. int index = (float)(floor(arr[i] - minVal) / delta); maxBucket[index] = max(maxBucket[index], arr[i]); minBucket[index] = min(minBucket[index], arr[i]); } // Finding maximum difference between maximum value // of previous bucket minus minimum of current bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == INT_MAX) continue; max_gap = max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = max(max_gap, maxVal - prev_val); return max_gap;} int main(){ int arr[] = { 1, 10, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxSortedAdjacentDiff(arr, n) << endl; return 0;}", "e": 28536, "s": 26837, "text": null }, { "code": "// Java program for the above approachimport java.util.Arrays; // Java program to find maximum adjacent difference// between two adjacent after sorting.class GFG { static int maxSortedAdjacentDiff(int[] arr, int n) { // Find maximum and minimum in arr[] int maxVal = arr[0]; int minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = Math.max(maxVal, arr[i]); minVal = Math.min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. int maxBucket[] = new int[n - 1]; int minBucket[] = new int[n - 1]; Arrays.fill(maxBucket, 0, n - 1, Integer.MIN_VALUE); Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE); // Expected gap for every bucket. float delta = (float)(maxVal - minVal) / (float)(n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) { continue; } // Finding index of bucket. int index = (int)(Math.round((arr[i] - minVal) / delta)); // Filling/Updating maximum value of bucket if (maxBucket[index] == Integer.MIN_VALUE) { maxBucket[index] = arr[i]; } else { maxBucket[index] = Math.max(maxBucket[index], arr[i]); } // Filling/Updating minimum value of bucket if (minBucket[index] == Integer.MAX_VALUE) { minBucket[index] = arr[i]; } else { minBucket[index] = Math.min(minBucket[index], arr[i]); } } // Finding maximum difference between maximum value // of previous bucket minus minimum of current // bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == Integer.MAX_VALUE) { continue; } max_gap = Math.max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.max(max_gap, maxVal - prev_val); return max_gap; } // Driver program to run the case public static void main(String[] args) { int arr[] = { 1, 10, 5 }; int n = arr.length; System.out.println(maxSortedAdjacentDiff(arr, n)); }}", "e": 31173, "s": 28536, "text": null }, { "code": "# Python3 program to find maximum adjacent# difference between two adjacent after sorting. def maxSortedAdjacentDiff(arr, n): # Find maximum and minimum in arr[] maxVal, minVal = arr[0], arr[0] for i in range(1, n): maxVal = max(maxVal, arr[i]) minVal = min(minVal, arr[i]) # Arrays to store maximum and minimum # values in n-1 buckets of differences. maxBucket = [INT_MIN] * (n - 1) minBucket = [INT_MAX] * (n - 1) # Expected gap for every bucket. delta = (maxVal - minVal) // (n - 1) # Traversing through array elements and # filling in appropriate bucket if bucket # is empty. Else updating bucket values. for i in range(0, n): if arr[i] == maxVal or arr[i] == minVal: continue # Finding index of bucket. index = (arr[i] - minVal) // delta # Filling/Updating maximum value # of bucket if maxBucket[index] == INT_MIN: maxBucket[index] = arr[i] else: maxBucket[index] = max(maxBucket[index], arr[i]) # Filling/Updating minimum value of bucket if minBucket[index] == INT_MAX: minBucket[index] = arr[i] else: minBucket[index] = min(minBucket[index], arr[i]) # Finding maximum difference between # maximum value of previous bucket # minus minimum of current bucket. prev_val, max_gap = minVal, 0 for i in range(0, n - 1): if minBucket[i] == INT_MAX: continue max_gap = max(max_gap, minBucket[i] - prev_val) prev_val = maxBucket[i] max_gap = max(max_gap, maxVal - prev_val) return max_gap # Driver Codeif __name__ == \"__main__\": arr = [1, 10, 5] n = len(arr) INT_MIN, INT_MAX = float('-inf'), float('inf') print(maxSortedAdjacentDiff(arr, n)) # This code is contributed by Rituraj Jain", "e": 33155, "s": 31173, "text": null }, { "code": "// C# program to find maximum// adjacent difference between// two adjacent after sorting.using System;using System.Linq; class GFG{static int maxSortedAdjacentDiff(int[] arr, int n){ // Find maximum and minimum in arr[] int maxVal = arr[0]; int minVal = arr[0]; for (int i = 1; i < n; i++) { maxVal = Math.Max(maxVal, arr[i]); minVal = Math.Min(minVal, arr[i]); } // Arrays to store maximum and // minimum values in n-1 buckets // of differences. int []maxBucket = new int[n - 1]; int []minBucket = new int[n - 1]; maxBucket = maxBucket.Select(i => int.MinValue).ToArray(); minBucket = minBucket.Select(i => int.MaxValue).ToArray(); // maxBucket.Fill(int.MinValue); // Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE); // Expected gap for every bucket. float delta = (float) (maxVal - minVal) / (float) (n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (int i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) { continue; } // Finding index of bucket. int index = (int) (Math.Round((arr[i] - minVal) / delta)); // Filling/Updating maximum value of bucket if (maxBucket[index] == int.MinValue) { maxBucket[index] = arr[i]; } else { maxBucket[index] = Math.Max(maxBucket[index], arr[i]); } // Filling/Updating minimum value of bucket if (minBucket[index] == int.MaxValue) { minBucket[index] = arr[i]; } else { minBucket[index] = Math.Min(minBucket[index], arr[i]); } } // Finding maximum difference between // maximum value of previous bucket // minus minimum of current bucket. int prev_val = minVal; int max_gap = 0; for (int i = 0; i < n - 1; i++) { if (minBucket[i] == int.MaxValue) { continue; } max_gap = Math.Max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.Max(max_gap, maxVal - prev_val); return max_gap;} // Driver Codepublic static void Main(){ int []arr = {1, 10, 5}; int n = arr.Length; Console.Write(maxSortedAdjacentDiff(arr, n));}} // This code contributed by 29AjayKumar", "e": 35790, "s": 33155, "text": null }, { "code": "<script> // JavaScript program to find maximum adjacent difference// between two adjacent after sorting. function maxSortedAdjacentDiff(arr, n){ // Find maximum and minimum in arr[] var maxVal = arr[0], minVal = arr[0]; for (var i = 1; i < n; i++) { maxVal = Math.max(maxVal, arr[i]); minVal = Math.min(minVal, arr[i]); } // Arrays to store maximum and minimum values // in n-1 buckets of differences. var maxBucket = Array(n-1).fill(-1000000000); var minBucket = Array(n-1).fill(1000000000); // Expected gap for every bucket. var delta = (maxVal - minVal) / (n - 1); // Traversing through array elements and // filling in appropriate bucket if bucket // is empty. Else updating bucket values. for (var i = 0; i < n; i++) { if (arr[i] == maxVal || arr[i] == minVal) continue; // Finding index of bucket. var index = Math.floor((arr[i] - minVal) / delta); maxBucket[index] = Math.max(maxBucket[index], arr[i]); minBucket[index] = Math.min(minBucket[index], arr[i]); } // Finding maximum difference between maximum value // of previous bucket minus minimum of current bucket. var prev_val = minVal; var max_gap = 0; for (var i = 0; i < n - 1; i++) { if (minBucket[i] == 1000000000) continue; max_gap = Math.max(max_gap, minBucket[i] - prev_val); prev_val = maxBucket[i]; } max_gap = Math.max(max_gap, maxVal - prev_val); return max_gap;} var arr = [1, 10, 5];var n = arr.length;document.write( maxSortedAdjacentDiff(arr, n)); </script>", "e": 37396, "s": 35790, "text": null }, { "code": null, "e": 37398, "s": 37396, "text": "5" }, { "code": null, "e": 37442, "s": 37398, "text": "Time complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 37452, "s": 37442, "text": "Rajput-Ji" }, { "code": null, "e": 37464, "s": 37452, "text": "29AjayKumar" }, { "code": null, "e": 37477, "s": 37464, "text": "rituraj_jain" }, { "code": null, "e": 37490, "s": 37477, "text": "nehal sharma" }, { "code": null, "e": 37505, "s": 37490, "text": "2701gouravgoel" }, { "code": null, "e": 37512, "s": 37505, "text": "rrrtnx" }, { "code": null, "e": 37529, "s": 37512, "text": "khushboogoyal499" }, { "code": null, "e": 37550, "s": 37529, "text": "Pigeonhole Principle" }, { "code": null, "e": 37557, "s": 37550, "text": "Arrays" }, { "code": null, "e": 37567, "s": 37557, "text": "Searching" }, { "code": null, "e": 37574, "s": 37567, "text": "Arrays" }, { "code": null, "e": 37584, "s": 37574, "text": "Searching" }, { "code": null, "e": 37682, "s": 37584, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37750, "s": 37682, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37794, "s": 37750, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37826, "s": 37794, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37849, "s": 37826, "text": "Introduction to Arrays" }, { "code": null, "e": 37894, "s": 37849, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 37962, "s": 37894, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37986, "s": 37962, "text": "Find the Missing Number" }, { "code": null, "e": 38042, "s": 37986, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 38086, "s": 38042, "text": "Program to find largest element in an array" } ]
Minimum steps to make all the elements of the array divisible by 4 in C++
Given an array of size n, the task iss to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array If input array is {1, 2, 0, 2, 4, 3} then 3 operations are required − 1 + 3 = 4 2 + 2 = 4 0 + 4 = 4 1. Sum of all the elements of the array should be divisible by If not, this task is not possible 2. Initialize an array namely modulus of size 4 to 0 3. Initialize a counter to 0. It will keep track of number of steps done 4. Traverse through the input array and take modulus 4 of each element 5. Increment the value of the mod 4 value in the modulus array by 1 6. modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element 7. modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both 8. Every 2 elements of modulus[2] can be combined to get an element divisible to 4. 9. For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3]. 10. Now, increment count by half modulus[2]. We take half because every two elements are combined as one 11. The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4 Live Demo #include <bits/stdc++.h> using namespace std; int getMinRequiredSteps(int arr[], int n) { int count = 0; int modulus[4] = {0}; int sum = 0; for (int i = 0; i < n; i++) { int mod = arr[i] % 4; sum += mod; modulus[mod]++; } if (sum % 4 != 0) { return -1; } else { if (modulus[1] > modulus[3]) { count += modulus[3]; } else { count += modulus[1]; } modulus[1] -= count; modulus[3] -= count; modulus[2] += modulus[1] / 2; modulus[2] += modulus[3] / 2; count += modulus[1] / 2; count += modulus[3] / 2; count += modulus[2] / 2; return count; } } int main() { int arr[] = {1, 2, 0, 2, 4, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum required steps = " << getMinRequiredSteps(arr, n) << endl; return 0; } When you compile and execute above program. It generates following output Minimum required steps = 2
[ { "code": null, "e": 1314, "s": 1062, "text": "Given an array of size n, the task iss to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array" }, { "code": null, "e": 1384, "s": 1314, "text": "If input array is {1, 2, 0, 2, 4, 3} then 3 operations are\nrequired −" }, { "code": null, "e": 1414, "s": 1384, "text": "1 + 3 = 4\n2 + 2 = 4\n0 + 4 = 4" }, { "code": null, "e": 2446, "s": 1414, "text": "1. Sum of all the elements of the array should be divisible by If not, this task is not possible\n2. Initialize an array namely modulus of size 4 to 0\n3. Initialize a counter to 0. It will keep track of number of steps done\n4. Traverse through the input array and take modulus 4 of each element\n5. Increment the value of the mod 4 value in the modulus array by 1\n6. modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element\n7. modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both\n8. Every 2 elements of modulus[2] can be combined to get an element divisible to 4.\n9. For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3].\n10. Now, increment count by half modulus[2]. We take half because every two elements are combined as one\n11. The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4" }, { "code": null, "e": 2457, "s": 2446, "text": " Live Demo" }, { "code": null, "e": 3319, "s": 2457, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMinRequiredSteps(int arr[], int n) {\n int count = 0;\n int modulus[4] = {0};\n int sum = 0;\n for (int i = 0; i < n; i++) {\n int mod = arr[i] % 4;\n sum += mod;\n modulus[mod]++;\n }\n if (sum % 4 != 0) {\n return -1;\n } else {\n if (modulus[1] > modulus[3]) {\n count += modulus[3];\n }\n else {\n count += modulus[1];\n }\n modulus[1] -= count;\n modulus[3] -= count;\n modulus[2] += modulus[1] / 2;\n modulus[2] += modulus[3] / 2;\n count += modulus[1] / 2;\n count += modulus[3] / 2;\n count += modulus[2] / 2;\n return count;\n }\n}\nint main() {\n int arr[] = {1, 2, 0, 2, 4, 3};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Minimum required steps = \" << getMinRequiredSteps(arr, n) << endl;\n return 0;\n}" }, { "code": null, "e": 3393, "s": 3319, "text": "When you compile and execute above program. It generates following output" }, { "code": null, "e": 3420, "s": 3393, "text": "Minimum required steps = 2" } ]
PHP Type Juggling
PHP is known as a dynamically typed language. Explicit type declaration of a variable is neither needed nor supported in PHP. Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling. $var="Hello"; // variable is string type $var=100; //same variable now becomes int Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression Live Demo <?php $var1=100; $var2="100"; $var3=$var1+$var2; var_dump($var3); ?> This will produce following result − int(200) If a string starts with digits, trailing non-numeric characters if any, are ignored while performing calculation. However, PHP parser issues a notice as shown below <?php $var1=100; $var2="100 days"; $var3=$var1+var2; var_dump($var3); ?> This will produce following result − PHP Notice: A non well formed numeric value encountered in ... int(200) Type casting forces a variable to be used as a certain type. Following script shows example of different type cast operators Live Demo <?php $var1=100; $var2=(boolean)$var1; $var3=(string)$var1; $var4=(array)$var1; $var5=(object)$var1; var_dump($var2, $var3, $var4, $var5); ?> This will produce following result − bool(true) string(3) "100" array(1) { [0]=> int(100) } object(stdClass)#1 (1) { ["scalar"]=> int(100) } Casting a variable to string can also be done by enclosing in double quoted string Live Demo <?php $var1=100.50; $var2=(string)$var1; $var3="$var1"; var_dump($var2, $var3); ?> This will produce following result − string(5) "100.5" string(5) "100.5"
[ { "code": null, "e": 1483, "s": 1062, "text": "PHP is known as a dynamically typed language. Explicit type declaration of a variable is neither needed nor supported in PHP. Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling." }, { "code": null, "e": 1566, "s": 1483, "text": "$var=\"Hello\"; // variable is string type\n$var=100; //same variable now becomes int" }, { "code": null, "e": 1760, "s": 1566, "text": "Type juggling also takes place during calculation of expression. In this example, a string variable containing digits is automatically converted to integer for evaluation of addition expression" }, { "code": null, "e": 1771, "s": 1760, "text": " Live Demo" }, { "code": null, "e": 1840, "s": 1771, "text": "<?php\n$var1=100;\n$var2=\"100\";\n$var3=$var1+$var2;\nvar_dump($var3);\n?>" }, { "code": null, "e": 1877, "s": 1840, "text": "This will produce following result −" }, { "code": null, "e": 1886, "s": 1877, "text": "int(200)" }, { "code": null, "e": 2051, "s": 1886, "text": "If a string starts with digits, trailing non-numeric characters if any, are ignored while performing calculation. However, PHP parser issues a notice as shown below" }, { "code": null, "e": 2124, "s": 2051, "text": "<?php\n$var1=100;\n$var2=\"100 days\";\n$var3=$var1+var2;\nvar_dump($var3);\n?>" }, { "code": null, "e": 2161, "s": 2124, "text": "This will produce following result −" }, { "code": null, "e": 2233, "s": 2161, "text": "PHP Notice: A non well formed numeric value encountered in ...\nint(200)" }, { "code": null, "e": 2358, "s": 2233, "text": "Type casting forces a variable to be used as a certain type. Following script shows example of different type cast operators" }, { "code": null, "e": 2369, "s": 2358, "text": " Live Demo" }, { "code": null, "e": 2511, "s": 2369, "text": "<?php\n$var1=100;\n$var2=(boolean)$var1;\n$var3=(string)$var1;\n$var4=(array)$var1;\n$var5=(object)$var1;\nvar_dump($var2, $var3, $var4, $var5);\n?>" }, { "code": null, "e": 2548, "s": 2511, "text": "This will produce following result −" }, { "code": null, "e": 2664, "s": 2548, "text": "bool(true)\nstring(3) \"100\"\narray(1) {\n [0]=>\n int(100)\n}\nobject(stdClass)#1 (1) {\n [\"scalar\"]=>\n int(100)\n}" }, { "code": null, "e": 2747, "s": 2664, "text": "Casting a variable to string can also be done by enclosing in double quoted string" }, { "code": null, "e": 2758, "s": 2747, "text": " Live Demo" }, { "code": null, "e": 2841, "s": 2758, "text": "<?php\n$var1=100.50;\n$var2=(string)$var1;\n$var3=\"$var1\";\nvar_dump($var2, $var3);\n?>" }, { "code": null, "e": 2878, "s": 2841, "text": "This will produce following result −" }, { "code": null, "e": 2914, "s": 2878, "text": "string(5) \"100.5\"\nstring(5) \"100.5\"" } ]
Spring Batch - MySQL to XML
In this chapter, we will create a Spring Batch application which uses a MySQL reader and an XML Writer. Reader − The reader we are using in the application is JdbcCursorItemReader to read data from MySQL database. Assume we have created a table in the MySQL database as shown below − CREATE TABLE details.xml_mysql( person_id int(10) NOT NULL, sales VARCHAR(20), qty int(3), staffName VARCHAR(20), date VARCHAR(20) ); Assume we have inserted the following records in to it. mysql> select * from tutorialsdata; +-------------+-----------------+----------------+-----------------+ | tutorial_id | tutorial_author | tutorial_title | submission_date | +-------------+-----------------+----------------+-----------------+ | 101 | Sanjay | Learn Java | 06-05-2007 | | 102 | Abdul S | Learn MySQL | 19-04-2007 | | 103 | Krishna Kasyap | Learn JavaFX | 06-07-2017 | +-------------+-----------------+----------------+-----------------+ 3 rows in set (0.00 sec) Writer − The Writer we are using in the application is StaxEventItemWriter to write the data to the XML file. Processor − The Processor we are using in the application is a custom processor which just prints the records read from the CSV file. Following is the configuration file of our sample Spring Batch application. In this file, we will define the Job and the Steps. In addition to these, we also define the beans for ItemReader, ItemProcessor, and ItemWriter. (Here, we associate them with their respective classes and pass the values for the required properties to configure them.) <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:batch = "http://www.springframework.org/schema/batch" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:util = "http://www.springframework.org/schema/util" xsi:schemaLocation = " http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <import resource = "../jobs/context.xml" /> <bean id = "report" class = "Report" scope = "prototype" /> <bean id = "itemProcessor" class = "CustomItemProcessor" /> <batch:job id = "helloWorldJob"> <batch:step id = "step1"> <batch:tasklet> <batch:chunk reader = "dbItemReader" writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10"> </batch:chunk> </batch:tasklet> </batch:step> </batch:job> <bean id = "dbItemReader" class = "org.springframework.batch.item.database.JdbcCursorItemReader" scope = "step"> <property name = "dataSource" ref = "dataSource" /> <property name = "sql" value = "select * from tutorials_data" /> <property name = "rowMapper"> <bean class = "TutorialRowMapper" /> </property> </bean> <bean id = "mysqlItemWriter" class = "org.springframework.batch.item.xml.StaxEventItemWriter"> <property name = "resource" value = "file:xml/outputs/tutorials.xml" /> <property name = "marshaller" ref = "reportMarshaller" /> <property name = "rootTagName" value = "Tutorial" /> </bean> <bean id = "reportMarshaller" class = "org.springframework.oxm.jaxb.Jaxb2Marshaller"> <property name = "classesToBeBound"> <list> <value>Tutorial</value> </list> </property> </bean> </beans> Following is the context.xml of our Spring Batch application. In this file, we will define the beans like job repository, job launcher, and transaction manager. <beans xmlns = " http://www.springframework.org/schema/beans" xmlns:jdbc = "http://www.springframework.org/schema/jdbc" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd "> <!-- stored job-meta in database --> <bean id = "jobRepository" class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name = "dataSource" ref = "dataSource" /> <property name = "transactionManager" ref = "transactionManager" /> <property name = "databaseType" value = "mysql" /> </bean> <bean id = "transactionManager" class = "org.springframework.batch.support.transaction.ResourcelessTransactionMana ger" /> <bean id = "jobLauncher" class = "org.springframework.batch.core.launch.support.SimpleJobLauncher"> <property name = "jobRepository" ref = "jobRepository" /> </bean> <!-- connect to MySQL database --> <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> <property name = "url" value = "jdbc:mysql://localhost:3306/details" /> <property name = "username" value = "myuser" /> <property name = "password" value = "password" /> </bean> <!-- create job-meta tables automatically --> <jdbc:initialize-database data-source = "dataSource"> <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql" /> <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql" /> </jdbc:initialize-database> </beans> Following is the Processor class. In this class, we write the code of processing in the application. Here, we are printing the contents of each record. import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> { @Override public Tutorial process(Tutorial item) throws Exception { System.out.println("Processing..." + item); return item; } } Following is the TutorialRowMapper class which sets the data to the Tutorial class. import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class TutorialRowMapper implements RowMapper<Tutorial> { @Override public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException { Tutorial tutorial = new Tutorial(); tutorial.setTutorial_id(rs.getInt("tutorial_id")); tutorial.setTutorial_author(rs.getString("tutorial_author")); tutorial.setTutorial_title(rs.getString("tutorial_title")); tutorial.setSubmission_date(rs.getString("submission_date")); return tutorial; } } Following is the Tutorial class. It is a simple Java class with setter and getter methods. In this class, we are using annotations to associate the methods of this class with the tags of the XML file. import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "details") public class Tutorial { int tutorial_id; String tutorial_author; String submission_date; @XmlAttribute(name = "tutorial_id") public int getTutorial_id() { return tutorial_id; } public void setTutorial_id(int tutorial_id) { this.tutorial_id = tutorial_id; } @XmlElement(name = "tutorial_author") public String getTutorial_author() { return tutorial_author; } public void setTutorial_author(String tutorial_author) { this.tutorial_author = tutorial_author; } @XmlElement(name = "tutorial_title") public String getTutorial_title() { return tutorial_title; } public void setTutorial_title(String tutorial_title) { this.tutorial_title = tutorial_title; } @XmlElement(name = "submission_date") public String getSubmission_date() { return submission_date; } public void setSubmission_date(String submission_date) { this.submission_date = submission_date; } public String toString() { return " [Tutorial Id=" + tutorial_id + ", Tutorial Author =" + tutorial_author + ", Tutorial Title =" + tutorial_title + ", Submission Date =" + submission_date + "]"; } } Following is the code which launces the batch process. In this class, we will launch the Batch Application by running the JobLauncher. import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) throws Exception { String[] springConfig = { "jobs/job_hello_world.xml" }; // Creating the application context object ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); // Creating the job launcher JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher"); // Creating the job Job job = (Job) context.getBean("helloWorldJob"); // Executing the JOB JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Exit Status : " + execution.getStatus()); } } On executing this application, it will produce the following output. May 08, 2017 11:32:06 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date [Mon May 08 11:32:06 IST 2017]; root of context hierarchy May 08, 2017 11:32:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [jobs/job_hello_world.xml] May 08, 2017 11:32:07 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions May 08, 2017 11:32:14 AM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1] Processing... [Tutorial Id=101, Tutorial Author=Sanjay, Tutorial Title=Learn Java, Submission Date=06-05-2007] Processing... [Tutorial Id=102, Tutorial Author=Abdul S, Tutorial Title=Learn MySQL, Submission Date=19-04-2007] Processing... [Tutorial Id=103, Tutorial Author=Krishna Kasyap, Tutorial Title=Learn JavaFX, Submission Date=06-07-2017] May 08, 2017 11:32:14 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] Exit Status : COMPLETED This will generate an XML file with the following contents. <?xml version = "1.0" encoding = "UTF-8"?> <Tutorial> <details tutorial_id = "101"> <submission_date>06-05-2007</submission_date> <tutorial_author>Sanjay</tutorial_author> <tutorial_title>Learn Java</tutorial_title> </details> <details tutorial_id = "102"> <submission_date>19-04-2007</submission_date> <tutorial_author>Abdul S</tutorial_author> <tutorial_title>Learn MySQL</tutorial_title> </details> <details tutorial_id = "103"> <submission_date>06-07-2017</submission_date> <tutorial_author>Krishna Kasyap</tutorial_author> <tutorial_title>Learn JavaFX</tutorial_title> </details> </Tutorial> 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2032, "s": 1928, "text": "In this chapter, we will create a Spring Batch application which uses a MySQL reader and an XML Writer." }, { "code": null, "e": 2142, "s": 2032, "text": "Reader − The reader we are using in the application is JdbcCursorItemReader to read data from MySQL database." }, { "code": null, "e": 2212, "s": 2142, "text": "Assume we have created a table in the MySQL database as shown below −" }, { "code": null, "e": 2367, "s": 2212, "text": "CREATE TABLE details.xml_mysql( \n person_id int(10) NOT NULL, \n sales VARCHAR(20), \n qty int(3), \n staffName VARCHAR(20), \n date VARCHAR(20) \n);" }, { "code": null, "e": 2423, "s": 2367, "text": "Assume we have inserted the following records in to it." }, { "code": null, "e": 2977, "s": 2423, "text": "mysql> select * from tutorialsdata; \n+-------------+-----------------+----------------+-----------------+ \n| tutorial_id | tutorial_author | tutorial_title | submission_date | \n+-------------+-----------------+----------------+-----------------+ \n| 101 | Sanjay | Learn Java | 06-05-2007 | \n| 102 | Abdul S | Learn MySQL | 19-04-2007 | \n| 103 | Krishna Kasyap | Learn JavaFX | 06-07-2017 | \n+-------------+-----------------+----------------+-----------------+ \n3 rows in set (0.00 sec) \n" }, { "code": null, "e": 3087, "s": 2977, "text": "Writer − The Writer we are using in the application is StaxEventItemWriter to write the data to the XML file." }, { "code": null, "e": 3221, "s": 3087, "text": "Processor − The Processor we are using in the application is a custom processor which just prints the records read from the CSV file." }, { "code": null, "e": 3566, "s": 3221, "text": "Following is the configuration file of our sample Spring Batch application. In this file, we will define the Job and the Steps. In addition to these, we also define the beans for ItemReader, ItemProcessor, and ItemWriter. (Here, we associate them with their respective classes and pass the values for the required properties to configure them.)" }, { "code": null, "e": 5570, "s": 3566, "text": "<beans xmlns = \"http://www.springframework.org/schema/beans\" \n xmlns:batch = \"http://www.springframework.org/schema/batch\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:util = \"http://www.springframework.org/schema/util\" \n xsi:schemaLocation = \" http://www.springframework.org/schema/batch \n http://www.springframework.org/schema/batch/spring-batch-2.2.xsd \n http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd\"> \n \n <import resource = \"../jobs/context.xml\" /> \n \n <bean id = \"report\" class = \"Report\" scope = \"prototype\" /> \n <bean id = \"itemProcessor\" class = \"CustomItemProcessor\" /> \n \n <batch:job id = \"helloWorldJob\"> \n <batch:step id = \"step1\"> \n <batch:tasklet> \n <batch:chunk reader = \"dbItemReader\" \n writer = \"mysqlItemWriter\" processor = \"itemProcessor\" commit-interval = \"10\">\n </batch:chunk> \n </batch:tasklet> \n </batch:step> \n </batch:job> \n \n <bean id = \"dbItemReader\" \n class = \"org.springframework.batch.item.database.JdbcCursorItemReader\" scope = \"step\"> \n <property name = \"dataSource\" ref = \"dataSource\" /> \n <property name = \"sql\" value = \"select * from tutorials_data\" /> \n <property name = \"rowMapper\"> \n <bean class = \"TutorialRowMapper\" /> \n </property> \n </bean> \n <bean id = \"mysqlItemWriter\" \n class = \"org.springframework.batch.item.xml.StaxEventItemWriter\"> \n <property name = \"resource\" value = \"file:xml/outputs/tutorials.xml\" /> \n <property name = \"marshaller\" ref = \"reportMarshaller\" />\n <property name = \"rootTagName\" value = \"Tutorial\" /> \n </bean> \n \n <bean id = \"reportMarshaller\" class = \"org.springframework.oxm.jaxb.Jaxb2Marshaller\"> \n <property name = \"classesToBeBound\"> \n <list> \n <value>Tutorial</value> \n </list> \n </property> \n </bean> \n</beans> " }, { "code": null, "e": 5731, "s": 5570, "text": "Following is the context.xml of our Spring Batch application. In this file, we will define the beans like job repository, job launcher, and transaction manager." }, { "code": null, "e": 7641, "s": 5731, "text": "<beans xmlns = \" http://www.springframework.org/schema/beans\" \n xmlns:jdbc = \"http://www.springframework.org/schema/jdbc\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.2.xsd \n http://www.springframework.org/schema/jdbc \n http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd \"> \n \n <!-- stored job-meta in database --> \n <bean id = \"jobRepository\" \n class = \"org.springframework.batch.core.repository.support.JobRepositoryFactoryBean\"> \n <property name = \"dataSource\" ref = \"dataSource\" /> \n <property name = \"transactionManager\" ref = \"transactionManager\" /> \n <property name = \"databaseType\" value = \"mysql\" /> \n </bean> \n \n <bean id = \"transactionManager\" \n class = \"org.springframework.batch.support.transaction.ResourcelessTransactionMana ger\" /> \n <bean id = \"jobLauncher\"\n class = \"org.springframework.batch.core.launch.support.SimpleJobLauncher\"> \n <property name = \"jobRepository\" ref = \"jobRepository\" /> \n </bean> \n \n <!-- connect to MySQL database --> \n <bean id = \"dataSource\" \n class = \"org.springframework.jdbc.datasource.DriverManagerDataSource\"> \n <property name = \"driverClassName\" value = \"com.mysql.jdbc.Driver\" /> \n <property name = \"url\" value = \"jdbc:mysql://localhost:3306/details\" /> \n <property name = \"username\" value = \"myuser\" /> \n <property name = \"password\" value = \"password\" /> \n </bean> \n \n <!-- create job-meta tables automatically --> \n <jdbc:initialize-database data-source = \"dataSource\"> \n <jdbc:script location = \"org/springframework/batch/core/schema-drop-mysql.sql\" /> \n <jdbc:script location = \"org/springframework/batch/core/schema-mysql.sql\" /> \n </jdbc:initialize-database> \n</beans> " }, { "code": null, "e": 7793, "s": 7641, "text": "Following is the Processor class. In this class, we write the code of processing in the application. Here, we are printing the contents of each record." }, { "code": null, "e": 8088, "s": 7793, "text": "import org.springframework.batch.item.ItemProcessor; \n\npublic class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> { \n\n @Override \n public Tutorial process(Tutorial item) throws Exception { \n System.out.println(\"Processing...\" + item); \n return item; \n } \n} " }, { "code": null, "e": 8172, "s": 8088, "text": "Following is the TutorialRowMapper class which sets the data to the Tutorial class." }, { "code": null, "e": 8789, "s": 8172, "text": "import java.sql.ResultSet; \nimport java.sql.SQLException; \nimport org.springframework.jdbc.core.RowMapper; \n\npublic class TutorialRowMapper implements RowMapper<Tutorial> { \n \n @Override \n public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException { \n \n Tutorial tutorial = new Tutorial(); \n tutorial.setTutorial_id(rs.getInt(\"tutorial_id\")); \n tutorial.setTutorial_author(rs.getString(\"tutorial_author\")); \n tutorial.setTutorial_title(rs.getString(\"tutorial_title\")); \n tutorial.setSubmission_date(rs.getString(\"submission_date\")); \n return tutorial; \n } \n}" }, { "code": null, "e": 8990, "s": 8789, "text": "Following is the Tutorial class. It is a simple Java class with setter and getter methods. In this class, we are using annotations to associate the methods of this class with the tags of the XML file." }, { "code": null, "e": 10439, "s": 8990, "text": "import javax.xml.bind.annotation.XmlAttribute; \nimport javax.xml.bind.annotation.XmlElement; \nimport javax.xml.bind.annotation.XmlRootElement; \n\n@XmlRootElement(name = \"details\") \npublic class Tutorial { \n \n int tutorial_id; \n String tutorial_author;\n String submission_date; \n \n @XmlAttribute(name = \"tutorial_id\") \n public int getTutorial_id() { \n return tutorial_id; \n } \n \n public void setTutorial_id(int tutorial_id) { \n this.tutorial_id = tutorial_id; \n } \n \n @XmlElement(name = \"tutorial_author\") \n public String getTutorial_author() { \n return tutorial_author; \n } \n \n public void setTutorial_author(String tutorial_author) { \n this.tutorial_author = tutorial_author; \n } \n \n @XmlElement(name = \"tutorial_title\") \n public String getTutorial_title() { \n return tutorial_title; \n } \n \n public void setTutorial_title(String tutorial_title) { \n this.tutorial_title = tutorial_title; \n } \n \n @XmlElement(name = \"submission_date\") \n public String getSubmission_date() { \n return submission_date; \n }\n\n public void setSubmission_date(String submission_date) { \n this.submission_date = submission_date; \n } \n\n public String toString() { \n return \" [Tutorial Id=\" + tutorial_id + \", \n Tutorial Author =\" + tutorial_author + \", \n Tutorial Title =\" + tutorial_title + \", \n Submission Date =\" + submission_date + \"]\"; \n } \n} " }, { "code": null, "e": 10574, "s": 10439, "text": "Following is the code which launces the batch process. In this class, we will launch the Batch Application by running the JobLauncher." }, { "code": null, "e": 11621, "s": 10574, "text": "import org.springframework.batch.core.Job; \nimport org.springframework.batch.core.JobExecution; \nimport org.springframework.batch.core.JobParameters; \nimport org.springframework.batch.core.launch.JobLauncher; \nimport org.springframework.context.ApplicationContext; \nimport org.springframework.context.support.ClassPathXmlApplicationContext; \n\npublic class App { \n public static void main(String[] args) throws Exception { \n \n String[] springConfig = { \"jobs/job_hello_world.xml\" }; \n \n // Creating the application context object \n ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); \n \n // Creating the job launcher \n JobLauncher jobLauncher = (JobLauncher) context.getBean(\"jobLauncher\"); \n \n // Creating the job \n Job job = (Job) context.getBean(\"helloWorldJob\");\n \n // Executing the JOB \n JobExecution execution = jobLauncher.run(job, new JobParameters()); \n System.out.println(\"Exit Status : \" + execution.getStatus()); \n } \n} " }, { "code": null, "e": 11690, "s": 11621, "text": "On executing this application, it will produce the following output." }, { "code": null, "e": 12991, "s": 11690, "text": "May 08, 2017 11:32:06 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh \nINFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: \nstartup date [Mon May 08 11:32:06 IST 2017]; root of context hierarchy \nMay 08, 2017 11:32:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions \nINFO: Loading XML bean definitions from class path resource [jobs/job_hello_world.xml] \nMay 08, 2017 11:32:07 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions \nMay 08, 2017 11:32:14 AM org.springframework.batch.core.job.SimpleStepHandler handleStep \nINFO: Executing step: [step1] \nProcessing... [Tutorial Id=101, Tutorial Author=Sanjay, \nTutorial Title=Learn Java, Submission Date=06-05-2007] \nProcessing... [Tutorial Id=102, Tutorial Author=Abdul S, \nTutorial Title=Learn MySQL, Submission Date=19-04-2007] \nProcessing... [Tutorial Id=103, Tutorial Author=Krishna Kasyap, \nTutorial Title=Learn JavaFX, Submission Date=06-07-2017] \nMay 08, 2017 11:32:14 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run \nINFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: \n[{}] and the following status: [COMPLETED] \nExit Status : COMPLETED\n" }, { "code": null, "e": 13051, "s": 12991, "text": "This will generate an XML file with the following contents." }, { "code": null, "e": 13746, "s": 13051, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<Tutorial> \n <details tutorial_id = \"101\"> \n <submission_date>06-05-2007</submission_date> \n <tutorial_author>Sanjay</tutorial_author> \n <tutorial_title>Learn Java</tutorial_title> \n </details> \n \n <details tutorial_id = \"102\"> \n <submission_date>19-04-2007</submission_date> \n <tutorial_author>Abdul S</tutorial_author> \n <tutorial_title>Learn MySQL</tutorial_title> \n </details> \n \n <details tutorial_id = \"103\"> \n <submission_date>06-07-2017</submission_date> \n <tutorial_author>Krishna Kasyap</tutorial_author> \n <tutorial_title>Learn JavaFX</tutorial_title> \n </details> \n</Tutorial>" }, { "code": null, "e": 13780, "s": 13746, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 13794, "s": 13780, "text": " Karthikeya T" }, { "code": null, "e": 13827, "s": 13794, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 13842, "s": 13827, "text": " Chaand Sheikh" }, { "code": null, "e": 13877, "s": 13842, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 13889, "s": 13877, "text": " Senol Atac" }, { "code": null, "e": 13924, "s": 13889, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13936, "s": 13924, "text": " Senol Atac" }, { "code": null, "e": 13971, "s": 13936, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 13983, "s": 13971, "text": " Senol Atac" }, { "code": null, "e": 14016, "s": 13983, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 14028, "s": 14016, "text": " Senol Atac" }, { "code": null, "e": 14035, "s": 14028, "text": " Print" }, { "code": null, "e": 14046, "s": 14035, "text": " Add Notes" } ]
Java Program to convert from integer to String
To convert integer to string, firstly set an integer. int val = 150; Now use the Integer.toString() method and pass the same int value. The method returns a string representation. String myStr = Integer.toString(val); Let us now see the complete example. Live Demo public class Demo { public static void main( String args[] ) { int val = 150; // integer to string String myStr = Integer.toString(val); System.out.println("String: "+myStr); } } String: 150
[ { "code": null, "e": 1116, "s": 1062, "text": "To convert integer to string, firstly set an integer." }, { "code": null, "e": 1131, "s": 1116, "text": "int val = 150;" }, { "code": null, "e": 1242, "s": 1131, "text": "Now use the Integer.toString() method and pass the same int value. The method returns a string representation." }, { "code": null, "e": 1280, "s": 1242, "text": "String myStr = Integer.toString(val);" }, { "code": null, "e": 1317, "s": 1280, "text": "Let us now see the complete example." }, { "code": null, "e": 1328, "s": 1317, "text": " Live Demo" }, { "code": null, "e": 1537, "s": 1328, "text": "public class Demo {\n public static void main( String args[] ) {\n int val = 150;\n // integer to string\n String myStr = Integer.toString(val);\n System.out.println(\"String: \"+myStr);\n }\n}" }, { "code": null, "e": 1549, "s": 1537, "text": "String: 150" } ]
What is a reference/ref parameter of an array type in C#?
Declare the reference parameters using the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare a ref parameter − public void swap(ref int x, ref int y) {} Declare a ref parameter of array type − static void Display(ref int[] myArr) The following is an example showing how to work with ref parameter of an array type in C# − class TestRef { static void Display(ref int[] myArr) { if (myArr == null) { myArr = new int[10]; } myArr[0] = 345; myArr[1] = 755; myArr[2] = 231; } static void Main() { int[] arr = { 98, 12, 65, 45, 90, 34, 77 }; Display(ref arr); for (int i = 0; i < arr.Length; i++) { System.Console.Write(arr[i] + " "); } System.Console.ReadKey(); } }
[ { "code": null, "e": 1315, "s": 1062, "text": "Declare the reference parameters using the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters." }, { "code": null, "e": 1341, "s": 1315, "text": "Declare a ref parameter −" }, { "code": null, "e": 1383, "s": 1341, "text": "public void swap(ref int x, ref int y) {}" }, { "code": null, "e": 1423, "s": 1383, "text": "Declare a ref parameter of array type −" }, { "code": null, "e": 1460, "s": 1423, "text": "static void Display(ref int[] myArr)" }, { "code": null, "e": 1552, "s": 1460, "text": "The following is an example showing how to work with ref parameter of an array type in C# −" }, { "code": null, "e": 1986, "s": 1552, "text": "class TestRef {\n static void Display(ref int[] myArr) {\n if (myArr == null) {\n myArr = new int[10];\n }\n\n myArr[0] = 345;\n myArr[1] = 755;\n myArr[2] = 231;\n }\n\n static void Main() {\n int[] arr = { 98, 12, 65, 45, 90, 34, 77 };\n\n Display(ref arr);\n\n for (int i = 0; i < arr.Length; i++) {\n System.Console.Write(arr[i] + \" \");\n }\n\n System.Console.ReadKey();\n }\n}" } ]
GWT - CellTable Widget
The CellTable widget represents a A tabular view that supports paging and columns. Following is the declaration for com.google.gwt.user.cellview.client.CellTable<T> class − public class CellTable<T> extends AbstractHasData<T> CellTable() Constructs a table with a default page size of 15. CellTable(int pageSize) Constructs a table with the given page size. CellTable(int pageSize, CellTable.Resources resources) Constructs a table with the given page size with the specified CellTable.BasicResources. CellTable(int pageSize, CellTable.Resources resources, ProvidesKey<T> keyProvider) Constructs a table with the given page size, the specified CellTable.BasicResources, and the given key provider. CellTable(int pageSize, ProvidesKey<T> keyProvider) Constructs a table with the given page size and the given key provider. CellTable(ProvidesKey<T> keyProvider) Constructs a table with a default page size of 15, and the given key provider. void addColumn(Column<T,?> col) Adds a column to the table. void addColumn(Column<T,?> col, Header<?> header) Adds a column to the table with an associated header. void addColumn(Column<T,?> col, Header<?> header, Header<?> footer) Adds a column to the table with an associated header and footer. void addColumn(Column<T,?> col, SafeHtml headerHtml) Adds a column to the table with an associated SafeHtml header. void addColumn(Column<T,?> col, SafeHtml headerHtml, SafeHtml footerHtml) Adds a column to the table with an associated SafeHtml header and footer. void addColumn(Column<T,?> col, java.lang.String headerString) Adds a column to the table with an associated String header. void add Column (Column<T,?> col, java. lang. String header String, java.lang.String footer String) Adds a column to the table with an associated String header and footer. void addColumnStyleName(int index, java.lang.String styleName) Add a style name to the TableColElement at the specified index, creating it if necessary. protected Element convertToElements(SafeHtml html) Convert the specified HTML into DOM elements and return the parent of the DOM elements. protected boolean dependsOnSelection() Check whether or not the cells in the view depend on the selection state. protected void do Selection (Event event, T value, int row, int column) Deprecated. use Abstract Has Data.add Cell Preview Handler(com.google.gwt.view.client. Cell Preview Event.Handler) instead. int getBodyHeight() Return the height of the table body. protected Element getChildContainer() Return the element that holds the rendered cells. int getHeaderHeight() Return the height of the table header. protected Element getKeyboardSelectedElement() Get the element that has keyboard selection. TableRowElement getRowElement(int row) Get the TableRowElement for the specified row. protected boolean isKeyboardNavigationSuppressed() Check if keyboard navigation is being suppressed, such as when the user is editing a cell. protected void onBlur() Called when the widget is blurred. protected void onBrowserEvent2(Event event) Called after AbstractHasData.onBrowserEvent(Event) completes. protected void onFocus() Called when the widget is focused. void redrawFooters() Redraw the table's footers. void redrawHeaders() Redraw the table's headers. void removeColumn(Column<T,?> col) Remove a column. void removeColumn(int index) Remove a column. void removeColumnStyleName(int index, java.lang.String styleName) Remove a style from the TableColElement at the specified index. protected void renderRowValues(SafeHtmlBuilder sb, java.util.List<T> values, int start, SelectionModel<? super T> selectionModel) Render all row values into the specified SafeHtmlBuilder. protected void replaceAllChildren(java.util.List<T> values, SafeHtml html) Replace all children with the specified html. protected boolean resetFocusOnCell() Reset focus on the currently focused cell. protected void setKeyboardSelected(int index, boolean selected, boolean stealFocus) Update an element to reflect its keyboard selected state. void setRowStyles(RowStyles<T> rowStyles) Sets the object used to determine how a row is styled; the change will take effect the next time that the table is rendered. protected void setSelected(Element elem, boolean selected) Deprecated. this method is never called by AbstractHasData, render the selected styles in renderRowValues(SafeHtmlBuilder, List, int, SelectionModel) This class inherits methods from the following classes − com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.UIObject com.google.gwt.user.client.ui.Widget com.google.gwt.user.client.ui.Widget com.google.gwt.user.cellview.client.AbstractHasData com.google.gwt.user.cellview.client.AbstractHasData java.lang.Object java.lang.Object This example will take you through simple steps to show usage of a CellTable Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter − Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml. <?xml version = "1.0" encoding = "UTF-8"?> <module rename-to = 'helloworld'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name = 'com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. --> <inherits name = 'com.google.gwt.user.theme.clean.Clean'/> <!-- Specify the app entry point class. --> <entry-point class = 'com.tutorialspoint.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module> Following is the content of the modified Style Sheet file war/HelloWorld.css. body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; } Following is the content of the modified HTML host file war/HelloWorld.html. <html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>CellTable Widget Demonstration</h1> <div id = "gwtContainer"></div> </body> </html> Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of CellTable widget. package com.tutorialspoint.client; import java.util.Arrays; import java.util.Date; import java.util.List; import com.google.gwt.cell.client.DateCell; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client .HasKeyboardSelectionPolicy.KeyboardSelectionPolicy; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; public class HelloWorld implements EntryPoint { /** * A simple data type that represents a contact. */ private static class Contact { private final String address; private final Date birthday; private final String name; public Contact(String name, Date birthday, String address) { this.name = name; this.birthday = birthday; this.address = address; } } /** * The list of data to display. */ private static final List<Contact> CONTACTS = Arrays.asList( new Contact("John", new Date(80, 4, 12), "123 Fourth Avenue"), new Contact("Joe", new Date(85, 2, 22), "22 Lance Ln"), new Contact("George",new Date(46, 6, 6),"1600 Pennsylvania Avenue")); public void onModuleLoad() { // Create a CellTable. CellTable<Contact> table = new CellTable<Contact>(); table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED); // Add a text column to show the name. TextColumn<Contact> nameColumn = new TextColumn<Contact>() { @Override public String getValue(Contact object) { return object.name; } }; table.addColumn(nameColumn, "Name"); // Add a date column to show the birthday. DateCell dateCell = new DateCell(); Column<Contact, Date> dateColumn = new Column<Contact, Date>(dateCell) { @Override public Date getValue(Contact object) { return object.birthday; } }; table.addColumn(dateColumn, "Birthday"); // Add a text column to show the address. TextColumn<Contact> addressColumn = new TextColumn<Contact>() { @Override public String getValue(Contact object) { return object.address; } }; table.addColumn(addressColumn, "Address"); // Add a selection model to handle user selection. final SingleSelectionModel<Contact> selectionModel = new SingleSelectionModel<Contact>(); table.setSelectionModel(selectionModel); selectionModel.addSelectionChangeHandler( new SelectionChangeEvent.Handler() { public void onSelectionChange(SelectionChangeEvent event) { Contact selected = selectionModel.getSelectedObject(); if (selected != null) { Window.alert("You selected: " + selected.name); } } }); // Set the total row count. This isn't strictly necessary, // but it affects paging calculations, so its good habit to // keep the row count up to date. table.setRowCount(CONTACTS.size(), true); // Push the data into the widget. table.setRowData(0, CONTACTS); VerticalPanel panel = new VerticalPanel(); panel.setBorderWidth(1); panel.setWidth("400"); panel.add(table); // Add the widgets to the root panel. RootPanel.get().add(panel); } } Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result − Print Add Notes Bookmark this page
[ { "code": null, "e": 2106, "s": 2023, "text": "The CellTable widget represents a A tabular view that supports paging and columns." }, { "code": null, "e": 2196, "s": 2106, "text": "Following is the declaration for com.google.gwt.user.cellview.client.CellTable<T> class −" }, { "code": null, "e": 2252, "s": 2196, "text": "public class CellTable<T>\n extends AbstractHasData<T>" }, { "code": null, "e": 2264, "s": 2252, "text": "CellTable()" }, { "code": null, "e": 2315, "s": 2264, "text": "Constructs a table with a default page size of 15." }, { "code": null, "e": 2339, "s": 2315, "text": "CellTable(int pageSize)" }, { "code": null, "e": 2384, "s": 2339, "text": "Constructs a table with the given page size." }, { "code": null, "e": 2439, "s": 2384, "text": "CellTable(int pageSize, CellTable.Resources resources)" }, { "code": null, "e": 2528, "s": 2439, "text": "Constructs a table with the given page size with the specified CellTable.BasicResources." }, { "code": null, "e": 2611, "s": 2528, "text": "CellTable(int pageSize, CellTable.Resources resources, ProvidesKey<T> keyProvider)" }, { "code": null, "e": 2724, "s": 2611, "text": "Constructs a table with the given page size, the specified CellTable.BasicResources, and the given key provider." }, { "code": null, "e": 2776, "s": 2724, "text": "CellTable(int pageSize, ProvidesKey<T> keyProvider)" }, { "code": null, "e": 2848, "s": 2776, "text": "Constructs a table with the given page size and the given key provider." }, { "code": null, "e": 2886, "s": 2848, "text": "CellTable(ProvidesKey<T> keyProvider)" }, { "code": null, "e": 2965, "s": 2886, "text": "Constructs a table with a default page size of 15, and the given key provider." }, { "code": null, "e": 2997, "s": 2965, "text": "void addColumn(Column<T,?> col)" }, { "code": null, "e": 3025, "s": 2997, "text": "Adds a column to the table." }, { "code": null, "e": 3075, "s": 3025, "text": "void addColumn(Column<T,?> col, Header<?> header)" }, { "code": null, "e": 3129, "s": 3075, "text": "Adds a column to the table with an associated header." }, { "code": null, "e": 3197, "s": 3129, "text": "void addColumn(Column<T,?> col, Header<?> header, Header<?> footer)" }, { "code": null, "e": 3262, "s": 3197, "text": "Adds a column to the table with an associated header and footer." }, { "code": null, "e": 3315, "s": 3262, "text": "void addColumn(Column<T,?> col, SafeHtml headerHtml)" }, { "code": null, "e": 3378, "s": 3315, "text": "Adds a column to the table with an associated SafeHtml header." }, { "code": null, "e": 3452, "s": 3378, "text": "void addColumn(Column<T,?> col, SafeHtml headerHtml, SafeHtml footerHtml)" }, { "code": null, "e": 3526, "s": 3452, "text": "Adds a column to the table with an associated SafeHtml header and footer." }, { "code": null, "e": 3589, "s": 3526, "text": "void addColumn(Column<T,?> col, java.lang.String headerString)" }, { "code": null, "e": 3650, "s": 3589, "text": "Adds a column to the table with an associated String header." }, { "code": null, "e": 3750, "s": 3650, "text": "void add Column (Column<T,?> col, java. lang. String header String, java.lang.String footer String)" }, { "code": null, "e": 3822, "s": 3750, "text": "Adds a column to the table with an associated String header and footer." }, { "code": null, "e": 3885, "s": 3822, "text": "void addColumnStyleName(int index, java.lang.String styleName)" }, { "code": null, "e": 3975, "s": 3885, "text": "Add a style name to the TableColElement at the specified index, creating it if necessary." }, { "code": null, "e": 4026, "s": 3975, "text": "protected Element convertToElements(SafeHtml html)" }, { "code": null, "e": 4114, "s": 4026, "text": "Convert the specified HTML into DOM elements and return the parent of the DOM elements." }, { "code": null, "e": 4153, "s": 4114, "text": "protected boolean dependsOnSelection()" }, { "code": null, "e": 4227, "s": 4153, "text": "Check whether or not the cells in the view depend on the selection state." }, { "code": null, "e": 4299, "s": 4227, "text": "protected void do Selection (Event event, T value, int row, int column)" }, { "code": null, "e": 4423, "s": 4299, "text": "Deprecated. use Abstract Has Data.add Cell Preview Handler(com.google.gwt.view.client. Cell Preview Event.Handler) instead." }, { "code": null, "e": 4443, "s": 4423, "text": "int getBodyHeight()" }, { "code": null, "e": 4480, "s": 4443, "text": "Return the height of the table body." }, { "code": null, "e": 4518, "s": 4480, "text": "protected Element getChildContainer()" }, { "code": null, "e": 4568, "s": 4518, "text": "Return the element that holds the rendered cells." }, { "code": null, "e": 4590, "s": 4568, "text": "int getHeaderHeight()" }, { "code": null, "e": 4629, "s": 4590, "text": "Return the height of the table header." }, { "code": null, "e": 4676, "s": 4629, "text": "protected Element getKeyboardSelectedElement()" }, { "code": null, "e": 4721, "s": 4676, "text": "Get the element that has keyboard selection." }, { "code": null, "e": 4760, "s": 4721, "text": "TableRowElement getRowElement(int row)" }, { "code": null, "e": 4807, "s": 4760, "text": "Get the TableRowElement for the specified row." }, { "code": null, "e": 4858, "s": 4807, "text": "protected boolean isKeyboardNavigationSuppressed()" }, { "code": null, "e": 4949, "s": 4858, "text": "Check if keyboard navigation is being suppressed, such as when the user is editing a cell." }, { "code": null, "e": 4973, "s": 4949, "text": "protected void onBlur()" }, { "code": null, "e": 5008, "s": 4973, "text": "Called when the widget is blurred." }, { "code": null, "e": 5052, "s": 5008, "text": "protected void onBrowserEvent2(Event event)" }, { "code": null, "e": 5114, "s": 5052, "text": "Called after AbstractHasData.onBrowserEvent(Event) completes." }, { "code": null, "e": 5139, "s": 5114, "text": "protected void onFocus()" }, { "code": null, "e": 5174, "s": 5139, "text": "Called when the widget is focused." }, { "code": null, "e": 5195, "s": 5174, "text": "void redrawFooters()" }, { "code": null, "e": 5223, "s": 5195, "text": "Redraw the table's footers." }, { "code": null, "e": 5244, "s": 5223, "text": "void redrawHeaders()" }, { "code": null, "e": 5272, "s": 5244, "text": "Redraw the table's headers." }, { "code": null, "e": 5307, "s": 5272, "text": "void removeColumn(Column<T,?> col)" }, { "code": null, "e": 5324, "s": 5307, "text": "Remove a column." }, { "code": null, "e": 5353, "s": 5324, "text": "void removeColumn(int index)" }, { "code": null, "e": 5370, "s": 5353, "text": "Remove a column." }, { "code": null, "e": 5436, "s": 5370, "text": "void removeColumnStyleName(int index, java.lang.String styleName)" }, { "code": null, "e": 5500, "s": 5436, "text": "Remove a style from the TableColElement at the specified index." }, { "code": null, "e": 5630, "s": 5500, "text": "protected void renderRowValues(SafeHtmlBuilder sb, java.util.List<T> values, int start, SelectionModel<? super T> selectionModel)" }, { "code": null, "e": 5689, "s": 5630, "text": " Render all row values into the specified SafeHtmlBuilder." }, { "code": null, "e": 5764, "s": 5689, "text": "protected void replaceAllChildren(java.util.List<T> values, SafeHtml html)" }, { "code": null, "e": 5810, "s": 5764, "text": "Replace all children with the specified html." }, { "code": null, "e": 5847, "s": 5810, "text": "protected boolean resetFocusOnCell()" }, { "code": null, "e": 5890, "s": 5847, "text": "Reset focus on the currently focused cell." }, { "code": null, "e": 5974, "s": 5890, "text": "protected void setKeyboardSelected(int index, boolean selected, boolean stealFocus)" }, { "code": null, "e": 6032, "s": 5974, "text": "Update an element to reflect its keyboard selected state." }, { "code": null, "e": 6074, "s": 6032, "text": "void setRowStyles(RowStyles<T> rowStyles)" }, { "code": null, "e": 6199, "s": 6074, "text": "Sets the object used to determine how a row is styled; the change will take effect the next time that the table is rendered." }, { "code": null, "e": 6258, "s": 6199, "text": "protected void setSelected(Element elem, boolean selected)" }, { "code": null, "e": 6408, "s": 6258, "text": "Deprecated. this method is never called by AbstractHasData, render the selected styles in renderRowValues(SafeHtmlBuilder, List, int, SelectionModel)" }, { "code": null, "e": 6465, "s": 6408, "text": "This class inherits methods from the following classes −" }, { "code": null, "e": 6504, "s": 6465, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 6543, "s": 6504, "text": "com.google.gwt.user.client.ui.UIObject" }, { "code": null, "e": 6580, "s": 6543, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 6617, "s": 6580, "text": "com.google.gwt.user.client.ui.Widget" }, { "code": null, "e": 6669, "s": 6617, "text": "com.google.gwt.user.cellview.client.AbstractHasData" }, { "code": null, "e": 6721, "s": 6669, "text": "com.google.gwt.user.cellview.client.AbstractHasData" }, { "code": null, "e": 6738, "s": 6721, "text": "java.lang.Object" }, { "code": null, "e": 6755, "s": 6738, "text": "java.lang.Object" }, { "code": null, "e": 6954, "s": 6755, "text": "This example will take you through simple steps to show usage of a CellTable Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter −" }, { "code": null, "e": 7056, "s": 6954, "text": "Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml." }, { "code": null, "e": 7665, "s": 7056, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<module rename-to = 'helloworld'>\n <!-- Inherit the core Web Toolkit stuff. -->\n <inherits name = 'com.google.gwt.user.User'/>\n\n <!-- Inherit the default GWT style sheet. -->\n <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>\n\n <!-- Specify the app entry point class. -->\n <entry-point class = 'com.tutorialspoint.client.HelloWorld'/>\n\n <!-- Specify the paths for translatable code -->\n <source path = 'client'/>\n <source path = 'shared'/>\n\n</module>" }, { "code": null, "e": 7743, "s": 7665, "text": "Following is the content of the modified Style Sheet file war/HelloWorld.css." }, { "code": null, "e": 7929, "s": 7743, "text": "body {\n text-align: center;\n font-family: verdana, sans-serif;\n}\n\nh1 {\n font-size: 2em;\n font-weight: bold;\n color: #777777;\n margin: 40px 0px 70px;\n text-align: center;\n}" }, { "code": null, "e": 8006, "s": 7929, "text": "Following is the content of the modified HTML host file war/HelloWorld.html." }, { "code": null, "e": 8334, "s": 8006, "text": "<html>\n <head>\n <title>Hello World</title>\n <link rel = \"stylesheet\" href = \"HelloWorld.css\"/>\n <script language = \"javascript\" src = \"helloworld/helloworld.nocache.js\">\n </script>\n </head>\n\n <body>\n <h1>CellTable Widget Demonstration</h1>\n <div id = \"gwtContainer\"></div>\n </body>\n</html>" }, { "code": null, "e": 8464, "s": 8334, "text": "Let us have following content of Java file src/com.tutorialspoint/HelloWorld.java which will demonstrate use of CellTable widget." }, { "code": null, "e": 12145, "s": 8464, "text": "package com.tutorialspoint.client;\n\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.gwt.cell.client.DateCell;\nimport com.google.gwt.core.client.EntryPoint;\nimport com.google.gwt.user.cellview.client.CellTable;\nimport com.google.gwt.user.cellview.client.Column;\nimport com.google.gwt.user.cellview.client\n.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;\nimport com.google.gwt.user.cellview.client.TextColumn;\nimport com.google.gwt.user.client.Window;\nimport com.google.gwt.user.client.ui.RootPanel;\nimport com.google.gwt.user.client.ui.VerticalPanel;\nimport com.google.gwt.view.client.SelectionChangeEvent;\nimport com.google.gwt.view.client.SingleSelectionModel;\n\npublic class HelloWorld implements EntryPoint {\n /**\n * A simple data type that represents a contact.\n */\n \n private static class Contact {\n private final String address;\n private final Date birthday;\n private final String name;\n\n public Contact(String name, Date birthday, String address) {\n this.name = name;\n this.birthday = birthday;\n this.address = address;\n }\n }\n\n /**\n * The list of data to display.\n */\n \n private static final List<Contact> CONTACTS = Arrays.asList(\n new Contact(\"John\", new Date(80, 4, 12), \"123 Fourth Avenue\"),\n new Contact(\"Joe\", new Date(85, 2, 22), \"22 Lance Ln\"),\n new Contact(\"George\",new Date(46, 6, 6),\"1600 Pennsylvania Avenue\"));\n\n public void onModuleLoad() {\n // Create a CellTable.\n CellTable<Contact> table = new CellTable<Contact>();\n table.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);\n\n // Add a text column to show the name.\n TextColumn<Contact> nameColumn = \n new TextColumn<Contact>() {\n @Override\n public String getValue(Contact object) {\n return object.name;\n }\n };\n table.addColumn(nameColumn, \"Name\");\n\n // Add a date column to show the birthday.\n DateCell dateCell = new DateCell();\n Column<Contact, Date> dateColumn \n = new Column<Contact, Date>(dateCell) {\n @Override\n public Date getValue(Contact object) {\n return object.birthday;\n }\n };\n table.addColumn(dateColumn, \"Birthday\");\n\n // Add a text column to show the address.\n TextColumn<Contact> addressColumn \n = new TextColumn<Contact>() {\n @Override\n public String getValue(Contact object) {\n return object.address;\n }\n };\n table.addColumn(addressColumn, \"Address\");\n\n // Add a selection model to handle user selection.\n final SingleSelectionModel<Contact> selectionModel \n = new SingleSelectionModel<Contact>();\n table.setSelectionModel(selectionModel);\n selectionModel.addSelectionChangeHandler(\n new SelectionChangeEvent.Handler() {\n public void onSelectionChange(SelectionChangeEvent event) {\n Contact selected = selectionModel.getSelectedObject();\n if (selected != null) {\n Window.alert(\"You selected: \" + selected.name);\n }\n }\n });\n\n // Set the total row count. This isn't strictly necessary,\n // but it affects paging calculations, so its good habit to\n // keep the row count up to date.\n table.setRowCount(CONTACTS.size(), true);\n\n // Push the data into the widget.\n table.setRowData(0, CONTACTS);\n\n VerticalPanel panel = new VerticalPanel();\n panel.setBorderWidth(1);\t \n panel.setWidth(\"400\");\n panel.add(table);\n\n // Add the widgets to the root panel.\n RootPanel.get().add(panel);\n }\n}" }, { "code": null, "e": 12379, "s": 12145, "text": "Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result −" }, { "code": null, "e": 12386, "s": 12379, "text": " Print" }, { "code": null, "e": 12397, "s": 12386, "text": " Add Notes" } ]
How to scroll to an element inside a div using javascript? - GeeksforGeeks
03 Jun, 2020 There are lots of methods to scroll to an element. The following are the methods available in javascript to scroll to an element. The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Syntax: element.scrollIntoView() Example: Using scrollIntoView() to scroll to an element. html <!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick="scrolldiv()">Scroll</button> <div id="condiv"> <div id="ele"> GeeksforGeeks </div> </div> <script> function scrolldiv() { var elem = document.getElementById("ele"); elem.scrollIntoView(); } </script> </body></html> Output : The scroll method: The scroll() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. element.scroll(x-cord,y-cord) Example: Using scroll() to scroll to an element. html <!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick="scrolldiv()">Scroll</button> <div id="condiv"> <div id="ele"> GeeksforGeeks </div> </div> <script> function scrolldiv() { window.scroll(0, findPosition(document.getElementById("ele"))); } function findPosition(obj) { var currenttop = 0; if (obj.offsetParent) { do { currenttop += obj.offsetTop; } while ((obj = obj.offsetParent)); return [currenttop]; } } </script> </body></html> Output : The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. element.scrollTo(x-cord,y-cord) Example: Using scrollTo() to scroll to an element. html <!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick="scrolldiv()">Scroll</button> <div id="condiv"> <div id="ele"> GeeksforGeeks </div> </div> <script> function scrolldiv() { window.scrollTo(0, findPosition(document.getElementById("ele"))); } function findPosition(obj) { var currenttop = 0; if (obj.offsetParent) { do { currenttop += obj.offsetTop; } while ((obj = obj.offsetParent)); return [currenttop]; } } </script> </body></html> Output : JavaScript-Misc Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request Set the value of an input field in JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux 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?
[ { "code": null, "e": 24641, "s": 24613, "text": "\n03 Jun, 2020" }, { "code": null, "e": 24773, "s": 24641, "text": "There are lots of methods to scroll to an element. The following are the methods available in javascript to scroll to an element. " }, { "code": null, "e": 24881, "s": 24773, "text": "The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. " }, { "code": null, "e": 24890, "s": 24881, "text": "Syntax: " }, { "code": null, "e": 24916, "s": 24890, "text": "element.scrollIntoView()\n" }, { "code": null, "e": 24975, "s": 24916, "text": "Example: Using scrollIntoView() to scroll to an element. " }, { "code": null, "e": 24980, "s": 24975, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick=\"scrolldiv()\">Scroll</button> <div id=\"condiv\"> <div id=\"ele\"> GeeksforGeeks </div> </div> <script> function scrolldiv() { var elem = document.getElementById(\"ele\"); elem.scrollIntoView(); } </script> </body></html>", "e": 25834, "s": 24980, "text": null }, { "code": null, "e": 25844, "s": 25834, "text": "Output : " }, { "code": null, "e": 25937, "s": 25844, "text": "The scroll method: The scroll() is used to scroll to the specified element in the browser. " }, { "code": null, "e": 26026, "s": 25937, "text": "Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. " }, { "code": null, "e": 26057, "s": 26026, "text": "element.scroll(x-cord,y-cord)\n" }, { "code": null, "e": 26107, "s": 26057, "text": "Example: Using scroll() to scroll to an element. " }, { "code": null, "e": 26112, "s": 26107, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick=\"scrolldiv()\">Scroll</button> <div id=\"condiv\"> <div id=\"ele\"> GeeksforGeeks </div> </div> <script> function scrolldiv() { window.scroll(0, findPosition(document.getElementById(\"ele\"))); } function findPosition(obj) { var currenttop = 0; if (obj.offsetParent) { do { currenttop += obj.offsetTop; } while ((obj = obj.offsetParent)); return [currenttop]; } } </script> </body></html>", "e": 27273, "s": 26112, "text": null }, { "code": null, "e": 27283, "s": 27273, "text": "Output : " }, { "code": null, "e": 27379, "s": 27283, "text": "The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. " }, { "code": null, "e": 27468, "s": 27379, "text": "Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. " }, { "code": null, "e": 27501, "s": 27468, "text": "element.scrollTo(x-cord,y-cord)\n" }, { "code": null, "e": 27553, "s": 27501, "text": "Example: Using scrollTo() to scroll to an element. " }, { "code": null, "e": 27558, "s": 27553, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> #condiv { height: 500px; width: 500px; overflow: auto; background: #82c93a; } #ele { top: 70%; height: 200px; width: 200px; background-color: green; position: absolute; } </style> </head> <body> <p>Click the button to scroll to the element.</p> <button onclick=\"scrolldiv()\">Scroll</button> <div id=\"condiv\"> <div id=\"ele\"> GeeksforGeeks </div> </div> <script> function scrolldiv() { window.scrollTo(0, findPosition(document.getElementById(\"ele\"))); } function findPosition(obj) { var currenttop = 0; if (obj.offsetParent) { do { currenttop += obj.offsetTop; } while ((obj = obj.offsetParent)); return [currenttop]; } } </script> </body></html>", "e": 28722, "s": 27558, "text": null }, { "code": null, "e": 28732, "s": 28722, "text": "Output : " }, { "code": null, "e": 28748, "s": 28732, "text": "JavaScript-Misc" }, { "code": null, "e": 28755, "s": 28748, "text": "Picked" }, { "code": null, "e": 28766, "s": 28755, "text": "JavaScript" }, { "code": null, "e": 28783, "s": 28766, "text": "Web Technologies" }, { "code": null, "e": 28881, "s": 28783, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28890, "s": 28881, "text": "Comments" }, { "code": null, "e": 28903, "s": 28890, "text": "Old Comments" }, { "code": null, "e": 28964, "s": 28903, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 29009, "s": 28964, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29081, "s": 29009, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 29122, "s": 29081, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29168, "s": 29122, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 29224, "s": 29168, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29257, "s": 29224, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29319, "s": 29257, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29362, "s": 29319, "text": "How to fetch data from an API in ReactJS ?" } ]
Concurrency in Python - Pool of Threads
Suppose we had to create a large number of threads for our multithreaded tasks. It would be computationally most expensive as there can be many performance issues, due to too many threads. A major issue could be in the throughput getting limited. We can solve this problem by creating a pool of threads. A thread pool may be defined as the group of pre-instantiated and idle threads, which stand ready to be given work. Creating thread pool is preferred over instantiating new threads for every task when we need to do large number of tasks. A thread pool can manage concurrent execution of large number of threads as follows − If a thread in a thread pool completes its execution then that thread can be reused. If a thread in a thread pool completes its execution then that thread can be reused. If a thread is terminated, another thread will be created to replace that thread. If a thread is terminated, another thread will be created to replace that thread. Python standard library includes the concurrent.futures module. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes. In our subsequent sections, we will learn about the different classes of the concurrent.futures module. Executoris an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses − ThreadPoolExecutor ProcessPoolExecutor It is one of the concrete subclasses of the Executor class. The subclass uses multi-threading and we get a pool of thread for submitting the tasks. This pool assigns tasks to the available threads and schedules them to run. With the help of concurrent.futures module and its concrete subclass Executor, we can easily create a pool of threads. For this, we need to construct a ThreadPoolExecutor with the number of threads we want in the pool. By default, the number is 5. Then we can submit a task to the thread pool. When we submit() a task, we get back a Future. The Future object has a method called done(), which tells if the future has resolved. With this, a value has been set for that particular future object. When a task finishes, the thread pool executor sets the value to the future object. from concurrent.futures import ThreadPoolExecutor from time import sleep def task(message): sleep(2) return message def main(): executor = ThreadPoolExecutor(5) future = executor.submit(task, ("Completed")) print(future.done()) sleep(2) print(future.done()) print(future.result()) if __name__ == '__main__': main() False True Completed In the above example, a ThreadPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the thread pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it. Another way to instantiate ThreadPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code − with ThreadPoolExecutor(max_workers = 5) as executor The following example is borrowed from the Python docs. In this example, first of all the concurrent.futures module has to be imported. Then a function named load_url() is created which will load the requested url. The function then creates ThreadPoolExecutor with the 5 threads in the pool. The ThreadPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it. import concurrent.futures import urllib.request URLS = ['http://www.foxnews.com/', 'http://www.cnn.com/', 'http://europe.wsj.com/', 'http://www.bbc.co.uk/', 'http://some-made-up-domain.com/'] def load_url(url, timeout): with urllib.request.urlopen(url, timeout = timeout) as conn: return conn.read() with concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor: future_to_url = {executor.submit(load_url, url, 60): url for url in URLS} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: data = future.result() except Exception as exc: print('%r generated an exception: %s' % (url, exc)) else: print('%r page is %d bytes' % (url, len(data))) Following would be the output of the above Python script − 'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed> 'http://www.foxnews.com/' page is 229313 bytes 'http://www.cnn.com/' page is 168933 bytes 'http://www.bbc.co.uk/' page is 283893 bytes 'http://europe.wsj.com/' page is 938109 bytes The Python map() function is widely used in a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to out ThreadPoolExecutor. Consider the following example of Python script to understand how the function works. In this example below, the map function is used to apply the square() function to every value in the values array. from concurrent.futures import ThreadPoolExecutor from concurrent.futures import as_completed values = [2,3,4,5] def square(n): return n * n def main(): with ThreadPoolExecutor(max_workers = 3) as executor: results = executor.map(square, values) for result in results: print(result) if __name__ == '__main__': main() The above Python script generates the following output − 4 9 16 25 57 Lectures 8 hours Denis Tishkov Print Add Notes Bookmark this page
[ { "code": null, "e": 2550, "s": 1922, "text": "Suppose we had to create a large number of threads for our multithreaded tasks. It would be computationally most expensive as there can be many performance issues, due to too many threads. A major issue could be in the throughput getting limited. We can solve this problem by creating a pool of threads. A thread pool may be defined as the group of pre-instantiated and idle threads, which stand ready to be given work. Creating thread pool is preferred over instantiating new threads for every task when we need to do large number of tasks. A thread pool can manage concurrent execution of large number of threads as follows −" }, { "code": null, "e": 2635, "s": 2550, "text": "If a thread in a thread pool completes its execution then that thread can be reused." }, { "code": null, "e": 2720, "s": 2635, "text": "If a thread in a thread pool completes its execution then that thread can be reused." }, { "code": null, "e": 2802, "s": 2720, "text": "If a thread is terminated, another thread will be created to replace that thread." }, { "code": null, "e": 2884, "s": 2802, "text": "If a thread is terminated, another thread will be created to replace that thread." }, { "code": null, "e": 3243, "s": 2884, "text": "Python standard library includes the concurrent.futures module. This module was added in Python 3.2 for providing the developers a high-level interface for launching asynchronous tasks. It is an abstraction layer on the top of Python’s threading and multiprocessing modules for providing the interface for running the tasks using pool of thread or processes." }, { "code": null, "e": 3347, "s": 3243, "text": "In our subsequent sections, we will learn about the different classes of the concurrent.futures module." }, { "code": null, "e": 3506, "s": 3347, "text": "Executoris an abstract class of the concurrent.futures Python module. It cannot be used directly and we need to use one of the following concrete subclasses −" }, { "code": null, "e": 3525, "s": 3506, "text": "ThreadPoolExecutor" }, { "code": null, "e": 3545, "s": 3525, "text": "ProcessPoolExecutor" }, { "code": null, "e": 3769, "s": 3545, "text": "It is one of the concrete subclasses of the Executor class. The subclass uses multi-threading and we get a pool of thread for submitting the tasks. This pool assigns tasks to the available threads and schedules them to run." }, { "code": null, "e": 4347, "s": 3769, "text": "With the help of concurrent.futures module and its concrete subclass Executor, we can easily create a pool of threads. For this, we need to construct a ThreadPoolExecutor with the number of threads we want in the pool. By default, the number is 5. Then we can submit a task to the thread pool. When we submit() a task, we get back a Future. The Future object has a method called done(), which tells if the future has resolved. With this, a value has been set for that particular future object. When a task finishes, the thread pool executor sets the value to the future object." }, { "code": null, "e": 4687, "s": 4347, "text": "from concurrent.futures import ThreadPoolExecutor\nfrom time import sleep\ndef task(message):\n sleep(2)\n return message\n\ndef main():\n executor = ThreadPoolExecutor(5)\n future = executor.submit(task, (\"Completed\"))\n print(future.done())\n sleep(2)\n print(future.done())\n print(future.result())\nif __name__ == '__main__':\nmain()" }, { "code": null, "e": 4709, "s": 4687, "text": "False\nTrue\nCompleted\n" }, { "code": null, "e": 5125, "s": 4709, "text": "In the above example, a ThreadPoolExecutor has been constructed with 5 threads. Then a task, which will wait for 2 seconds before giving the message, is submitted to the thread pool executor. As seen from the output, the task does not complete until 2 seconds, so the first call to done() will return False. After 2 seconds, the task is done and we get the result of the future by calling the result() method on it." }, { "code": null, "e": 5415, "s": 5125, "text": "Another way to instantiate ThreadPoolExecutor is with the help of context manager. It works similar to the method used in the above example. The main advantage of using context manager is that it looks syntactically good. The instantiation can be done with the help of the following code −" }, { "code": null, "e": 5468, "s": 5415, "text": "with ThreadPoolExecutor(max_workers = 5) as executor" }, { "code": null, "e": 5895, "s": 5468, "text": "The following example is borrowed from the Python docs. In this example, first of all the concurrent.futures module has to be imported. Then a function named load_url() is created which will load the requested url. The function then creates ThreadPoolExecutor\nwith the 5 threads in the pool. The ThreadPoolExecutor has been utilized as context manager. We can get the result of the future by calling the result() method on it." }, { "code": null, "e": 6649, "s": 5895, "text": "import concurrent.futures\nimport urllib.request\n\nURLS = ['http://www.foxnews.com/',\n 'http://www.cnn.com/',\n 'http://europe.wsj.com/',\n 'http://www.bbc.co.uk/',\n 'http://some-made-up-domain.com/']\n\ndef load_url(url, timeout):\n with urllib.request.urlopen(url, timeout = timeout) as conn:\n return conn.read()\n\nwith concurrent.futures.ThreadPoolExecutor(max_workers = 5) as executor:\n\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as exc:\n print('%r generated an exception: %s' % (url, exc))\n else:\n print('%r page is %d bytes' % (url, len(data)))" }, { "code": null, "e": 6708, "s": 6649, "text": "Following would be the output of the above Python script −" }, { "code": null, "e": 6997, "s": 6708, "text": "'http://some-made-up-domain.com/' generated an exception: <urlopen error [Errno 11004] getaddrinfo failed>\n'http://www.foxnews.com/' page is 229313 bytes\n'http://www.cnn.com/' page is 168933 bytes\n'http://www.bbc.co.uk/' page is 283893 bytes\n'http://europe.wsj.com/' page is 938109 bytes\n" }, { "code": null, "e": 7358, "s": 6997, "text": "The Python map() function is widely used in a number of tasks. One such task is to apply a certain function to every element within iterables. Similarly, we can map all the elements of an iterator to a function and submit these as independent jobs to out ThreadPoolExecutor. Consider the following example of Python script to understand how the function works." }, { "code": null, "e": 7473, "s": 7358, "text": "In this example below, the map function is used to apply the square() function to every value in the values array." }, { "code": null, "e": 7811, "s": 7473, "text": "from concurrent.futures import ThreadPoolExecutor\nfrom concurrent.futures import as_completed\nvalues = [2,3,4,5]\ndef square(n):\n return n * n\ndef main():\n with ThreadPoolExecutor(max_workers = 3) as executor:\n results = executor.map(square, values)\nfor result in results:\n print(result)\nif __name__ == '__main__':\n main()" }, { "code": null, "e": 7868, "s": 7811, "text": "The above Python script generates the following output −" }, { "code": null, "e": 7879, "s": 7868, "text": "4\n9\n16\n25\n" }, { "code": null, "e": 7912, "s": 7879, "text": "\n 57 Lectures \n 8 hours \n" }, { "code": null, "e": 7927, "s": 7912, "text": " Denis Tishkov" }, { "code": null, "e": 7934, "s": 7927, "text": " Print" }, { "code": null, "e": 7945, "s": 7934, "text": " Add Notes" } ]
vector insert() function in C++ STL - GeeksforGeeks
23 Jan, 2020 std::vector::insert() is a built-in function in C++ STL which inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. Syntax:vector_name.insert (position, val) Parameter:The function accepts two parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}Output:The vector elements are: 2 3 7 10 20 30 40 Example 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << "The vector elements are: "; for (auto it : vec) cout << it << " "; return 0;}Output:The vector elements are: 10 20 30 40 50 60 70 80 Syntax:vector_name.insert(position, size, val) Parameter:The function accepts three parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.size – It specifies the number of times a val is to be inserted at the specified position.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Below program illustrates the above mentioned function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}Output:The vector elements are: 4 4 3 10 20 30 40 Syntax:vector_name.insert(position, iterator1, iterator2) Parameter:The function accepts three parameters specified as below:position – It specifies the position at which insertion is to be done in vector.iterator1 – It specifies the starting position from which the elements are to be insertediterator2 – It specifies the ending position till which elements are to be insertedReturn value: The function returns an iterator which points to the newly inserted element.Below is the illustration of above function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << "The vector2 elements are: "; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << " "; return 0;}Output:The vector2 elements are: 10 20 30 40 Syntax:vector_name.insert (position, val) Parameter:The function accepts two parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}Output:The vector elements are: 2 3 7 10 20 30 40 Example 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << "The vector elements are: "; for (auto it : vec) cout << it << " "; return 0;}Output:The vector elements are: 10 20 30 40 50 60 70 80 vector_name.insert (position, val) Parameter:The function accepts two parameters specified as below: position – It specifies the iterator which points to the position where the insertion is to be done. val – It specifies the value to be inserted. Return value: The function returns an iterator which points to the newly inserted element. Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front. // Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;} The vector elements are: 2 3 7 10 20 30 40 Example 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position. // Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << "The vector elements are: "; for (auto it : vec) cout << it << " "; return 0;} The vector elements are: 10 20 30 40 50 60 70 80 Syntax:vector_name.insert(position, size, val) Parameter:The function accepts three parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.size – It specifies the number of times a val is to be inserted at the specified position.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Below program illustrates the above mentioned function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;}Output:The vector elements are: 4 4 3 10 20 30 40 vector_name.insert(position, size, val) Parameter:The function accepts three parameters specified as below: position – It specifies the iterator which points to the position where the insertion is to be done. size – It specifies the number of times a val is to be inserted at the specified position. val – It specifies the value to be inserted. Return value: The function returns an iterator which points to the newly inserted element. Below program illustrates the above mentioned function: // program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << "The vector elements are: "; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " "; return 0;} The vector elements are: 4 4 3 10 20 30 40 Syntax:vector_name.insert(position, iterator1, iterator2) Parameter:The function accepts three parameters specified as below:position – It specifies the position at which insertion is to be done in vector.iterator1 – It specifies the starting position from which the elements are to be insertediterator2 – It specifies the ending position till which elements are to be insertedReturn value: The function returns an iterator which points to the newly inserted element.Below is the illustration of above function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << "The vector2 elements are: "; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << " "; return 0;}Output:The vector2 elements are: 10 20 30 40 vector_name.insert(position, iterator1, iterator2) Parameter:The function accepts three parameters specified as below: position – It specifies the position at which insertion is to be done in vector. iterator1 – It specifies the starting position from which the elements are to be inserted iterator2 – It specifies the ending position till which elements are to be inserted Return value: The function returns an iterator which points to the newly inserted element. Below is the illustration of above function: // program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << "The vector2 elements are: "; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << " "; return 0;} The vector2 elements are: 10 20 30 40 grim_firefly CPP-Functions cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in C++ C++ Classes and Objects Socket Programming in C/C++ Operator Overloading in C++ Copy Constructor in C++ Virtual Function in C++ Templates in C++ with Examples rand() and srand() in C/C++ vector erase() and clear() in C++ unordered_map in C++ STL
[ { "code": null, "e": 24020, "s": 23992, "text": "\n23 Jan, 2020" }, { "code": null, "e": 24227, "s": 24020, "text": "std::vector::insert() is a built-in function in C++ STL which inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted." }, { "code": null, "e": 27885, "s": 24227, "text": "Syntax:vector_name.insert (position, val)\nParameter:The function accepts two parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector elements are: 2 3 7 10 20 30 40\nExample 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << \"The vector elements are: \"; for (auto it : vec) cout << it << \" \"; return 0;}Output:The vector elements are: 10 20 30 40 50 60 70 80\nSyntax:vector_name.insert(position, size, val)\nParameter:The function accepts three parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.size – It specifies the number of times a val is to be inserted at the specified position.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Below program illustrates the above mentioned function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector elements are: 4 4 3 10 20 30 40\nSyntax:vector_name.insert(position, iterator1, iterator2)\nParameter:The function accepts three parameters specified as below:position – It specifies the position at which insertion is to be done in vector.iterator1 – It specifies the starting position from which the elements are to be insertediterator2 – It specifies the ending position till which elements are to be insertedReturn value: The function returns an iterator which points to the newly inserted element.Below is the illustration of above function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << \"The vector2 elements are: \"; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector2 elements are: 10 20 30 40\n" }, { "code": null, "e": 29522, "s": 27885, "text": "Syntax:vector_name.insert (position, val)\nParameter:The function accepts two parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector elements are: 2 3 7 10 20 30 40\nExample 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position.// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << \"The vector elements are: \"; for (auto it : vec) cout << it << \" \"; return 0;}Output:The vector elements are: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 29558, "s": 29522, "text": "vector_name.insert (position, val)\n" }, { "code": null, "e": 29624, "s": 29558, "text": "Parameter:The function accepts two parameters specified as below:" }, { "code": null, "e": 29725, "s": 29624, "text": "position – It specifies the iterator which points to the position where the insertion is to be done." }, { "code": null, "e": 29770, "s": 29725, "text": "val – It specifies the value to be inserted." }, { "code": null, "e": 29861, "s": 29770, "text": "Return value: The function returns an iterator which points to the newly inserted element." }, { "code": null, "e": 29973, "s": 29861, "text": "Example 1: Below program illustrates the above mentioned function where new elements are inserted at the front." }, { "code": "// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 at front auto it = vec.insert(vec.begin(), 3); // inserts 2 at front vec.insert(it, 2); int i = 2; // inserts 7 at i-th index it = vec.insert(vec.begin() + i, 7); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}", "e": 30504, "s": 29973, "text": null }, { "code": null, "e": 30548, "s": 30504, "text": "The vector elements are: 2 3 7 10 20 30 40\n" }, { "code": null, "e": 30670, "s": 30548, "text": "Example 2: Below program illustrates the above mentioned function where new elements are inserted at a specific position." }, { "code": "// Program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 70, 80 }; int x = 50; // inserting multiple elements // at specific positions vec.insert(vec.begin() + 2, { 30, 40, x, 60 }); cout << \"The vector elements are: \"; for (auto it : vec) cout << it << \" \"; return 0;}", "e": 31098, "s": 30670, "text": null }, { "code": null, "e": 31148, "s": 31098, "text": "The vector elements are: 10 20 30 40 50 60 70 80\n" }, { "code": null, "e": 32163, "s": 31148, "text": "Syntax:vector_name.insert(position, size, val)\nParameter:The function accepts three parameters specified as below:position – It specifies the iterator which points to the position where the insertion is to be done.size – It specifies the number of times a val is to be inserted at the specified position.val – It specifies the value to be inserted.Return value: The function returns an iterator which points to the newly inserted element.Below program illustrates the above mentioned function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector elements are: 4 4 3 10 20 30 40\n" }, { "code": null, "e": 32204, "s": 32163, "text": "vector_name.insert(position, size, val)\n" }, { "code": null, "e": 32272, "s": 32204, "text": "Parameter:The function accepts three parameters specified as below:" }, { "code": null, "e": 32373, "s": 32272, "text": "position – It specifies the iterator which points to the position where the insertion is to be done." }, { "code": null, "e": 32464, "s": 32373, "text": "size – It specifies the number of times a val is to be inserted at the specified position." }, { "code": null, "e": 32509, "s": 32464, "text": "val – It specifies the value to be inserted." }, { "code": null, "e": 32600, "s": 32509, "text": "Return value: The function returns an iterator which points to the newly inserted element." }, { "code": null, "e": 32656, "s": 32600, "text": "Below program illustrates the above mentioned function:" }, { "code": "// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec = { 10, 20, 30, 40 }; // inserts 3 one time at front auto it = vec.insert(vec.begin(), 1, 3); // inserts 4 two times at front vec.insert(it, 2, 4); cout << \"The vector elements are: \"; for (auto it = vec.begin(); it != vec.end(); ++it) cout << *it << \" \"; return 0;}", "e": 33128, "s": 32656, "text": null }, { "code": null, "e": 33172, "s": 33128, "text": "The vector elements are: 4 4 3 10 20 30 40\n" }, { "code": null, "e": 34180, "s": 33172, "text": "Syntax:vector_name.insert(position, iterator1, iterator2)\nParameter:The function accepts three parameters specified as below:position – It specifies the position at which insertion is to be done in vector.iterator1 – It specifies the starting position from which the elements are to be insertediterator2 – It specifies the ending position till which elements are to be insertedReturn value: The function returns an iterator which points to the newly inserted element.Below is the illustration of above function:// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << \"The vector2 elements are: \"; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << \" \"; return 0;}Output:The vector2 elements are: 10 20 30 40\n" }, { "code": null, "e": 34232, "s": 34180, "text": "vector_name.insert(position, iterator1, iterator2)\n" }, { "code": null, "e": 34300, "s": 34232, "text": "Parameter:The function accepts three parameters specified as below:" }, { "code": null, "e": 34381, "s": 34300, "text": "position – It specifies the position at which insertion is to be done in vector." }, { "code": null, "e": 34471, "s": 34381, "text": "iterator1 – It specifies the starting position from which the elements are to be inserted" }, { "code": null, "e": 34555, "s": 34471, "text": "iterator2 – It specifies the ending position till which elements are to be inserted" }, { "code": null, "e": 34646, "s": 34555, "text": "Return value: The function returns an iterator which points to the newly inserted element." }, { "code": null, "e": 34691, "s": 34646, "text": "Below is the illustration of above function:" }, { "code": "// program below illustrates the// vector::insert() function #include <bits/stdc++.h>using namespace std; int main(){ // initialising the vector vector<int> vec1 = { 10, 20, 30, 40 }; vector<int> vec2; // inserts at the beginning of vec2 vec2.insert(vec2.begin(), vec1.begin(), vec1.end()); cout << \"The vector2 elements are: \"; for (auto it = vec2.begin(); it != vec2.end(); ++it) cout << *it << \" \"; return 0;}", "e": 35143, "s": 34691, "text": null }, { "code": null, "e": 35182, "s": 35143, "text": "The vector2 elements are: 10 20 30 40\n" }, { "code": null, "e": 35195, "s": 35182, "text": "grim_firefly" }, { "code": null, "e": 35209, "s": 35195, "text": "CPP-Functions" }, { "code": null, "e": 35220, "s": 35209, "text": "cpp-vector" }, { "code": null, "e": 35224, "s": 35220, "text": "STL" }, { "code": null, "e": 35228, "s": 35224, "text": "C++" }, { "code": null, "e": 35232, "s": 35228, "text": "STL" }, { "code": null, "e": 35236, "s": 35232, "text": "CPP" }, { "code": null, "e": 35334, "s": 35236, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35343, "s": 35334, "text": "Comments" }, { "code": null, "e": 35356, "s": 35343, "text": "Old Comments" }, { "code": null, "e": 35376, "s": 35356, "text": "Constructors in C++" }, { "code": null, "e": 35400, "s": 35376, "text": "C++ Classes and Objects" }, { "code": null, "e": 35428, "s": 35400, "text": "Socket Programming in C/C++" }, { "code": null, "e": 35456, "s": 35428, "text": "Operator Overloading in C++" }, { "code": null, "e": 35480, "s": 35456, "text": "Copy Constructor in C++" }, { "code": null, "e": 35504, "s": 35480, "text": "Virtual Function in C++" }, { "code": null, "e": 35535, "s": 35504, "text": "Templates in C++ with Examples" }, { "code": null, "e": 35563, "s": 35535, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 35597, "s": 35563, "text": "vector erase() and clear() in C++" } ]
C# Program to Subtract Two TimeSpan
Firstly, set two TimeSpans − TimeSpan t1 = TimeSpan.FromMinutes(2); TimeSpan t2 = TimeSpan.FromMinutes(1); To add it, use the Subtract() method − imeSpan res = t1.Subtract(t2); Here is the complete code − Live Demo using System; using System.Linq; public class Demo { public static void Main() { TimeSpan t1 = TimeSpan.FromMinutes(2); TimeSpan t2 = TimeSpan.FromMinutes(1); Console.WriteLine("First TimeSpan: "+t1); Console.WriteLine("Second TimeSpan: "+t2); // Subtracting TimeSpan res = t1.Subtract(t2); Console.WriteLine("Resultant TimeSpan: "+res); } } First TimeSpan: 00:02:00 Second TimeSpan: 00:01:00 Resultant TimeSpan: 00:01:00
[ { "code": null, "e": 1091, "s": 1062, "text": "Firstly, set two TimeSpans −" }, { "code": null, "e": 1169, "s": 1091, "text": "TimeSpan t1 = TimeSpan.FromMinutes(2);\nTimeSpan t2 = TimeSpan.FromMinutes(1);" }, { "code": null, "e": 1208, "s": 1169, "text": "To add it, use the Subtract() method −" }, { "code": null, "e": 1239, "s": 1208, "text": "imeSpan res = t1.Subtract(t2);" }, { "code": null, "e": 1267, "s": 1239, "text": "Here is the complete code −" }, { "code": null, "e": 1278, "s": 1267, "text": " Live Demo" }, { "code": null, "e": 1668, "s": 1278, "text": "using System;\nusing System.Linq;\npublic class Demo {\n public static void Main() {\n TimeSpan t1 = TimeSpan.FromMinutes(2);\n TimeSpan t2 = TimeSpan.FromMinutes(1);\n Console.WriteLine(\"First TimeSpan: \"+t1);\n Console.WriteLine(\"Second TimeSpan: \"+t2);\n // Subtracting\n TimeSpan res = t1.Subtract(t2);\n Console.WriteLine(\"Resultant TimeSpan: \"+res);\n }\n}" }, { "code": null, "e": 1748, "s": 1668, "text": "First TimeSpan: 00:02:00\nSecond TimeSpan: 00:01:00\nResultant TimeSpan: 00:01:00" } ]
Regression Plots in Python with Seaborn | by Alan Jones | Towards Data Science
A Scatter plot is a great way of exploring relationships or patterns in data. But adding a regression line can make those patterns stand out and it is one thing that is not built into the Pandas plot API. You can use a stats library like Statsmodels, or even Numpy, to create a regression model from your data and include this in your plot. But, if all you need is a visual guide to relationships in your data, Seaborn can do this for you, easily. Seaborn is a statistical plotting library that can read Pandas dataframes (as well as other data structures) and provides simple methods for adding regression lines to your scatter diagrams. We are going to take a look at how the regplot function in Seaborn can be used to do this and we’ll look at linear regression that helps us see simple relations in the data and also higher order regressions that show a more complex picture. To introduce the regplot function, we’ll first manufacture some data to produce some idealised plots and then later use world population data to illustrate its use in a real-world situation. Below are examples of a scatter plot and the same plot with a linear regression line added. The regression line is an attempt to find the best fit through the points in the scatter plot. The shaded area around the line is the confidence interval. You were probably able to discern a linear relationship from the first plot but adding a regression line on top of the scatter diagram makes it much clearer. Let’s get right into the code and see how Seaborn helps us. First import the Seaborn library. import seaborn as sns Now we will create a couple of Numpy arrays that will represent the x and y data that we will plot. In the code below we import the Numpy library and then create an array of integers from -5 to 5 — that’s the array representing the x data. To create the y array we use a formula that creates a linear relationship between x and y: y = x*2 + 3 When we plot this we would expect to see a straight line graph with the intercept at 3 and a two-to-one relationship between x and y. The last line of the code below creates a scatter plot and we can see that it is the form of a straight line. import numpy as npx=np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5])y=x*2+3sns.scatterplot(x=x,y=y) So when we create a regplot, a plot that includes a regression line we would expect that line to coincide the scatter points. sns.regplot(x=x,y=y) And, of course, it does. But regression does not have to be linear. In the next block of code we define a quadratic relationship between x and y. We then plot that but instead of the default linear option we set a second order regression, order=2. This instructs regplot to find a quadratic relationship. y2=x**2+2*x+3sns.regplot(x=x,y=y2,order=2) Again, the regression line exactly matches the scatter diagram points as expected. We could go on but we will stop at the third order regression which is illustrated below. y3=x**3+x**2+2*x+3sns.regplot(x=x,y=y3,order=3) Those examples were not realistic, of course. We were giving regplot exact representations of first, second and third order plots and, unsurprisingly, the regression line fitted the scatter plot points exactly. Real data is generally more noisy: there are random variations, errors in measurement. Or, maybe the data simply doesn’t conform to our ideal linear, quadratic or third order formulae. So, now we are going to see the same type of plots but with some real data. We are going to load some world population data, pick a country and try to see if a regression plot can give us any insights. Here, we set the url of the data to download to a Github repository — the data is oiginally from Gapminder (you can see the full acknowledgement below*). We then load the data into a Pandas dataframe. Just a couple of things to note here: the file is a tsv file, that’s like a csv but with tabs for separators instead of commas, so we need to specify that when converting to a dataframe; and also I convert the year field to an integer to make it easier to make comparisons (it otherwise loads as a float). The population totals are real numbers and are, of course, in the millions. To make these look a bit nicer on the graphs, I divide them all by 1 million. popDataURL = "https://raw.githubusercontent.com/jennybc/gapminder/master/inst/extdata/gapminder.tsv"import pandas as pdpopData = pd.read_csv(popDataURL, delimiter='\t', dtype=({'year':int}))popData['pop']=popData['pop']/1000000popData I am only going to look at one country, initially, so I created a new dataframe called SpainData. Then I plot the population in Spain over the last several decades on a regplot, looking for the default linear relationship between time and population. SpainData = popData[popData['country']=='Spain' sns.regplot(x="year", y="pop", data=SpainData) Looking at this, it seems that there is a steady growth in population, but examining the scatter points it looks like there is a steeper curve in the earlier decades and a shallower one more recently. Perhaps a straight line is not the best fit. Let’s try higher order regressions. sns.regplot(x="year", y="pop", data=SpainData, order=2, ci=None) sns.regplot(x="year", y="pop", data=SpainData, order=3, ci=None) By just looking at the plots above, it looks like the second order graph is closer to the real data than the others. This is not to say that the population of Spain can be interpreted by strictly quadratic model — it’s likely to be more complex that that — but that curve gives us a better understanding of what is happening; that the population growth is not increasing at a steady rate but, rather, it is slowing. It would probably be a mistake to try and use such a simple mathematical model to predict the likely increase in population of any country because there are so many factors that have to be taken into account. But Seaborn’s visual only approach can give us a better understanding of trends than a scatter chart with no regression line. What if we want to compare different countries? Seaborn gives us a neat way of doing this using the hue parameter. Let’s create a new dataframe with five significant European countries, France, Germany, Spain, Italy and The Netherlands and see how the growth of their populations compare. The resulting plot is done with lmplot. This is similar to regplot but allows us to plot the different countries in different colors by setting hue='country'. topeucountries = ['France','Germany','Spain','Italy','Netherlands']europeData = popData[popData['country'].isin(topeucountries)]sns.lmplot(x="year", y="pop", data=europeData, hue='country', order=2, ci=False) In the resulting graph, you can see that, while still on an apparently upward trajectory, population growth appears to be slowing. This seems particularly clear in the case of Italy. Let’s look at another example. It’s indisputable that, on average, the more money you have the longer you can expect to live. Wealth and life expectancy are linked due to access to better healthcare facilities, better diets and so on. So, the more you earn the longer you live but only up to a point. Life expectancy can’t continue to increase with wealth; there must be a limit. Here’s a couple of graphs that demonstrate the link. Here, we represent wealth by GDP per capita (that’s the total GDP of a nation divided by the number of people who live there — which can be thought of as the average wealth within a particular nation). The first linear graph appears to be a reasonably good fit but it cannot be that the line in this diagram will extend to 100, 150 or 200 years as income increases. There must be a limit; increases in income must surely follow a law of diminishing returns. The order=2 version confirms this and gives a better picture of reality where the increase in life expectancy tails off as GdpPercap increases. sns.lmplot(x="gdpPercap", y="lifeExp",data=europeData, ci=False, order=1)sns.lmplot(x="gdpPercap", y="lifeExp",data=europeData, ci=False, order=2) Hopefully you can see from the examples above that regression plots can make interpreting data a little easier and that Seaborn gives you the tools to do this easily. As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here. If you are not a Medium subscriber, how about signing up so you can read as many articles as you like for $5 a month. Sign up here and I’ll earn a small commision.
[ { "code": null, "e": 376, "s": 171, "text": "A Scatter plot is a great way of exploring relationships or patterns in data. But adding a regression line can make those patterns stand out and it is one thing that is not built into the Pandas plot API." }, { "code": null, "e": 619, "s": 376, "text": "You can use a stats library like Statsmodels, or even Numpy, to create a regression model from your data and include this in your plot. But, if all you need is a visual guide to relationships in your data, Seaborn can do this for you, easily." }, { "code": null, "e": 810, "s": 619, "text": "Seaborn is a statistical plotting library that can read Pandas dataframes (as well as other data structures) and provides simple methods for adding regression lines to your scatter diagrams." }, { "code": null, "e": 1051, "s": 810, "text": "We are going to take a look at how the regplot function in Seaborn can be used to do this and we’ll look at linear regression that helps us see simple relations in the data and also higher order regressions that show a more complex picture." }, { "code": null, "e": 1242, "s": 1051, "text": "To introduce the regplot function, we’ll first manufacture some data to produce some idealised plots and then later use world population data to illustrate its use in a real-world situation." }, { "code": null, "e": 1489, "s": 1242, "text": "Below are examples of a scatter plot and the same plot with a linear regression line added. The regression line is an attempt to find the best fit through the points in the scatter plot. The shaded area around the line is the confidence interval." }, { "code": null, "e": 1647, "s": 1489, "text": "You were probably able to discern a linear relationship from the first plot but adding a regression line on top of the scatter diagram makes it much clearer." }, { "code": null, "e": 1741, "s": 1647, "text": "Let’s get right into the code and see how Seaborn helps us. First import the Seaborn library." }, { "code": null, "e": 1763, "s": 1741, "text": "import seaborn as sns" }, { "code": null, "e": 2094, "s": 1763, "text": "Now we will create a couple of Numpy arrays that will represent the x and y data that we will plot. In the code below we import the Numpy library and then create an array of integers from -5 to 5 — that’s the array representing the x data. To create the y array we use a formula that creates a linear relationship between x and y:" }, { "code": null, "e": 2106, "s": 2094, "text": "y = x*2 + 3" }, { "code": null, "e": 2350, "s": 2106, "text": "When we plot this we would expect to see a straight line graph with the intercept at 3 and a two-to-one relationship between x and y. The last line of the code below creates a scatter plot and we can see that it is the form of a straight line." }, { "code": null, "e": 2440, "s": 2350, "text": "import numpy as npx=np.array([-5,-4,-3,-2,-1,0,1,2,3,4,5])y=x*2+3sns.scatterplot(x=x,y=y)" }, { "code": null, "e": 2566, "s": 2440, "text": "So when we create a regplot, a plot that includes a regression line we would expect that line to coincide the scatter points." }, { "code": null, "e": 2587, "s": 2566, "text": "sns.regplot(x=x,y=y)" }, { "code": null, "e": 2612, "s": 2587, "text": "And, of course, it does." }, { "code": null, "e": 2892, "s": 2612, "text": "But regression does not have to be linear. In the next block of code we define a quadratic relationship between x and y. We then plot that but instead of the default linear option we set a second order regression, order=2. This instructs regplot to find a quadratic relationship." }, { "code": null, "e": 2935, "s": 2892, "text": "y2=x**2+2*x+3sns.regplot(x=x,y=y2,order=2)" }, { "code": null, "e": 3018, "s": 2935, "text": "Again, the regression line exactly matches the scatter diagram points as expected." }, { "code": null, "e": 3108, "s": 3018, "text": "We could go on but we will stop at the third order regression which is illustrated below." }, { "code": null, "e": 3156, "s": 3108, "text": "y3=x**3+x**2+2*x+3sns.regplot(x=x,y=y3,order=3)" }, { "code": null, "e": 3552, "s": 3156, "text": "Those examples were not realistic, of course. We were giving regplot exact representations of first, second and third order plots and, unsurprisingly, the regression line fitted the scatter plot points exactly. Real data is generally more noisy: there are random variations, errors in measurement. Or, maybe the data simply doesn’t conform to our ideal linear, quadratic or third order formulae." }, { "code": null, "e": 3628, "s": 3552, "text": "So, now we are going to see the same type of plots but with some real data." }, { "code": null, "e": 3754, "s": 3628, "text": "We are going to load some world population data, pick a country and try to see if a regression plot can give us any insights." }, { "code": null, "e": 3908, "s": 3754, "text": "Here, we set the url of the data to download to a Github repository — the data is oiginally from Gapminder (you can see the full acknowledgement below*)." }, { "code": null, "e": 3955, "s": 3908, "text": "We then load the data into a Pandas dataframe." }, { "code": null, "e": 4261, "s": 3955, "text": "Just a couple of things to note here: the file is a tsv file, that’s like a csv but with tabs for separators instead of commas, so we need to specify that when converting to a dataframe; and also I convert the year field to an integer to make it easier to make comparisons (it otherwise loads as a float)." }, { "code": null, "e": 4415, "s": 4261, "text": "The population totals are real numbers and are, of course, in the millions. To make these look a bit nicer on the graphs, I divide them all by 1 million." }, { "code": null, "e": 4653, "s": 4415, "text": "popDataURL = \"https://raw.githubusercontent.com/jennybc/gapminder/master/inst/extdata/gapminder.tsv\"import pandas as pdpopData = pd.read_csv(popDataURL, delimiter='\\t', dtype=({'year':int}))popData['pop']=popData['pop']/1000000popData" }, { "code": null, "e": 4904, "s": 4653, "text": "I am only going to look at one country, initially, so I created a new dataframe called SpainData. Then I plot the population in Spain over the last several decades on a regplot, looking for the default linear relationship between time and population." }, { "code": null, "e": 4999, "s": 4904, "text": "SpainData = popData[popData['country']=='Spain' sns.regplot(x=\"year\", y=\"pop\", data=SpainData)" }, { "code": null, "e": 5281, "s": 4999, "text": "Looking at this, it seems that there is a steady growth in population, but examining the scatter points it looks like there is a steeper curve in the earlier decades and a shallower one more recently. Perhaps a straight line is not the best fit. Let’s try higher order regressions." }, { "code": null, "e": 5346, "s": 5281, "text": "sns.regplot(x=\"year\", y=\"pop\", data=SpainData, order=2, ci=None)" }, { "code": null, "e": 5411, "s": 5346, "text": "sns.regplot(x=\"year\", y=\"pop\", data=SpainData, order=3, ci=None)" }, { "code": null, "e": 5827, "s": 5411, "text": "By just looking at the plots above, it looks like the second order graph is closer to the real data than the others. This is not to say that the population of Spain can be interpreted by strictly quadratic model — it’s likely to be more complex that that — but that curve gives us a better understanding of what is happening; that the population growth is not increasing at a steady rate but, rather, it is slowing." }, { "code": null, "e": 6162, "s": 5827, "text": "It would probably be a mistake to try and use such a simple mathematical model to predict the likely increase in population of any country because there are so many factors that have to be taken into account. But Seaborn’s visual only approach can give us a better understanding of trends than a scatter chart with no regression line." }, { "code": null, "e": 6277, "s": 6162, "text": "What if we want to compare different countries? Seaborn gives us a neat way of doing this using the hue parameter." }, { "code": null, "e": 6451, "s": 6277, "text": "Let’s create a new dataframe with five significant European countries, France, Germany, Spain, Italy and The Netherlands and see how the growth of their populations compare." }, { "code": null, "e": 6610, "s": 6451, "text": "The resulting plot is done with lmplot. This is similar to regplot but allows us to plot the different countries in different colors by setting hue='country'." }, { "code": null, "e": 6821, "s": 6610, "text": "topeucountries = ['France','Germany','Spain','Italy','Netherlands']europeData = popData[popData['country'].isin(topeucountries)]sns.lmplot(x=\"year\", y=\"pop\", data=europeData, hue='country', order=2, ci=False)" }, { "code": null, "e": 7004, "s": 6821, "text": "In the resulting graph, you can see that, while still on an apparently upward trajectory, population growth appears to be slowing. This seems particularly clear in the case of Italy." }, { "code": null, "e": 7035, "s": 7004, "text": "Let’s look at another example." }, { "code": null, "e": 7239, "s": 7035, "text": "It’s indisputable that, on average, the more money you have the longer you can expect to live. Wealth and life expectancy are linked due to access to better healthcare facilities, better diets and so on." }, { "code": null, "e": 7384, "s": 7239, "text": "So, the more you earn the longer you live but only up to a point. Life expectancy can’t continue to increase with wealth; there must be a limit." }, { "code": null, "e": 7639, "s": 7384, "text": "Here’s a couple of graphs that demonstrate the link. Here, we represent wealth by GDP per capita (that’s the total GDP of a nation divided by the number of people who live there — which can be thought of as the average wealth within a particular nation)." }, { "code": null, "e": 7895, "s": 7639, "text": "The first linear graph appears to be a reasonably good fit but it cannot be that the line in this diagram will extend to 100, 150 or 200 years as income increases. There must be a limit; increases in income must surely follow a law of diminishing returns." }, { "code": null, "e": 8039, "s": 7895, "text": "The order=2 version confirms this and gives a better picture of reality where the increase in life expectancy tails off as GdpPercap increases." }, { "code": null, "e": 8192, "s": 8039, "text": "sns.lmplot(x=\"gdpPercap\", y=\"lifeExp\",data=europeData, ci=False, order=1)sns.lmplot(x=\"gdpPercap\", y=\"lifeExp\",data=europeData, ci=False, order=2)" }, { "code": null, "e": 8359, "s": 8192, "text": "Hopefully you can see from the examples above that regression plots can make interpreting data a little easier and that Seaborn gives you the tools to do this easily." }, { "code": null, "e": 8497, "s": 8359, "text": "As always, thanks for reading. If you would like to know when I publish new articles, please consider signing up for an email alert here." } ]
New York Taxi data set analysis. Recently I had the opportunity to play... | by Marie Stephen Leo | Towards Data Science
Recently I had the opportunity to play with the New York taxi public data set hosted by Google cloud’s Big Query platform. I decided to apply machine learning techniques on the data set to try and build some predictive models using Python. For this post, I’ll attempt to predict the taxi fare amount. Let’s jump right into it! All the code for this article can be found on Github at Link First, on inspecting the Google Big Query tables, we notice that there is one table per year. This gives me an idea. I could use the data from 2015 to train my machine learning models and then use the data from 2016 to test the model’s predictive power. Next, let’s query random 100K rows from 2015 and a random 100K rows from 2016 data using Google’s data lab platform. Now, let’s begin the process of predicting taxi fare. First, let’s import the necessary packages and load the data into a pandas data frame. I use the %matplotlib inline as I am using a jupyter notebook for the analysis. From the data frame, we see that each row is one trip while each column is an attribute related to the trip. I like to start my projects by first building a predictive model purely from intuition. This simple intuitive model will give us our baseline accuracy and we shall try to beat this baseline accuracy using more advanced techniques. For any predictive model, we need to consider what is the response variable we are trying to predict and what are the feature variables that could have an impact on the said response. In this exercise, the response we want to predict is the fare_amount. Purely from an intuition perspective, we know that taxis generally charge on a fixed initial fee + a per km basis (total distance) + a per minute basis (total duration). Looking back at our data frame columns, we already have a trip_distance column, but we lack a trip_duration column. However, we are provided with pickup and dropoff datetimes, so we can easily calculate the trip_duration using these columns as below. Now, let us visualize the columns of interest for our simple intuitive model (fare_amount, trip_distance, and trip_duration). As can be seen from the chart, there are significant outliers for all three columns. Let’s perform an outlier removal and plot again. Much better! Also, we can clearly see that there is a strong correlation between fare_amount to both the trip_distance and the trip_duration and so we are on the right track. Before we proceed further, let’s create some helper functions. The first function is to split the data so that the training dataset only has data from 2015 and the test dataset only has data from 2016 as mentioned before. The second function is to calculate some statistics that can be used to evaluate the predictive power of our models. For this exercise, the statistics I choose are Root Mean Square Error (RMSE) which gives the standard deviation of the difference between actual fare_amount and predicted fare_amount in $ and can be calculated as the square root of sklearn’s mean_squared_error(). The R-square gives how much percentage of the actual fare_amount’s variation is predicted by the model and can be directly obtained from sklearn’s r2_score(). Great! Now we are all set to build our first model purely from intuition. Let’s first split the data into the response (y) and features (X), then create the training and testing sets using the above helper function, then fit a simple Linear Regression model on the training dataset and finally, check the model results using the above helper function. ----Training Data results (2015 data set)----RMSE: $5.6R2: 0.79----Test Data results (2016 data set)----RMSE: $5.5R2: 0.81 Not bad for our very first attempt! The testing dataset has an RMSE of $5.5 and we shall use this as our baseline score. Now, let us try to improve this score. The method I shall employ here is to add more features to the model by the process of feature engineering. Thinking deeper about the problem. Pickup day of the week and hour of the day could play an important role in demand and traffic conditions leading to an impact on fare Latitude difference and Longitude difference could be additional data to augment trip_distance’s impact on fare Pickup and dropoff neighborhoods could have an effect on fare due to additional fees for specific locations? So, let’s add a few extra features as below. Geohashing is a method to create discrete geographic locations based on absolute latitude and longitudes. You can think of it as creating a common name for locations belonging to the same neighborhood. I use the pygeohash python package which can be installed using pip install pygeohash. Since there is a lot of missing data in the latitude and longitude columns, let’s remove them as well. The new features added are: Pickup monthPickup day of the weekPickup hour of the dayLattitude differenceLongitude differenceGeohashed pickup locationGeohashed dropoff location Pickup month Pickup day of the week Pickup hour of the day Lattitude difference Longitude difference Geohashed pickup location Geohashed dropoff location Looks like there are some outliers in lat_dif and lon_dif, so let’s remove them. Also, since the columns like month, day_of_week, hour_of_day, pickup_geohash, and dropoff_geohash are categorical, let’s encode them using the pandas get_dummies method. Now let’s split the training and testing datasets and fit a simple Linear Regression model ----Training Data results (2015 data set)----RMSE: $3.5R2: 0.92----Test Data results (2016 data set)----RMSE: $7139352.0R2: -338832003532.88 Yikes! the model has better RMSE on the training dataset but much worse RMSE on the test dataset indicating that the model is overfitting. This necessitates the use of a regularization technique. We can use sklearn’s Lasso Regression for regularization. ----Training Data results (2015 data set)----RMSE: $5.6R2: 0.79----Test Data results (2016 data set)----RMSE: $5.3R2: 0.82 Ok, that’s better from an over-fitting perspective but the Model RMSE did not improve much. Let us now try hyper-parameter tuning to improve the model RMSE. The parameter we can tune for Lasso Regression is called alpha which is a constant that multiplies the L1 penalty term. The default value of alpha is 1. Smaller alpha will make Lasso regression similar to Linear regression by reducing the penalty term. Since we are using Lasso Regression, there are two methods to perform alpha hyperparameter tuning. The first method is to use sklearn’s generic GridSearchCV which can be used to tune any machine learning model. The second method is to use sklearn’s own LassoCV which is specific to just Lasso regression. Let’s try both and compare their run times as well as the best alpha each can find. First, let’s run the GridSearchCV method: GridSearchCV execution time: 3124.58699989Lasso best params: {'alpha': 0.0004012807031942776}----Training Data results (2015 data set)----RMSE: $3.7R2: 0.91----Test Data results (2016 data set)----RMSE: $3.8R2: 0.90 Wow! with an alpha of 0.0004, we were able to obtain a test RMSE of just $3.8! However, the GridSearchCV method took a whopping 3124 seconds to run. That’s almost an hour! Let’s see if LassoCV can run faster but provide us with comparable results. Take note we shall use the same alpha search space for LassoCV to make this a true head to head comparison. LassoCV execution time: 42.0979998112LassoCV best params: 0.000401280703194----Training Data results (2015 data set)----RMSE: $3.7R2: 0.91----Test Data results (2016 data set)----RMSE: $3.8R2: 0.90 Fantastic! not only does LassoCV give us the same best alpha of 0.0004 to obtain a test RMSE of just $3.8, but it also runs much faster and can complete in just 42 seconds! I must admit, I am surprised by the results myself and will have to dig deeper to understand why LassoCV runs so much faster than GridSearchCV. For now, it looks like the best test score RMSE we can achieve using a linear model is $3.8. This is $1.7 lower than the RMSE of our simple intuitive model! Finally, let’s plot the actual fare vs the predicted fare from the LassoCV model to visually check the correlation Great! that look’s pretty promising. We could try to improve the model’s RMSE further by either trying a more complex model like Gradient Boosting or even a Neural Network. We could also add more data into the training set by querying 1 Million rows instead of 100K rows. What do you think? Please leave a comment on how we can improve the model further. Thank you for reading! Hope you found it interesting. Cheers!
[ { "code": null, "e": 560, "s": 172, "text": "Recently I had the opportunity to play with the New York taxi public data set hosted by Google cloud’s Big Query platform. I decided to apply machine learning techniques on the data set to try and build some predictive models using Python. For this post, I’ll attempt to predict the taxi fare amount. Let’s jump right into it! All the code for this article can be found on Github at Link" }, { "code": null, "e": 814, "s": 560, "text": "First, on inspecting the Google Big Query tables, we notice that there is one table per year. This gives me an idea. I could use the data from 2015 to train my machine learning models and then use the data from 2016 to test the model’s predictive power." }, { "code": null, "e": 931, "s": 814, "text": "Next, let’s query random 100K rows from 2015 and a random 100K rows from 2016 data using Google’s data lab platform." }, { "code": null, "e": 1152, "s": 931, "text": "Now, let’s begin the process of predicting taxi fare. First, let’s import the necessary packages and load the data into a pandas data frame. I use the %matplotlib inline as I am using a jupyter notebook for the analysis." }, { "code": null, "e": 1261, "s": 1152, "text": "From the data frame, we see that each row is one trip while each column is an attribute related to the trip." }, { "code": null, "e": 1492, "s": 1261, "text": "I like to start my projects by first building a predictive model purely from intuition. This simple intuitive model will give us our baseline accuracy and we shall try to beat this baseline accuracy using more advanced techniques." }, { "code": null, "e": 2167, "s": 1492, "text": "For any predictive model, we need to consider what is the response variable we are trying to predict and what are the feature variables that could have an impact on the said response. In this exercise, the response we want to predict is the fare_amount. Purely from an intuition perspective, we know that taxis generally charge on a fixed initial fee + a per km basis (total distance) + a per minute basis (total duration). Looking back at our data frame columns, we already have a trip_distance column, but we lack a trip_duration column. However, we are provided with pickup and dropoff datetimes, so we can easily calculate the trip_duration using these columns as below." }, { "code": null, "e": 2293, "s": 2167, "text": "Now, let us visualize the columns of interest for our simple intuitive model (fare_amount, trip_distance, and trip_duration)." }, { "code": null, "e": 2427, "s": 2293, "text": "As can be seen from the chart, there are significant outliers for all three columns. Let’s perform an outlier removal and plot again." }, { "code": null, "e": 2602, "s": 2427, "text": "Much better! Also, we can clearly see that there is a strong correlation between fare_amount to both the trip_distance and the trip_duration and so we are on the right track." }, { "code": null, "e": 3364, "s": 2602, "text": "Before we proceed further, let’s create some helper functions. The first function is to split the data so that the training dataset only has data from 2015 and the test dataset only has data from 2016 as mentioned before. The second function is to calculate some statistics that can be used to evaluate the predictive power of our models. For this exercise, the statistics I choose are Root Mean Square Error (RMSE) which gives the standard deviation of the difference between actual fare_amount and predicted fare_amount in $ and can be calculated as the square root of sklearn’s mean_squared_error(). The R-square gives how much percentage of the actual fare_amount’s variation is predicted by the model and can be directly obtained from sklearn’s r2_score()." }, { "code": null, "e": 3716, "s": 3364, "text": "Great! Now we are all set to build our first model purely from intuition. Let’s first split the data into the response (y) and features (X), then create the training and testing sets using the above helper function, then fit a simple Linear Regression model on the training dataset and finally, check the model results using the above helper function." }, { "code": null, "e": 3839, "s": 3716, "text": "----Training Data results (2015 data set)----RMSE: $5.6R2: 0.79----Test Data results (2016 data set)----RMSE: $5.5R2: 0.81" }, { "code": null, "e": 3999, "s": 3839, "text": "Not bad for our very first attempt! The testing dataset has an RMSE of $5.5 and we shall use this as our baseline score. Now, let us try to improve this score." }, { "code": null, "e": 4141, "s": 3999, "text": "The method I shall employ here is to add more features to the model by the process of feature engineering. Thinking deeper about the problem." }, { "code": null, "e": 4275, "s": 4141, "text": "Pickup day of the week and hour of the day could play an important role in demand and traffic conditions leading to an impact on fare" }, { "code": null, "e": 4387, "s": 4275, "text": "Latitude difference and Longitude difference could be additional data to augment trip_distance’s impact on fare" }, { "code": null, "e": 4496, "s": 4387, "text": "Pickup and dropoff neighborhoods could have an effect on fare due to additional fees for specific locations?" }, { "code": null, "e": 4961, "s": 4496, "text": "So, let’s add a few extra features as below. Geohashing is a method to create discrete geographic locations based on absolute latitude and longitudes. You can think of it as creating a common name for locations belonging to the same neighborhood. I use the pygeohash python package which can be installed using pip install pygeohash. Since there is a lot of missing data in the latitude and longitude columns, let’s remove them as well. The new features added are:" }, { "code": null, "e": 5109, "s": 4961, "text": "Pickup monthPickup day of the weekPickup hour of the dayLattitude differenceLongitude differenceGeohashed pickup locationGeohashed dropoff location" }, { "code": null, "e": 5122, "s": 5109, "text": "Pickup month" }, { "code": null, "e": 5145, "s": 5122, "text": "Pickup day of the week" }, { "code": null, "e": 5168, "s": 5145, "text": "Pickup hour of the day" }, { "code": null, "e": 5189, "s": 5168, "text": "Lattitude difference" }, { "code": null, "e": 5210, "s": 5189, "text": "Longitude difference" }, { "code": null, "e": 5236, "s": 5210, "text": "Geohashed pickup location" }, { "code": null, "e": 5263, "s": 5236, "text": "Geohashed dropoff location" }, { "code": null, "e": 5514, "s": 5263, "text": "Looks like there are some outliers in lat_dif and lon_dif, so let’s remove them. Also, since the columns like month, day_of_week, hour_of_day, pickup_geohash, and dropoff_geohash are categorical, let’s encode them using the pandas get_dummies method." }, { "code": null, "e": 5605, "s": 5514, "text": "Now let’s split the training and testing datasets and fit a simple Linear Regression model" }, { "code": null, "e": 5746, "s": 5605, "text": "----Training Data results (2015 data set)----RMSE: $3.5R2: 0.92----Test Data results (2016 data set)----RMSE: $7139352.0R2: -338832003532.88" }, { "code": null, "e": 6000, "s": 5746, "text": "Yikes! the model has better RMSE on the training dataset but much worse RMSE on the test dataset indicating that the model is overfitting. This necessitates the use of a regularization technique. We can use sklearn’s Lasso Regression for regularization." }, { "code": null, "e": 6123, "s": 6000, "text": "----Training Data results (2015 data set)----RMSE: $5.6R2: 0.79----Test Data results (2016 data set)----RMSE: $5.3R2: 0.82" }, { "code": null, "e": 6533, "s": 6123, "text": "Ok, that’s better from an over-fitting perspective but the Model RMSE did not improve much. Let us now try hyper-parameter tuning to improve the model RMSE. The parameter we can tune for Lasso Regression is called alpha which is a constant that multiplies the L1 penalty term. The default value of alpha is 1. Smaller alpha will make Lasso regression similar to Linear regression by reducing the penalty term." }, { "code": null, "e": 6922, "s": 6533, "text": "Since we are using Lasso Regression, there are two methods to perform alpha hyperparameter tuning. The first method is to use sklearn’s generic GridSearchCV which can be used to tune any machine learning model. The second method is to use sklearn’s own LassoCV which is specific to just Lasso regression. Let’s try both and compare their run times as well as the best alpha each can find." }, { "code": null, "e": 6964, "s": 6922, "text": "First, let’s run the GridSearchCV method:" }, { "code": null, "e": 7180, "s": 6964, "text": "GridSearchCV execution time: 3124.58699989Lasso best params: {'alpha': 0.0004012807031942776}----Training Data results (2015 data set)----RMSE: $3.7R2: 0.91----Test Data results (2016 data set)----RMSE: $3.8R2: 0.90" }, { "code": null, "e": 7536, "s": 7180, "text": "Wow! with an alpha of 0.0004, we were able to obtain a test RMSE of just $3.8! However, the GridSearchCV method took a whopping 3124 seconds to run. That’s almost an hour! Let’s see if LassoCV can run faster but provide us with comparable results. Take note we shall use the same alpha search space for LassoCV to make this a true head to head comparison." }, { "code": null, "e": 7734, "s": 7536, "text": "LassoCV execution time: 42.0979998112LassoCV best params: 0.000401280703194----Training Data results (2015 data set)----RMSE: $3.7R2: 0.91----Test Data results (2016 data set)----RMSE: $3.8R2: 0.90" }, { "code": null, "e": 8323, "s": 7734, "text": "Fantastic! not only does LassoCV give us the same best alpha of 0.0004 to obtain a test RMSE of just $3.8, but it also runs much faster and can complete in just 42 seconds! I must admit, I am surprised by the results myself and will have to dig deeper to understand why LassoCV runs so much faster than GridSearchCV. For now, it looks like the best test score RMSE we can achieve using a linear model is $3.8. This is $1.7 lower than the RMSE of our simple intuitive model! Finally, let’s plot the actual fare vs the predicted fare from the LassoCV model to visually check the correlation" }, { "code": null, "e": 8360, "s": 8323, "text": "Great! that look’s pretty promising." }, { "code": null, "e": 8678, "s": 8360, "text": "We could try to improve the model’s RMSE further by either trying a more complex model like Gradient Boosting or even a Neural Network. We could also add more data into the training set by querying 1 Million rows instead of 100K rows. What do you think? Please leave a comment on how we can improve the model further." } ]
NHibernate - Configuration
In this chapter, we will look at NHibernate configuration. We have different ways that we can configure NHibernate. It divides into two main groups XML-based configuration Code-based configuration The code-based configuration is built into NHibernate. It was introduced around the NHibernate 3 and we have used the code bases configuration up till now. String Data Source = asia13797\\sqlexpress; String Initial Catalog = NHibernateDemoDB; String Integrated Security = True; String Connect Timeout = 15; String Encrypt = False; String TrustServerCertificate = False; String ApplicationIntent = ReadWrite; String MultiSubnetFailover = False; cfg.DataBaseIntegration(x = > { x.ConnectionString = "Data Source + Initial Catalog + Integrated Security + Connect Timeout + Encrypt + TrustServerCertificate + ApplicationIntent + MultiSubnetFailover"; x.Driver<SqlClientDriver>(); x.Dialect<MsSql2008Dialect>(); x.LogSqlInConsole = true; }); cfg.AddAssembly(Assembly.GetExecutingAssembly()); All the configurations are specified in the C# code. You can see here that we have got our new configuration object, and then we use loquacious configuration that was introduced with NHibernate 3.1 to configure the database. What connection string we are using, what database we are connecting to and the dialect to use. We also add our mapping assembly directly to here. If you are using XML-based configuration, you can use a hibernate.cfg.xml file, which is just a standalone xml file using the NHibernate schema, or you can embed that NHibernate specific configuration inside of your app or web.cfg. The hibernate.cfg.xml name is by default, but we can use an arbitrary name for that xml file as well. Let’s have a look into the XML-based configuration by adding a new xml file to the NHibernateDemoApp project and call it hibernate.cfg.xml. Enter the following information into the hibernate.cfg.xml file. <?xml version = "1.0" encoding = "utf-8" ?> <hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2"> <session-factory> <property name = "connection.connection_string"> Data Source = asia13797\\sqlexpress; Initial Catalog = NHibernateDemoDB; Integrated Security = True; Connect Timeout = 15; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False; </property> <property name = "connection.driver_class"> NHibernate.Driver.SqlClientDriver </property> <property name = "dialect"> NHibernate.Dialect.MsSql2008Dialect </property> <mapping assembly = "NHibernateDemoApp"/> </session-factory> </hibernate-configuration> As you can see in the above xml file, we have specified the same configuration as mentioned in the C#. Now let’s comment on this configuration from the Program.cs file and just call the Configure() method, which will load the hibernate.cfg.xml file as shown below. using HibernatingRhinos.Profiler.Appender.NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using System; using System.Linq; using System.Reflection; namespace NHibernateDemoApp { class Program { static void Main(string[] args) { NHibernateProfiler.Initialize(); var cfg = new Configuration(); //cfg.DataBaseIntegration(x => //{ // x.ConnectionString = "Data Source = asia13797;\\sqlexpress Initial Catalog = NHibernateDemoDB; Integrated Security = True; Connect Timeout = 15; Encrypt =False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"; // x.Driver<SqlClientDriver>(); // x.Dialect<MsSql2008Dialect>(); // x.LogSqlInConsole = true; //}); //cfg.AddAssembly(Assembly.GetExecutingAssembly()); cfg.Configure(); var sefact = cfg.BuildSessionFactory(); using (var session = sefact.OpenSession()) { using (var tx = session.BeginTransaction()) { var students = session.CreateCriteria<Student>().List<Student>(); Console.WriteLine("\nFetch the complete list again\n"); foreach (var student in students) { Console.WriteLine("{0} \t{1} \t{2} \t{3}", student.ID, student.FirstName, student.LastName, student.AcademicStanding); } tx.Commit(); } Console.ReadLine(); } } } } Let’s run your application again and you will see the same output. Fetch the complete list again 1 Allan Bommer Excellent 2 Jerry Lewis Good Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2333, "text": "In this chapter, we will look at NHibernate configuration. We have different ways that we can configure NHibernate. It divides into two main groups" }, { "code": null, "e": 2505, "s": 2481, "text": "XML-based configuration" }, { "code": null, "e": 2530, "s": 2505, "text": "Code-based configuration" }, { "code": null, "e": 2686, "s": 2530, "text": "The code-based configuration is built into NHibernate. It was introduced around the NHibernate 3 and we have used the code bases configuration up till now." }, { "code": null, "e": 3344, "s": 2686, "text": "String Data Source = asia13797\\\\sqlexpress;\nString Initial Catalog = NHibernateDemoDB;\nString Integrated Security = True;\nString Connect Timeout = 15;\nString Encrypt = False;\nString TrustServerCertificate = False;\nString ApplicationIntent = ReadWrite;\nString MultiSubnetFailover = False;\n\ncfg.DataBaseIntegration(x = > { x.ConnectionString = \"Data Source + \n Initial Catalog + Integrated Security + Connect Timeout + Encrypt +\n TrustServerCertificate + ApplicationIntent + MultiSubnetFailover\"; \n \n x.Driver<SqlClientDriver>(); \n x.Dialect<MsSql2008Dialect>(); \n x.LogSqlInConsole = true; \n}); \n\ncfg.AddAssembly(Assembly.GetExecutingAssembly());" }, { "code": null, "e": 3716, "s": 3344, "text": "All the configurations are specified in the C# code. You can see here that we have got our new configuration object, and then we use loquacious configuration that was introduced with NHibernate 3.1 to configure the database. What connection string we are using, what database we are connecting to and the dialect to use. We also add our mapping assembly directly to here." }, { "code": null, "e": 4050, "s": 3716, "text": "If you are using XML-based configuration, you can use a hibernate.cfg.xml file, which is just a standalone xml file using the NHibernate schema, or you can embed that NHibernate specific configuration inside of your app or web.cfg. The hibernate.cfg.xml name is by default, but we can use an arbitrary name for that xml file as well." }, { "code": null, "e": 4190, "s": 4050, "text": "Let’s have a look into the XML-based configuration by adding a new xml file to the NHibernateDemoApp project and call it hibernate.cfg.xml." }, { "code": null, "e": 4255, "s": 4190, "text": "Enter the following information into the hibernate.cfg.xml file." }, { "code": null, "e": 5100, "s": 4255, "text": "<?xml version = \"1.0\" encoding = \"utf-8\" ?> \n<hibernate-configuration xmlns = \"urn:nhibernate-configuration-2.2\"> \n <session-factory> \n \n <property name = \"connection.connection_string\">\n Data Source = asia13797\\\\sqlexpress;\n Initial Catalog = NHibernateDemoDB;\n Integrated Security = True;\n Connect Timeout = 15;\n Encrypt = False;\n TrustServerCertificate = False;\n ApplicationIntent = ReadWrite;\n MultiSubnetFailover = False;\n </property> \n \n <property name = \"connection.driver_class\">\n NHibernate.Driver.SqlClientDriver\n </property> \n\t\t\n <property name = \"dialect\">\n NHibernate.Dialect.MsSql2008Dialect\n </property> \n\t\t\n <mapping assembly = \"NHibernateDemoApp\"/>\n\t\t\n </session-factory> \n\t\n</hibernate-configuration>" }, { "code": null, "e": 5203, "s": 5100, "text": "As you can see in the above xml file, we have specified the same configuration as mentioned in the C#." }, { "code": null, "e": 5365, "s": 5203, "text": "Now let’s comment on this configuration from the Program.cs file and just call the Configure() method, which will load the hibernate.cfg.xml file as shown below." }, { "code": null, "e": 7134, "s": 5365, "text": "using HibernatingRhinos.Profiler.Appender.NHibernate; \nusing NHibernate.Cfg; \nusing NHibernate.Dialect; \nusing NHibernate.Driver; \n\nusing System; \nusing System.Linq; \nusing System.Reflection; \n\nnamespace NHibernateDemoApp { \n\n class Program { \n \n static void Main(string[] args) { \n\t\t\n NHibernateProfiler.Initialize(); \n var cfg = new Configuration(); \n \n //cfg.DataBaseIntegration(x =>\n \n //{ \n // x.ConnectionString = \"Data Source = asia13797;\\\\sqlexpress\n Initial Catalog = NHibernateDemoDB;\n Integrated Security = True;\n Connect Timeout = 15;\n Encrypt =False;\n TrustServerCertificate = False;\n ApplicationIntent = ReadWrite;\n MultiSubnetFailover = False\"; \n \n // x.Driver<SqlClientDriver>(); \n // x.Dialect<MsSql2008Dialect>(); \n // x.LogSqlInConsole = true; \n //}); \n \n //cfg.AddAssembly(Assembly.GetExecutingAssembly());\n\t\t\t\n cfg.Configure();\n var sefact = cfg.BuildSessionFactory();\n\t\t\t\n using (var session = sefact.OpenSession()) { \n \n using (var tx = session.BeginTransaction()) { \n var students = session.CreateCriteria<Student>().List<Student>(); \n Console.WriteLine(\"\\nFetch the complete list again\\n\"); \n \n foreach (var student in students) { \n Console.WriteLine(\"{0} \\t{1} \\t{2} \\t{3}\", student.ID,\n student.FirstName, student.LastName, student.AcademicStanding); \n } \n\t\t\t\t\t\n tx.Commit(); \n } \n\t\t\t\t\n Console.ReadLine(); \n } \n } \n } \n}" }, { "code": null, "e": 7201, "s": 7134, "text": "Let’s run your application again and you will see the same output." }, { "code": null, "e": 7277, "s": 7201, "text": "Fetch the complete list again\n\n1 Allan Bommer Excellent\n2 Jerry Lewis Good\n" }, { "code": null, "e": 7284, "s": 7277, "text": " Print" }, { "code": null, "e": 7295, "s": 7284, "text": " Add Notes" } ]
Loading CSV data into Azure Synapse Analytics by using PolyBase | by Dhyanendra Singh Rathore | Towards Data Science
Azure Synapse Analytics SQL pool supports various data loading methods. The fastest and most scalable way to load data is through PolyBase. PolyBase is a data virtualization technology that can access external data stored in Hadoop or Azure Data Lake Storage via the T-SQL language. PolyBase shifts the data loading paradigm from ETL to ELT. The data is first loaded into a staging table followed by the transformation steps and finally loaded into the production tables. In this article, we load a CSV file from an Azure Data Lake Storage Gen2 account to an Azure Synapse Analytics data warehouse by using PolyBase. We will look at the detailed steps to carry out the loading procedure. Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization. Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5 An active Microsoft Azure subscriptionAzure Data Lake Storage Gen2 account with CSV filesAzure Synapse Analytics data warehouse An active Microsoft Azure subscription Azure Data Lake Storage Gen2 account with CSV files Azure Synapse Analytics data warehouse To use PolyBase, you need to define external tables in your SQL pool before loading. PolyBase uses external tables to define and access the data from the Azure storage. The external table contains the table schema and points to data that is stored outside the SQL pool. Defining external tables involves specifying three objects: data source, the format of the text files, and the table definitions. External tables are in-memory tables that don’t persist onto the physical disk. External tables can be queried like any other table. The external data source object provides the connection information required to connect to the external data source itself, in our case, the ADLS account. Let’s begin by collecting the URL and the access key. Sign in to the Azure Portal, and navigate to your storage account. Click on Access Keys and copy the Key and the Storage account name to a notepad. The next step is to create a database scoped credential to secure the credentials to the ADLS account. Create a database master key if one does not already exist, and then encrypt the database-scoped credential named ADLS_Credential using the master key. The database master key is used to encrypt the private keys of certificates and keys that are present in the database. A database scoped credential contains the authentication information required to connect to an external resource. You can run the below T-SQL statements in SSMS or a tool of your choice or Query editor (preview) from the Common Tasks section of your Synapse instance in the Azure portal. Replace the storage account name, storage account key, and password accordingly. -- Create a database master key if one does not already exist, using your own password. This key will be used to encrypt the credential secret in next step.CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Pa$$word123' ;CREATE DATABASE SCOPED CREDENTIAL ADLS_CredentialWITH-- IDENTITY = '<storage_account_name>' ,-- SECRET = '<storage_account_key>'IDENTITY = 'dlspolybasestorage' , SECRET = 'zN9S8mggblYX/sEiz5DVRmcZWjPw65A393bzD9T5rQjo+LnI5GAGrjdLvt4iqK5YEWMSMqV82IsVm3Bww6uw=='; Follow our article for instructions on how to connect and access Azure Synapse Analytics from SSMS: medium.com Further reading on the database master key and the database scoped credentials: docs.microsoft.com docs.microsoft.com Use the database-scoped credential to create an external data source named AzureStorage. The location URL point to the container named csvstore in the ADLS Gen2 account. The type Hadoop is used for both Hadoop-based and Azure Blob storage-based external sources. Modify the location to refer to your storage account and the container. -- Note this example uses a ADLS Gen2 secured endpoint (abfss)CREATE EXTERNAL DATA SOURCE AzureStorageWITH ( LOCATION = 'abfss://csvstore@dlspolybasestorage.dfs.core.windows.net' , CREDENTIAL = ADLS_Credential , TYPE = HADOOP ); Further reading on creating external data source: docs.microsoft.com The external file format object contains how the data in a file is structured and defines how rows are defined and what column separators are used. Run the below query to define the external file format named csvFile. For this exercise, we’re using a CSV file available here. This file has 4,167 data rows and a header row. FORMAT_TYPE indicates to PolyBase that the format of the text file is DelimitedText. FIELD_TERMINATOR specifies column separator. STRING_DELIMITER specifies the field terminator for string type data. FIRST_ROW specifies the row number that is read first during the PolyBase load. If the value is set to two, the header row is skipped when the data is loaded. USE_TYPE_DEFAULT specifies how to handle missing values; FALSE means store all missing values as NULL. ENCODING specifies the encoding of the external file. -- Create an external file format for DELIMITED (CSV/TSV) files. CREATE EXTERNAL FILE FORMAT csvFileWITH ( FORMAT_TYPE = DELIMITEDTEXT, FORMAT_OPTIONS ( FIELD_TERMINATOR = ',', STRING_DELIMITER = '"', FIRST_ROW = 2, USE_TYPE_DEFAULT = FALSE, ENCODING = 'UTF8' )); Further reading on creating an external file format: docs.microsoft.com The external table object uses the external data source and external file format objects to define the external table structure within Azure Synapse Analytics. You can then use the external table as a basis for loading data into your data warehouse. Create an external table named dbo.FIPSLOOKUP_EXT with the column definition corresponding to your CSV file. Use a WITH clause to call the external data source definition (AzureStorage) and the external file format (csvFile) we created in the previous steps. The location denotes that the file to load is in the root folder of the data source. -- Create a temp table to hold the imported dataCREATE EXTERNAL TABLE dbo.FIPSLOOKUP_EXT ( UID INT NOT NULL, iso2 VARCHAR(2) NULL, iso3 VARCHAR(3) NULL, code3 INT NULL, FIPS INT NULL, Admin2 VARCHAR(255) NULL, provincestate VARCHAR(255) NULL, countryregion VARCHAR(255) NULL, latitude DECIMAL(12,9) NULL, longitude DECIMAL(12,9) NULL, combined_key VARCHAR(255) NULL, population INT NULL)WITH ( LOCATION='../', DATA_SOURCE=AzureStorage, FILE_FORMAT=csvFile); Run the query and refresh the Object Explorer in SSMS. At this point, we can see all the three external objects we have created so far. Let’s run a quick SELECT query to see the data from our external table and test our external objects. Further reading on creating an external table: docs.microsoft.com We have set up our PolyBase correctly; however, the data is not yet physically stored in our data warehouse. The data still exists only in the ADLS account. We need to load this data into a physical table to persist in our data warehouse physically. Create a physical table in the Azure Synapse Analytics. The table will have a clustered column store index defined on all the columns with a round-robin table geometry because round-robin is the best table geometry to use for loading the data. -- Load the data from Azure Data Lake Store Gen2 to Azure Synapse Analytics data warehouseCREATE TABLE dbo.FIPSLOOKUPWITH ( CLUSTERED COLUMNSTORE INDEX, DISTRIBUTION = ROUND_ROBIN)ASSELECT * FROM dbo.FIPSLOOKUP_EXT; Let’s quickly examine the number of rows loaded into the physical table. The total number of rows loaded is 4,167, meaning none of the rows were discarded during the load. That’s all, folks. You’ve successfully loaded a CSV file into your Azure Synapse Analytics data warehouse using PolyBase. If you need to transform or cleanse the data you’ve just loaded, the best spot to do it is to introduce the cleansing and transformation query during the load from the external table to the physical table. This is the ETL to ELT paradigm shift enabled by the PolyBase we discussed earlier. We loaded CSV data into our Azure Synapse Analytics data warehouse by using PolyBase. We created three external objects and loaded a file stored in ADLS Gen2 account to a physical data table. Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering. You can join him on Medium or connect with him on LinkedIn. Got any topic-related issues you wish to discuss? Shoot an email to dhyan.singh@everydaybi.com for a private consultation.
[ { "code": null, "e": 455, "s": 172, "text": "Azure Synapse Analytics SQL pool supports various data loading methods. The fastest and most scalable way to load data is through PolyBase. PolyBase is a data virtualization technology that can access external data stored in Hadoop or Azure Data Lake Storage via the T-SQL language." }, { "code": null, "e": 644, "s": 455, "text": "PolyBase shifts the data loading paradigm from ETL to ELT. The data is first loaded into a staging table followed by the transformation steps and finally loaded into the production tables." }, { "code": null, "e": 860, "s": 644, "text": "In this article, we load a CSV file from an Azure Data Lake Storage Gen2 account to an Azure Synapse Analytics data warehouse by using PolyBase. We will look at the detailed steps to carry out the loading procedure." }, { "code": null, "e": 990, "s": 860, "text": "Caution: Microsoft Azure is a paid service, and following this article can cause financial liability to you or your organization." }, { "code": null, "e": 1135, "s": 990, "text": "Please read our terms of use before proceeding with this article: https://dhyanintech.medium.com/disclaimer-disclosure-terms-of-use-fb3bfbd1e0e5" }, { "code": null, "e": 1263, "s": 1135, "text": "An active Microsoft Azure subscriptionAzure Data Lake Storage Gen2 account with CSV filesAzure Synapse Analytics data warehouse" }, { "code": null, "e": 1302, "s": 1263, "text": "An active Microsoft Azure subscription" }, { "code": null, "e": 1354, "s": 1302, "text": "Azure Data Lake Storage Gen2 account with CSV files" }, { "code": null, "e": 1393, "s": 1354, "text": "Azure Synapse Analytics data warehouse" }, { "code": null, "e": 1793, "s": 1393, "text": "To use PolyBase, you need to define external tables in your SQL pool before loading. PolyBase uses external tables to define and access the data from the Azure storage. The external table contains the table schema and points to data that is stored outside the SQL pool. Defining external tables involves specifying three objects: data source, the format of the text files, and the table definitions." }, { "code": null, "e": 1926, "s": 1793, "text": "External tables are in-memory tables that don’t persist onto the physical disk. External tables can be queried like any other table." }, { "code": null, "e": 2283, "s": 1926, "text": "The external data source object provides the connection information required to connect to the external data source itself, in our case, the ADLS account. Let’s begin by collecting the URL and the access key. Sign in to the Azure Portal, and navigate to your storage account. Click on Access Keys and copy the Key and the Storage account name to a notepad." }, { "code": null, "e": 2538, "s": 2283, "text": "The next step is to create a database scoped credential to secure the credentials to the ADLS account. Create a database master key if one does not already exist, and then encrypt the database-scoped credential named ADLS_Credential using the master key." }, { "code": null, "e": 2657, "s": 2538, "text": "The database master key is used to encrypt the private keys of certificates and keys that are present in the database." }, { "code": null, "e": 2771, "s": 2657, "text": "A database scoped credential contains the authentication information required to connect to an external resource." }, { "code": null, "e": 3026, "s": 2771, "text": "You can run the below T-SQL statements in SSMS or a tool of your choice or Query editor (preview) from the Common Tasks section of your Synapse instance in the Azure portal. Replace the storage account name, storage account key, and password accordingly." }, { "code": null, "e": 3502, "s": 3026, "text": "-- Create a database master key if one does not already exist, using your own password. This key will be used to encrypt the credential secret in next step.CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'Pa$$word123' ;CREATE DATABASE SCOPED CREDENTIAL ADLS_CredentialWITH-- IDENTITY = '<storage_account_name>' ,-- SECRET = '<storage_account_key>'IDENTITY = 'dlspolybasestorage' , SECRET = 'zN9S8mggblYX/sEiz5DVRmcZWjPw65A393bzD9T5rQjo+LnI5GAGrjdLvt4iqK5YEWMSMqV82IsVm3Bww6uw==';" }, { "code": null, "e": 3602, "s": 3502, "text": "Follow our article for instructions on how to connect and access Azure Synapse Analytics from SSMS:" }, { "code": null, "e": 3613, "s": 3602, "text": "medium.com" }, { "code": null, "e": 3693, "s": 3613, "text": "Further reading on the database master key and the database scoped credentials:" }, { "code": null, "e": 3712, "s": 3693, "text": "docs.microsoft.com" }, { "code": null, "e": 3731, "s": 3712, "text": "docs.microsoft.com" }, { "code": null, "e": 4066, "s": 3731, "text": "Use the database-scoped credential to create an external data source named AzureStorage. The location URL point to the container named csvstore in the ADLS Gen2 account. The type Hadoop is used for both Hadoop-based and Azure Blob storage-based external sources. Modify the location to refer to your storage account and the container." }, { "code": null, "e": 4303, "s": 4066, "text": "-- Note this example uses a ADLS Gen2 secured endpoint (abfss)CREATE EXTERNAL DATA SOURCE AzureStorageWITH ( LOCATION = 'abfss://csvstore@dlspolybasestorage.dfs.core.windows.net' , CREDENTIAL = ADLS_Credential , TYPE = HADOOP );" }, { "code": null, "e": 4353, "s": 4303, "text": "Further reading on creating external data source:" }, { "code": null, "e": 4372, "s": 4353, "text": "docs.microsoft.com" }, { "code": null, "e": 4696, "s": 4372, "text": "The external file format object contains how the data in a file is structured and defines how rows are defined and what column separators are used. Run the below query to define the external file format named csvFile. For this exercise, we’re using a CSV file available here. This file has 4,167 data rows and a header row." }, { "code": null, "e": 5212, "s": 4696, "text": "FORMAT_TYPE indicates to PolyBase that the format of the text file is DelimitedText. FIELD_TERMINATOR specifies column separator. STRING_DELIMITER specifies the field terminator for string type data. FIRST_ROW specifies the row number that is read first during the PolyBase load. If the value is set to two, the header row is skipped when the data is loaded. USE_TYPE_DEFAULT specifies how to handle missing values; FALSE means store all missing values as NULL. ENCODING specifies the encoding of the external file." }, { "code": null, "e": 5507, "s": 5212, "text": "-- Create an external file format for DELIMITED (CSV/TSV) files. CREATE EXTERNAL FILE FORMAT csvFileWITH ( FORMAT_TYPE = DELIMITEDTEXT, FORMAT_OPTIONS ( FIELD_TERMINATOR = ',', STRING_DELIMITER = '\"', FIRST_ROW = 2, USE_TYPE_DEFAULT = FALSE, ENCODING = 'UTF8' ));" }, { "code": null, "e": 5560, "s": 5507, "text": "Further reading on creating an external file format:" }, { "code": null, "e": 5579, "s": 5560, "text": "docs.microsoft.com" }, { "code": null, "e": 5829, "s": 5579, "text": "The external table object uses the external data source and external file format objects to define the external table structure within Azure Synapse Analytics. You can then use the external table as a basis for loading data into your data warehouse." }, { "code": null, "e": 6173, "s": 5829, "text": "Create an external table named dbo.FIPSLOOKUP_EXT with the column definition corresponding to your CSV file. Use a WITH clause to call the external data source definition (AzureStorage) and the external file format (csvFile) we created in the previous steps. The location denotes that the file to load is in the root folder of the data source." }, { "code": null, "e": 6664, "s": 6173, "text": "-- Create a temp table to hold the imported dataCREATE EXTERNAL TABLE dbo.FIPSLOOKUP_EXT ( UID INT NOT NULL, iso2 VARCHAR(2) NULL, iso3 VARCHAR(3) NULL, code3 INT NULL, FIPS INT NULL, Admin2 VARCHAR(255) NULL, provincestate VARCHAR(255) NULL, countryregion VARCHAR(255) NULL, latitude DECIMAL(12,9) NULL, longitude DECIMAL(12,9) NULL, combined_key VARCHAR(255) NULL, population INT NULL)WITH ( LOCATION='../', DATA_SOURCE=AzureStorage, FILE_FORMAT=csvFile);" }, { "code": null, "e": 6800, "s": 6664, "text": "Run the query and refresh the Object Explorer in SSMS. At this point, we can see all the three external objects we have created so far." }, { "code": null, "e": 6902, "s": 6800, "text": "Let’s run a quick SELECT query to see the data from our external table and test our external objects." }, { "code": null, "e": 6949, "s": 6902, "text": "Further reading on creating an external table:" }, { "code": null, "e": 6968, "s": 6949, "text": "docs.microsoft.com" }, { "code": null, "e": 7218, "s": 6968, "text": "We have set up our PolyBase correctly; however, the data is not yet physically stored in our data warehouse. The data still exists only in the ADLS account. We need to load this data into a physical table to persist in our data warehouse physically." }, { "code": null, "e": 7462, "s": 7218, "text": "Create a physical table in the Azure Synapse Analytics. The table will have a clustered column store index defined on all the columns with a round-robin table geometry because round-robin is the best table geometry to use for loading the data." }, { "code": null, "e": 7687, "s": 7462, "text": "-- Load the data from Azure Data Lake Store Gen2 to Azure Synapse Analytics data warehouseCREATE TABLE dbo.FIPSLOOKUPWITH ( CLUSTERED COLUMNSTORE INDEX, DISTRIBUTION = ROUND_ROBIN)ASSELECT * FROM dbo.FIPSLOOKUP_EXT;" }, { "code": null, "e": 7859, "s": 7687, "text": "Let’s quickly examine the number of rows loaded into the physical table. The total number of rows loaded is 4,167, meaning none of the rows were discarded during the load." }, { "code": null, "e": 8271, "s": 7859, "text": "That’s all, folks. You’ve successfully loaded a CSV file into your Azure Synapse Analytics data warehouse using PolyBase. If you need to transform or cleanse the data you’ve just loaded, the best spot to do it is to introduce the cleansing and transformation query during the load from the external table to the physical table. This is the ETL to ELT paradigm shift enabled by the PolyBase we discussed earlier." }, { "code": null, "e": 8463, "s": 8271, "text": "We loaded CSV data into our Azure Synapse Analytics data warehouse by using PolyBase. We created three external objects and loaded a file stored in ADLS Gen2 account to a physical data table." }, { "code": null, "e": 8730, "s": 8463, "text": "Dhyanendra Singh Rathore is a Microsoft-certified Data, BI, and power platform professional. He is passionate about solving problems and currently gravitating towards serverless computing and AI platforms. He has a Master’s degree in Computer Networking Engineering." }, { "code": null, "e": 8790, "s": 8730, "text": "You can join him on Medium or connect with him on LinkedIn." } ]
Distributed Application Paradigms - GeeksforGeeks
03 Sep, 2021 Paradigm means an idea or pattern. In this article, we will see the classification of the paradigms for distributed applications. Level of Abstraction: Message Passing Paradigm: It is a basic approach for Inter Process Communication. The data exchange between the sender and the receiver. A process sends a message representing the request. The receiver receives and processes it then sends back as reply. Operations: send, receive Connections: connect, disconnect Client Server Paradigm: In this approach, the server acts as a service provider, the client issues the request and wait for the response from the server. Here server is dump machine. Until client make a call server doesn’t communicate. Many Internet services are client-server applications. Server Process: listen, accept Client Process: issue the request, accept the response Peer to Peer Paradigm: Direct communication between processes. Here is no client or server, anyone can make request to others and get the response. Example: A well-known example of a peer-to-peer file transfer. Message System Paradigm: Message system act as intermediate among independent processes. It is also act as switch through which process exchange messages asynchronously in decoupled manner. sender sends message which drop at first in message system then forward to message queue which is associated with the receiver. Types: Point to Point message model Publish/Subscribe model Point to Point message model: Forward message from sender to receiver via message system. The message system keeps repository of messages and directly forward messages to the receiver’s message queue. Unlike the basic message-passing model, it provides asynchronous message passing. Public/Subscribe Model: In this model, each message is associated with a specific topic or event. whoever interest in the messages can subscribe to the event before it occurs. When the waited event occurs, the process publishes the message with an event or topic. Then the message system distributes messages to all the subscribers. Example: IBM MQ service, Microsoft Message Queuing Remote Procedure Call: Local procedure call happens only within a local machine. Remote Procedure call(RPC) happens between two remote machines. RPC involves two independent processes that may reside on a separate machine. Process A wishing to make a request process B for procedure call with a list of arguments. Process B operates the procedure and return values to Process A. Distributed Object Paradigm: Application access the objects distributed over the network. Objects provide methods, through the invocation of which an application obtains access to services. Types: Remote Method Invocation (RMI) Object Request Broker Object Space Remote Method Invocation: RMI is more like RPC but major difference is, it is object-oriented approach. A process invokes the methods in an object, which may reside in a remote host. Arguments may be passed with the invocation. Object Request Broker (ORB): ORB acts as mediator between objects and object requester, it allows requester can access multiple remote objects. An application issues requests to an object request broker (ORB), which directs the request to an appropriate object that provides service. Example: CORBA Object Space: Objects are placed as logical entities in the space called object space. Providers place their objects entries in the objects space. Requests who subscribe can access the objects. Mobile Agent Paradigm: Mobile agent starts from originated host and transports over host to host. At each host, the agent can access the services or resources to complete the mission. Network Service Paradigm: All the service objects are register with global directory service. If process want a service can contact directory service at runtime. Requestor is provided a reference, using which process interact with service. services are identified by the global unique identifier. Example: Java Jini Collaborative Application Paradigm: processes participate in a collaborative session as a group. Each participating process may contribute input to part or all of the group. Types: Message based groupware paradigm Whiteboard based groupware paradigm Message based groupware paradigm: A host can multicast to send data to all hosts in the group or part of the hosts in the group. Whiteboard based groupware paradigm: The information is available on the public board in the group whoever in the group can access it. Anyone can read or write data to a shared display kalrap615 Distributed System Technical Scripter 2019 Operating Systems Technical Scripter Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Memory Management in Operating System Difference between Internal and External fragmentation Program for Least Recently Used (LRU) Page Replacement algorithm Logical and Physical Address in Operating System Mutex lock for Linux Thread Synchronization States of a Process in Operating Systems File Allocation Methods Dining Philosopher Problem Using Semaphores Process Table and Process Control Block (PCB) Introduction of Process Management
[ { "code": null, "e": 24412, "s": 24384, "text": "\n03 Sep, 2021" }, { "code": null, "e": 24543, "s": 24412, "text": "Paradigm means an idea or pattern. In this article, we will see the classification of the paradigms for distributed applications. " }, { "code": null, "e": 24566, "s": 24543, "text": "Level of Abstraction: " }, { "code": null, "e": 24822, "s": 24566, "text": "Message Passing Paradigm: It is a basic approach for Inter Process Communication. The data exchange between the sender and the receiver. A process sends a message representing the request. The receiver receives and processes it then sends back as reply. " }, { "code": null, "e": 24882, "s": 24822, "text": "Operations: send, receive\nConnections: connect, disconnect " }, { "code": null, "e": 25175, "s": 24882, "text": "Client Server Paradigm: In this approach, the server acts as a service provider, the client issues the request and wait for the response from the server. Here server is dump machine. Until client make a call server doesn’t communicate. Many Internet services are client-server applications. " }, { "code": null, "e": 25262, "s": 25175, "text": "Server Process: listen, accept\nClient Process: issue the request, accept the response " }, { "code": null, "e": 25411, "s": 25262, "text": "Peer to Peer Paradigm: Direct communication between processes. Here is no client or server, anyone can make request to others and get the response. " }, { "code": null, "e": 25476, "s": 25411, "text": "Example: A well-known example of a peer-to-peer file transfer. " }, { "code": null, "e": 25795, "s": 25476, "text": "Message System Paradigm: Message system act as intermediate among independent processes. It is also act as switch through which process exchange messages asynchronously in decoupled manner. sender sends message which drop at first in message system then forward to message queue which is associated with the receiver. " }, { "code": null, "e": 25803, "s": 25795, "text": "Types: " }, { "code": null, "e": 25832, "s": 25803, "text": "Point to Point message model" }, { "code": null, "e": 25856, "s": 25832, "text": "Publish/Subscribe model" }, { "code": null, "e": 26140, "s": 25856, "text": "Point to Point message model: Forward message from sender to receiver via message system. The message system keeps repository of messages and directly forward messages to the receiver’s message queue. Unlike the basic message-passing model, it provides asynchronous message passing. " }, { "code": null, "e": 26525, "s": 26140, "text": "Public/Subscribe Model: In this model, each message is associated with a specific topic or event. whoever interest in the messages can subscribe to the event before it occurs. When the waited event occurs, the process publishes the message with an event or topic. Then the message system distributes messages to all the subscribers. Example: IBM MQ service, Microsoft Message Queuing " }, { "code": null, "e": 26549, "s": 26525, "text": "Remote Procedure Call: " }, { "code": null, "e": 26672, "s": 26549, "text": "Local procedure call happens only within a local machine. Remote Procedure call(RPC) happens between two remote machines. " }, { "code": null, "e": 26907, "s": 26672, "text": "RPC involves two independent processes that may reside on a separate machine. Process A wishing to make a request process B for procedure call with a list of arguments. Process B operates the procedure and return values to Process A. " }, { "code": null, "e": 27098, "s": 26907, "text": "Distributed Object Paradigm: Application access the objects distributed over the network. Objects provide methods, through the invocation of which an application obtains access to services. " }, { "code": null, "e": 27106, "s": 27098, "text": "Types: " }, { "code": null, "e": 27137, "s": 27106, "text": "Remote Method Invocation (RMI)" }, { "code": null, "e": 27159, "s": 27137, "text": "Object Request Broker" }, { "code": null, "e": 27172, "s": 27159, "text": "Object Space" }, { "code": null, "e": 27402, "s": 27172, "text": "Remote Method Invocation: RMI is more like RPC but major difference is, it is object-oriented approach. A process invokes the methods in an object, which may reside in a remote host. Arguments may be passed with the invocation. " }, { "code": null, "e": 27687, "s": 27402, "text": "Object Request Broker (ORB): ORB acts as mediator between objects and object requester, it allows requester can access multiple remote objects. An application issues requests to an object request broker (ORB), which directs the request to an appropriate object that provides service. " }, { "code": null, "e": 27703, "s": 27687, "text": "Example: CORBA " }, { "code": null, "e": 27899, "s": 27703, "text": "Object Space: Objects are placed as logical entities in the space called object space. Providers place their objects entries in the objects space. Requests who subscribe can access the objects. " }, { "code": null, "e": 28084, "s": 27899, "text": "Mobile Agent Paradigm: Mobile agent starts from originated host and transports over host to host. At each host, the agent can access the services or resources to complete the mission. " }, { "code": null, "e": 28401, "s": 28084, "text": "Network Service Paradigm: All the service objects are register with global directory service. If process want a service can contact directory service at runtime. Requestor is provided a reference, using which process interact with service. services are identified by the global unique identifier. Example: Java Jini " }, { "code": null, "e": 28576, "s": 28401, "text": "Collaborative Application Paradigm: processes participate in a collaborative session as a group. Each participating process may contribute input to part or all of the group. " }, { "code": null, "e": 28585, "s": 28576, "text": "Types: " }, { "code": null, "e": 28618, "s": 28585, "text": "Message based groupware paradigm" }, { "code": null, "e": 28654, "s": 28618, "text": "Whiteboard based groupware paradigm" }, { "code": null, "e": 28784, "s": 28654, "text": "Message based groupware paradigm: A host can multicast to send data to all hosts in the group or part of the hosts in the group. " }, { "code": null, "e": 28970, "s": 28784, "text": "Whiteboard based groupware paradigm: The information is available on the public board in the group whoever in the group can access it. Anyone can read or write data to a shared display " }, { "code": null, "e": 28982, "s": 28972, "text": "kalrap615" }, { "code": null, "e": 29001, "s": 28982, "text": "Distributed System" }, { "code": null, "e": 29025, "s": 29001, "text": "Technical Scripter 2019" }, { "code": null, "e": 29043, "s": 29025, "text": "Operating Systems" }, { "code": null, "e": 29062, "s": 29043, "text": "Technical Scripter" }, { "code": null, "e": 29080, "s": 29062, "text": "Operating Systems" }, { "code": null, "e": 29178, "s": 29080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29187, "s": 29178, "text": "Comments" }, { "code": null, "e": 29200, "s": 29187, "text": "Old Comments" }, { "code": null, "e": 29238, "s": 29200, "text": "Memory Management in Operating System" }, { "code": null, "e": 29293, "s": 29238, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 29358, "s": 29293, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 29407, "s": 29358, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 29451, "s": 29407, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 29492, "s": 29451, "text": "States of a Process in Operating Systems" }, { "code": null, "e": 29516, "s": 29492, "text": "File Allocation Methods" }, { "code": null, "e": 29560, "s": 29516, "text": "Dining Philosopher Problem Using Semaphores" }, { "code": null, "e": 29606, "s": 29560, "text": "Process Table and Process Control Block (PCB)" } ]
AbstractMap.SimpleEntry getKey() Method in Java with Examples - GeeksforGeeks
27 Jun, 2019 AbstractMap.SimpleEntry<K, V> is used to maintain a key and a value entry. The value can be changed using the setValue method. This class facilitates the process of building custom map implementations.getKey() method of AbstractMap.SimpleEntry<K, V> returns the key corresponding to this entry. Syntax: public K getKey() Parameters: This method accepts nothing. Return value: This method returns the key corresponding to this entry. Below programs illustrate getKey() method:Program 1: // Java program to demonstrate// AbstractMap.SimpleEntry.getKey() method import java.util.*;import java.util.AbstractMap.SimpleEntry; public class GFG { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { // create a ArrayList of Map ArrayList<AbstractMap .SimpleEntry<Integer, Integer> > arrayList = new ArrayList<AbstractMap .SimpleEntry<Integer, Integer> >(); // add values arrayList.add(new AbstractMap.SimpleEntry(0, 123)); arrayList.add(new AbstractMap.SimpleEntry(1, 130)); arrayList.add(new AbstractMap.SimpleEntry(2, 994)); // print keys for (int i = 0; i < arrayList.size(); i++) { // get map from list AbstractMap.SimpleEntry<Integer, Integer> map = arrayList.get(i); // get key from map.getKey(); int key = map.getKey(); System.out.println("Key " + key); } }} Key 0 Key 1 Key 2 Program 2: // Java program to demonstrate// AbstractMap.SimpleEntry.get() method import java.util.*; public class GFG { @SuppressWarnings({ "unchecked", "rawtypes" }) public static void main(String[] args) { // create a ArrayList of Map ArrayList<AbstractMap .SimpleEntry<String, String> > arrayList = new ArrayList<AbstractMap .SimpleEntry<String, String> >(); // add values arrayList.add(new AbstractMap .SimpleEntry(" 001AB ", " Emp 1")); arrayList.add(new AbstractMap .SimpleEntry(" 011AC ", " Emp 2")); arrayList.add(new AbstractMap .SimpleEntry(" 111AD ", " Emp 3")); arrayList.add(new AbstractMap .SimpleEntry(" 101BE ", " Emp 4")); arrayList.add(new AbstractMap .SimpleEntry(" 110CE ", " Emp 5")); // print keys for (int i = 0; i < arrayList.size(); i++) { // get map from list AbstractMap.SimpleEntry<String, String> map = arrayList.get(i); // get key from map.getKey() String key = map.getKey(); System.out.println("Key " + key); } }} Key 001AB Key 011AC Key 111AD Key 101BE Key 110CE References: https://docs.oracle.com/javase/10/docs/api/java/util/AbstractMap.SimpleEntry.html#getKey() Java - util package Java-AbstractMap-SimpleEntry Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Exceptions in Java Constructors in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 25347, "s": 25319, "text": "\n27 Jun, 2019" }, { "code": null, "e": 25642, "s": 25347, "text": "AbstractMap.SimpleEntry<K, V> is used to maintain a key and a value entry. The value can be changed using the setValue method. This class facilitates the process of building custom map implementations.getKey() method of AbstractMap.SimpleEntry<K, V> returns the key corresponding to this entry." }, { "code": null, "e": 25650, "s": 25642, "text": "Syntax:" }, { "code": null, "e": 25669, "s": 25650, "text": "public K getKey()\n" }, { "code": null, "e": 25710, "s": 25669, "text": "Parameters: This method accepts nothing." }, { "code": null, "e": 25781, "s": 25710, "text": "Return value: This method returns the key corresponding to this entry." }, { "code": null, "e": 25834, "s": 25781, "text": "Below programs illustrate getKey() method:Program 1:" }, { "code": "// Java program to demonstrate// AbstractMap.SimpleEntry.getKey() method import java.util.*;import java.util.AbstractMap.SimpleEntry; public class GFG { @SuppressWarnings({ \"unchecked\", \"rawtypes\" }) public static void main(String[] args) { // create a ArrayList of Map ArrayList<AbstractMap .SimpleEntry<Integer, Integer> > arrayList = new ArrayList<AbstractMap .SimpleEntry<Integer, Integer> >(); // add values arrayList.add(new AbstractMap.SimpleEntry(0, 123)); arrayList.add(new AbstractMap.SimpleEntry(1, 130)); arrayList.add(new AbstractMap.SimpleEntry(2, 994)); // print keys for (int i = 0; i < arrayList.size(); i++) { // get map from list AbstractMap.SimpleEntry<Integer, Integer> map = arrayList.get(i); // get key from map.getKey(); int key = map.getKey(); System.out.println(\"Key \" + key); } }}", "e": 26892, "s": 25834, "text": null }, { "code": null, "e": 26911, "s": 26892, "text": "Key 0\nKey 1\nKey 2\n" }, { "code": null, "e": 26922, "s": 26911, "text": "Program 2:" }, { "code": "// Java program to demonstrate// AbstractMap.SimpleEntry.get() method import java.util.*; public class GFG { @SuppressWarnings({ \"unchecked\", \"rawtypes\" }) public static void main(String[] args) { // create a ArrayList of Map ArrayList<AbstractMap .SimpleEntry<String, String> > arrayList = new ArrayList<AbstractMap .SimpleEntry<String, String> >(); // add values arrayList.add(new AbstractMap .SimpleEntry(\" 001AB \", \" Emp 1\")); arrayList.add(new AbstractMap .SimpleEntry(\" 011AC \", \" Emp 2\")); arrayList.add(new AbstractMap .SimpleEntry(\" 111AD \", \" Emp 3\")); arrayList.add(new AbstractMap .SimpleEntry(\" 101BE \", \" Emp 4\")); arrayList.add(new AbstractMap .SimpleEntry(\" 110CE \", \" Emp 5\")); // print keys for (int i = 0; i < arrayList.size(); i++) { // get map from list AbstractMap.SimpleEntry<String, String> map = arrayList.get(i); // get key from map.getKey() String key = map.getKey(); System.out.println(\"Key \" + key); } }}", "e": 28245, "s": 26922, "text": null }, { "code": null, "e": 28305, "s": 28245, "text": "Key 001AB \nKey 011AC \nKey 111AD \nKey 101BE \nKey 110CE\n" }, { "code": null, "e": 28408, "s": 28305, "text": "References: https://docs.oracle.com/javase/10/docs/api/java/util/AbstractMap.SimpleEntry.html#getKey()" }, { "code": null, "e": 28428, "s": 28408, "text": "Java - util package" }, { "code": null, "e": 28457, "s": 28428, "text": "Java-AbstractMap-SimpleEntry" }, { "code": null, "e": 28472, "s": 28457, "text": "Java-Functions" }, { "code": null, "e": 28477, "s": 28472, "text": "Java" }, { "code": null, "e": 28482, "s": 28477, "text": "Java" }, { "code": null, "e": 28580, "s": 28482, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28595, "s": 28580, "text": "Stream In Java" }, { "code": null, "e": 28614, "s": 28595, "text": "Exceptions in Java" }, { "code": null, "e": 28635, "s": 28614, "text": "Constructors in Java" }, { "code": null, "e": 28665, "s": 28635, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28711, "s": 28665, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28728, "s": 28711, "text": "Generics in Java" }, { "code": null, "e": 28749, "s": 28728, "text": "Introduction to Java" }, { "code": null, "e": 28792, "s": 28749, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28814, "s": 28792, "text": "PriorityQueue in Java" } ]
How to Create Custom Shapes of Data Points in GraphView in Android?
23 May, 2021 If you are looking for a view to represent some statistical data or looking for a UI for displaying a graph in your app then in this article we will take a look at creating a line graph view and showing custom shape to the data points in our Android App. We will be building a simple Line Graph View in our Android app and we will be displaying some sample data with custom shapes in our application. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘com.jjoe64:graphview:4.2.2’ Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.jjoe64.graphview.GraphView android:id="@+id/graphview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.jjoe64.graphview.GraphView;import com.jjoe64.graphview.series.DataPoint;import com.jjoe64.graphview.series.DataPointInterface;import com.jjoe64.graphview.series.PointsGraphSeries; public class MainActivity extends AppCompatActivity { GraphView graphView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); graphView = findViewById(R.id.graphview); // For creating Point Graph Series We use PointGraphSeries PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(getDataPoint()); graphView.addSeries(series); // we use this method to define the shape that // will be used for data points // series.setShape(PointsGraphSeries.Shape.TRIANGLE); // we use this method to define the size of the shape series.setSize(50); // we use this method to set the color series.setColor(Color.RED); // we use this method to define the custom shape, // we create our own shape series.setCustomShape(new PointsGraphSeries.CustomShape() { @Override public void draw(Canvas canvas, Paint paint, float x, float y, DataPointInterface dataPoint) { paint.setStrokeWidth(5); // we are initialising the shape structure of dat points canvas.drawLine(x - 20, y, x, y - 20, paint); canvas.drawLine(x, y - 20, x + 20, y, paint); canvas.drawLine(x + 20, y, x, y + 20, paint); canvas.drawLine(x - 20, y, x, y + 20, paint); } }); } // initialising the data points private DataPoint[] getDataPoint() { DataPoint[] dp = new DataPoint[]{ new DataPoint(0, 1), new DataPoint(2, 1), new DataPoint(3, 5), new DataPoint(6, 2), new DataPoint(7, 8), }; return dp; }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2021" }, { "code": null, "e": 285, "s": 28, "text": "If you are looking for a view to represent some statistical data or looking for a UI for displaying a graph in your app then in this article we will take a look at creating a line graph view and showing custom shape to the data points in our Android App. " }, { "code": null, "e": 506, "s": 285, "text": "We will be building a simple Line Graph View in our Android app and we will be displaying some sample data with custom shapes in our application. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 535, "s": 506, "text": "Step 1: Create a New Project" }, { "code": null, "e": 697, "s": 535, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 720, "s": 697, "text": "Step 2: Add dependency" }, { "code": null, "e": 839, "s": 720, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. " }, { "code": null, "e": 883, "s": 839, "text": "implementation ‘com.jjoe64:graphview:4.2.2’" }, { "code": null, "e": 931, "s": 883, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 1074, "s": 931, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 1078, "s": 1074, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <com.jjoe64.graphview.GraphView android:id=\"@+id/graphview\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>", "e": 1543, "s": 1078, "text": null }, { "code": null, "e": 1591, "s": 1543, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 1781, "s": 1591, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 1786, "s": 1781, "text": "Java" }, { "code": "import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.jjoe64.graphview.GraphView;import com.jjoe64.graphview.series.DataPoint;import com.jjoe64.graphview.series.DataPointInterface;import com.jjoe64.graphview.series.PointsGraphSeries; public class MainActivity extends AppCompatActivity { GraphView graphView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); graphView = findViewById(R.id.graphview); // For creating Point Graph Series We use PointGraphSeries PointsGraphSeries<DataPoint> series = new PointsGraphSeries<>(getDataPoint()); graphView.addSeries(series); // we use this method to define the shape that // will be used for data points // series.setShape(PointsGraphSeries.Shape.TRIANGLE); // we use this method to define the size of the shape series.setSize(50); // we use this method to set the color series.setColor(Color.RED); // we use this method to define the custom shape, // we create our own shape series.setCustomShape(new PointsGraphSeries.CustomShape() { @Override public void draw(Canvas canvas, Paint paint, float x, float y, DataPointInterface dataPoint) { paint.setStrokeWidth(5); // we are initialising the shape structure of dat points canvas.drawLine(x - 20, y, x, y - 20, paint); canvas.drawLine(x, y - 20, x + 20, y, paint); canvas.drawLine(x + 20, y, x, y + 20, paint); canvas.drawLine(x - 20, y, x, y + 20, paint); } }); } // initialising the data points private DataPoint[] getDataPoint() { DataPoint[] dp = new DataPoint[]{ new DataPoint(0, 1), new DataPoint(2, 1), new DataPoint(3, 5), new DataPoint(6, 2), new DataPoint(7, 8), }; return dp; }}", "e": 3987, "s": 1786, "text": null }, { "code": null, "e": 3995, "s": 3987, "text": "Output:" }, { "code": null, "e": 4003, "s": 3995, "text": "Android" }, { "code": null, "e": 4008, "s": 4003, "text": "Java" }, { "code": null, "e": 4013, "s": 4008, "text": "Java" }, { "code": null, "e": 4021, "s": 4013, "text": "Android" } ]
Python Program to find whether a no is power of two
06 Jan, 2022 Given a positive integer, write a function to find if it is a power of two or not.Examples : Input : n = 4 Output : Yes 22 = 4 Input : n = 7 Output : No Input : n = 32 Output : Yes 25 = 32 1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. Python3 # Python3 Program to find# whether a no is# power of twoimport math # Function to check# Log base 2def Log2(x): return (math.log10(x) / math.log10(2)); # Function to check# if x is power of 2def isPowerOfTwo(n): return (math.ceil(Log2(n)) == math.floor(Log2(n))); # Driver Codeif(isPowerOfTwo(31)): print("Yes");else: print("No"); if(isPowerOfTwo(64)): print("Yes");else: print("No"); # This code is contributed# by mits No Yes Time Complexity: O(log2n) Auxiliary Space: O(1) 2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. Python3 # Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo(n): if (n == 0): return False while (n != 1): if (n % 2 != 0): return False n = n // 2 return True # Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No')if(isPowerOfTwo(64)): print('Yes')else: print('No') # This code is contributed by Danish Raza No Yes 3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. Python3 # Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo (x): # First x in the below expression # is for the case when x is 0 return (x and (not(x & (x - 1))) ) # Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No') if(isPowerOfTwo(64)): print('Yes')else: print('No') # This code is contributed by Danish Raza No Yes Please refer complete article on Program to find whether a no is power of two for more details! souravmahato348 amartyaghoshgfg Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jan, 2022" }, { "code": null, "e": 147, "s": 52, "text": "Given a positive integer, write a function to find if it is a power of two or not.Examples : " }, { "code": null, "e": 245, "s": 147, "text": "Input : n = 4\nOutput : Yes\n22 = 4\n\nInput : n = 7\nOutput : No\n\nInput : n = 32\nOutput : Yes\n25 = 32" }, { "code": null, "e": 378, "s": 245, "text": "1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2. " }, { "code": null, "e": 386, "s": 378, "text": "Python3" }, { "code": "# Python3 Program to find# whether a no is# power of twoimport math # Function to check# Log base 2def Log2(x): return (math.log10(x) / math.log10(2)); # Function to check# if x is power of 2def isPowerOfTwo(n): return (math.ceil(Log2(n)) == math.floor(Log2(n))); # Driver Codeif(isPowerOfTwo(31)): print(\"Yes\");else: print(\"No\"); if(isPowerOfTwo(64)): print(\"Yes\");else: print(\"No\"); # This code is contributed# by mits", "e": 840, "s": 386, "text": null }, { "code": null, "e": 847, "s": 840, "text": "No\nYes" }, { "code": null, "e": 875, "s": 849, "text": "Time Complexity: O(log2n)" }, { "code": null, "e": 897, "s": 875, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1111, "s": 897, "text": "2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2. " }, { "code": null, "e": 1119, "s": 1111, "text": "Python3" }, { "code": "# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo(n): if (n == 0): return False while (n != 1): if (n % 2 != 0): return False n = n // 2 return True # Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No')if(isPowerOfTwo(64)): print('Yes')else: print('No') # This code is contributed by Danish Raza", "e": 1573, "s": 1119, "text": null }, { "code": null, "e": 1580, "s": 1573, "text": "No\nYes" }, { "code": null, "e": 2415, "s": 1582, "text": "3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Below is the implementation of this method. " }, { "code": null, "e": 2423, "s": 2415, "text": "Python3" }, { "code": "# Python program to check if given# number is power of 2 or not # Function to check if x is power of 2def isPowerOfTwo (x): # First x in the below expression # is for the case when x is 0 return (x and (not(x & (x - 1))) ) # Driver codeif(isPowerOfTwo(31)): print('Yes')else: print('No') if(isPowerOfTwo(64)): print('Yes')else: print('No') # This code is contributed by Danish Raza ", "e": 2838, "s": 2423, "text": null }, { "code": null, "e": 2845, "s": 2838, "text": "No\nYes" }, { "code": null, "e": 2944, "s": 2847, "text": "Please refer complete article on Program to find whether a no is power of two for more details! " }, { "code": null, "e": 2960, "s": 2944, "text": "souravmahato348" }, { "code": null, "e": 2976, "s": 2960, "text": "amartyaghoshgfg" }, { "code": null, "e": 2992, "s": 2976, "text": "Python Programs" } ]
Ruby | Array sort() function
06 Dec, 2019 Array#sort() : sort() is a Array class method which returns a new array created by sorting self Syntax: Array.sort() Parameter: Array Return: a new array created by sorting self Example #1 : # Ruby code for sort() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", "efg", "geeks"] # declaring arrayb = ["cow", "coal", "dog"] arr = [a, b, c] # sort method exampleputs "sort() method form : #{arr.sort()}\n\n" Output : sort() method form : [["abc", "nil", "dog"], ["cat", "efg", "geeks"], ["cow", "coal", "dog"]] Example #2 : # Ruby code for sort() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", "efg", "geeks"] # declaring arrayb = ["cow", "coal", "dog"] # sort method exampleputs "sort() method form : #{a.sort()}\n\n" puts "sort() method form : #{b.sort()}\n\n" puts "sort() method form : #{c.sort()}\n\n" Output : sort() method form : ["abc", "dog", "nil"] sort() method form : ["coal", "cow", "dog"] sort() method form : ["cat", "efg", "geeks"] Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Enumerator each_with_index function Ruby | unless Statement and unless Modifier Ruby on Rails Introduction Ruby | String concat Method Ruby | Array class find_index() operation Ruby For Beginners Ruby | Array shift() function Ruby | Types of Variables
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2019" }, { "code": null, "e": 124, "s": 28, "text": "Array#sort() : sort() is a Array class method which returns a new array created by sorting self" }, { "code": null, "e": 145, "s": 124, "text": "Syntax: Array.sort()" }, { "code": null, "e": 162, "s": 145, "text": "Parameter: Array" }, { "code": null, "e": 206, "s": 162, "text": "Return: a new array created by sorting self" }, { "code": null, "e": 219, "s": 206, "text": "Example #1 :" }, { "code": "# Ruby code for sort() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", \"efg\", \"geeks\"] # declaring arrayb = [\"cow\", \"coal\", \"dog\"] arr = [a, b, c] # sort method exampleputs \"sort() method form : #{arr.sort()}\\n\\n\"", "e": 469, "s": 219, "text": null }, { "code": null, "e": 478, "s": 469, "text": "Output :" }, { "code": null, "e": 574, "s": 478, "text": "sort() method form : [[\"abc\", \"nil\", \"dog\"], [\"cat\", \"efg\", \"geeks\"], [\"cow\", \"coal\", \"dog\"]]\n\n" }, { "code": null, "e": 587, "s": 574, "text": "Example #2 :" }, { "code": "# Ruby code for sort() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", \"efg\", \"geeks\"] # declaring arrayb = [\"cow\", \"coal\", \"dog\"] # sort method exampleputs \"sort() method form : #{a.sort()}\\n\\n\" puts \"sort() method form : #{b.sort()}\\n\\n\" puts \"sort() method form : #{c.sort()}\\n\\n\"", "e": 910, "s": 587, "text": null }, { "code": null, "e": 919, "s": 910, "text": "Output :" }, { "code": null, "e": 1055, "s": 919, "text": "sort() method form : [\"abc\", \"dog\", \"nil\"]\n\nsort() method form : [\"coal\", \"cow\", \"dog\"]\n\nsort() method form : [\"cat\", \"efg\", \"geeks\"]\n\n" }, { "code": null, "e": 1072, "s": 1055, "text": "Ruby Array-class" }, { "code": null, "e": 1085, "s": 1072, "text": "Ruby-Methods" }, { "code": null, "e": 1090, "s": 1085, "text": "Ruby" }, { "code": null, "e": 1188, "s": 1090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1234, "s": 1188, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1277, "s": 1234, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1321, "s": 1277, "text": "Ruby | unless Statement and unless Modifier" }, { "code": null, "e": 1348, "s": 1321, "text": "Ruby on Rails Introduction" }, { "code": null, "e": 1376, "s": 1348, "text": "Ruby | String concat Method" }, { "code": null, "e": 1418, "s": 1376, "text": "Ruby | Array class find_index() operation" }, { "code": null, "e": 1437, "s": 1418, "text": "Ruby For Beginners" }, { "code": null, "e": 1467, "s": 1437, "text": "Ruby | Array shift() function" } ]
PHPUnit assertIsArray() Function
07 Aug, 2020 The assertIsArray() function is a builtin function in PHPUnit and is used to assert whether the given variable is an array or not. This assertion will return true in the case if the given variable is array else returns false. In case of true the asserted test case got passed else test case got failed. Syntax: assertIsArray($actual[, $message = '']) Parameters: This function accepts two parameters as mentioned above and described below: $variable: This parameter is of any type of variable which represents the actual data. $message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message. Below example illustrate the assertIsArray() function in PHPUnit: Example 1: PHP <?php use PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testNegativeForassertIsArray() { $variable = ("apple/banana"); // Assert function to test whether assert // variable is array or not $this->assertIsArray( $variable, "assert variable is array or not" ); } } ?> Output: PHPUnit 8.5.8 by Sebastian Bergmann and contributors. F 1 / 1 (100%) Time: 90 ms, Memory: 10.00 MB There was 1 failure: 1) GeeksPhpunitTestCase::testNegativeForassertIsArray assert variable is array or not Failed asserting that 'apple/banana' is of type "array". /home/lovely/Documents/php/test.php:15 FAILURES! Tests: 1, Assertions: 1, Failures: 1. Example 2: PHP <?php use PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testPositiveForassertIsArray() { $variable = array ("apple/banana"); // Assert function to test whether assert // variable is array or not $this->assertIsArray( $variable, "assert variable is array or not" ); } } ?> Output: PHPUnit 8.5.8 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 88 ms, Memory: 10.00 MB OK (1 test, 1 assertion) Reference: https://phpunit.readthedocs.io/en/9.2/assertions.html#assertisiterable PHP-PHPUnit PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Aug, 2020" }, { "code": null, "e": 331, "s": 28, "text": "The assertIsArray() function is a builtin function in PHPUnit and is used to assert whether the given variable is an array or not. This assertion will return true in the case if the given variable is array else returns false. In case of true the asserted test case got passed else test case got failed." }, { "code": null, "e": 339, "s": 331, "text": "Syntax:" }, { "code": null, "e": 381, "s": 339, "text": "assertIsArray($actual[, $message = ''])\n\n" }, { "code": null, "e": 470, "s": 381, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 557, "s": 470, "text": "$variable: This parameter is of any type of variable which represents the actual data." }, { "code": null, "e": 689, "s": 557, "text": "$message: This parameter takes a string value. When the test case got failed this string message got displayed as an error message." }, { "code": null, "e": 755, "s": 689, "text": "Below example illustrate the assertIsArray() function in PHPUnit:" }, { "code": null, "e": 766, "s": 755, "text": "Example 1:" }, { "code": null, "e": 770, "s": 766, "text": "PHP" }, { "code": "<?php use PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testNegativeForassertIsArray() { $variable = (\"apple/banana\"); // Assert function to test whether assert // variable is array or not $this->assertIsArray( $variable, \"assert variable is array or not\" ); } } ?> ", "e": 1177, "s": 770, "text": null }, { "code": null, "e": 1185, "s": 1177, "text": "Output:" }, { "code": null, "e": 1591, "s": 1185, "text": "PHPUnit 8.5.8 by Sebastian Bergmann and contributors.\n\nF 1 / 1 (100%)\n\nTime: 90 ms, Memory: 10.00 MB\n\nThere was 1 failure:\n\n1) GeeksPhpunitTestCase::testNegativeForassertIsArray\nassert variable is array or not\nFailed asserting that 'apple/banana' is of type \"array\".\n\n/home/lovely/Documents/php/test.php:15\n\nFAILURES!\nTests: 1, Assertions: 1, Failures: 1.\n" }, { "code": null, "e": 1602, "s": 1591, "text": "Example 2:" }, { "code": null, "e": 1606, "s": 1602, "text": "PHP" }, { "code": "<?php use PHPUnit\\Framework\\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testPositiveForassertIsArray() { $variable = array (\"apple/banana\"); // Assert function to test whether assert // variable is array or not $this->assertIsArray( $variable, \"assert variable is array or not\" ); } } ?> ", "e": 2018, "s": 1606, "text": null }, { "code": null, "e": 2026, "s": 2018, "text": "Output:" }, { "code": null, "e": 2203, "s": 2026, "text": "PHPUnit 8.5.8 by Sebastian Bergmann and contributors.\n\n. 1 / 1 (100%)\n\nTime: 88 ms, Memory: 10.00 MB\n\nOK (1 test, 1 assertion)\n" }, { "code": null, "e": 2285, "s": 2203, "text": "Reference: https://phpunit.readthedocs.io/en/9.2/assertions.html#assertisiterable" }, { "code": null, "e": 2297, "s": 2285, "text": "PHP-PHPUnit" }, { "code": null, "e": 2301, "s": 2297, "text": "PHP" }, { "code": null, "e": 2318, "s": 2301, "text": "Web Technologies" }, { "code": null, "e": 2322, "s": 2318, "text": "PHP" } ]
Get the Number of Levels of a Factor in R Programming – nlevels() Function
16 Jun, 2020 nlevels() function in R Language is used to get the number of levels of a factor. Syntax: nlevels(x) Parameters:x: Factor Object Example 1: # R program to get the number# of levels of a factor # Creating a factorx <- gl(3, 2)x # Calling nlevels() function# to get the number of levelsnlevels(x) Output: [1] 1 1 2 2 3 3 Levels: 1 2 3 [1] 3 Example 2: # R program to get the number# of levels of a factor # Creating a factorgender <- factor(c("female", "male", "male", "female")); gender # Calling nlevels() function# to get the number of levelsnlevels(gender) Output: [1] female male male female Levels: female male [1] 2 R Factor-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2020" }, { "code": null, "e": 110, "s": 28, "text": "nlevels() function in R Language is used to get the number of levels of a factor." }, { "code": null, "e": 129, "s": 110, "text": "Syntax: nlevels(x)" }, { "code": null, "e": 157, "s": 129, "text": "Parameters:x: Factor Object" }, { "code": null, "e": 168, "s": 157, "text": "Example 1:" }, { "code": "# R program to get the number# of levels of a factor # Creating a factorx <- gl(3, 2)x # Calling nlevels() function# to get the number of levelsnlevels(x)", "e": 325, "s": 168, "text": null }, { "code": null, "e": 333, "s": 325, "text": "Output:" }, { "code": null, "e": 370, "s": 333, "text": "[1] 1 1 2 2 3 3\nLevels: 1 2 3\n[1] 3\n" }, { "code": null, "e": 381, "s": 370, "text": "Example 2:" }, { "code": "# R program to get the number# of levels of a factor # Creating a factorgender <- factor(c(\"female\", \"male\", \"male\", \"female\")); gender # Calling nlevels() function# to get the number of levelsnlevels(gender)", "e": 592, "s": 381, "text": null }, { "code": null, "e": 600, "s": 592, "text": "Output:" }, { "code": null, "e": 659, "s": 600, "text": "[1] female male male female\nLevels: female male\n[1] 2\n" }, { "code": null, "e": 677, "s": 659, "text": "R Factor-Function" }, { "code": null, "e": 688, "s": 677, "text": "R Language" } ]
System Design – URL Shortening Service
14 Feb, 2021 Designing a URL shortener service is one of the frequently asked common questions of system design round in interviews. You will have to tell your approach to design this service within a limited timeframe (45 minutes or less). A lot of candidates get afraid of this round more than the coding round because they don’t get the idea that what topics and tradeoffs they should cover within this limited timeframe. Firstly, remember that the system design round is extremely open-ended and there’s no such thing as a standard answer. Even for the same question, you’ll have a totally different discussion with different interviewers. In this blog, we will discuss how to design a URL shortener service but before we go further we want you to read the article “How to Crack System Design Round in Interviews?”. It will give you an idea that what this round looks like, what you are expected to do in this round and what mistakes you should avoid in front of the interviewer. URL shortening services like bit.ly or TinyURL are very popular to generate shorter aliases for long URLs. You need to design this kind of web service where if a user gives a long URL then the service returns a short URL and if the user gives a short URL then it returns the original long URL. For example, shortening the given URL through TinyURL: https://www.geeksforgeeks.org/get-your-dream-job-with-amazon-sde-test-series/?ref=leftbar-rightbar We get the result given below https://tinyurl.com/y7vg2xjl A lot of candidates might be thinking that designing this service is not difficult. When a user gives a long URL convert it into a short URL and updates the database and when the user hits the short URL then search the short URL in the database, get that long URL, and redirect the user to the original URL. Is it really simple? Absolutely not if we think about the scalability of this service. When you’re asked this question in your interviews don’t jump into the technical details immediately. Most of the candidates make mistakes here and immediately they start listing out some bunch of tools, databases, and frameworks. In this kind of question, the interviewer wants a high-level design idea where you can give the solution for the scalability and durability of the service. Let’s start by talking about the requirement first... Before you jump into the solution always clarify all the assumptions you’re making at the beginning of the interview. Ask questions to identify the scope of the system. This will clear the initial doubt, and you will get to know what are the specific detail interviewer wants to consider in this service. Given a long URL, the service should generate a shorter and unique alias of it. When the user hits a short link, the service should redirect to the original link. Links will expire after a standard default time span. The system should be highly available. This is really important to consider because if the service goes down, all the URL redirection will start failing. URL redirection should happen in real-time with minimal latency. Shortened links should not be predictable. Let’s start by making some assumptions about the traffic (for scalability) and the length of the URL. Let’s assume our service has 30M new URL shortenings per month. Let’s assume we store every URL shortening request (and associated shortened link) for 5 years. For this period the service will generate about 1.8 B records. 30 million * 5 years * 12 months = 1.8B Let’s consider we are using 7 characters to generate a short URL. These characters are a combination of 62 characters [A-Z, a-z, 0-9] something like http://ad.com/abXdef2. Discuss the data capacity model to estimate the storage of the system. We need to understand how much data we might have to insert in our system. Think about the different columns or attributes that will be stored in our database and calculate the storage of data for five years. Let’s make the assumption given below for different attributes... Consider average long URL size of 2KB ie for 2048 characters. Short URL size: 17 Bytes for 17 character created_at- 7 bytes expiration_length_in_minutes -7 bytes The above calculation will give a total of 2.031KB per shortened URL entry in the database. If we calculate the total storage then for 30 M active users total size = 30000000 * 2.031 = 60780000 KB = 60.78 GB per month. In a Year of 0.7284 TB and in 5 years 3.642 TB of data. We need to think about the reads and writes that will happen on our system for this amount of data. This will decide what kind of database (RDBMS or NoSQL) we need to use. To convert a long URL into a unique short URL we can use some hashing techniques like Base62 or MD5. We will discuss both approaches. Base62 Encoding: Base62 encoder allows us to use the combination of characters and numbers which contains A-Z, a-z, 0–9 total( 26 + 26 + 10 = 62). So for 7 characters short URL, we can serve 62^7 ~= 3500 billion URLs which is quite enough in comparison to base10 (base10 only contains numbers 0-9 so you will get only 10M combinations). If we use base62 making the assumption that the service is generating 1000 tiny URLs/sec then it will take 110 years to exhaust this 3500 billion combination. We can generate a random number for the given long URL and convert it to base62 and use the hash as a short URL id. Python3 def to_base_62(deci): s = '012345689abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' hash_str = '' while deci > 0: hash_str= s[deci % 62] + hash_str deci /= 62 return hash_str print to_base_62(999) MD5 Encoding: MD5 also gives base62 output but the MD5 hash gives a lengthy output which is more than 7 characters. MD5 hash generates 128-bit long output so out of 128 bit we will take 43 bit to generate a tiny URL of 7 characters. MD5 can create a lot of collisions. For two or many different long URL inputs we may get the same unique id for short URL and that could cause data corruption. So we need to perform some checks to ensure that this unique id doesn’t exist in the database already. We can use RDBMS which uses ACID properties but you will be facing the scalability issue with relational databases. Now if you think you can use sharding and resolve the scalability issue in RDBMS then that will increase the complexity of the system. There are 30M active users so there will be conversions and a lot of Short URL resolution and redirections. Read and write will be heavy for these 30M users so scaling the RDBMS using shard will increase the complexity of the design when we want to have our system in a distributed manner. You may have to use consistent hashing to balance the traffics and DB queries in the case of RDBMS and which is a complicated process. So to handle this amount of huge traffic on our system relational databases are not fit and also it won’t be a good decision to scale the RDBMS. Now let’s talk about NoSQL! The only problem with using the NoSQL database is its eventual consistency. We write something and it takes some time to replicate to a different node but our system needs high availability and NoSQL is fits this requirement. NoSQL can easily handle the 30M of active users and it is easy to scale. We just need to keep adding the nodes when we want to expand the storage. Let’s discuss the mapping of a long URL into a short URL in our database. Assume we generate the Tiny URL using base62 encoding then we need to perform the steps give below... The tiny URL should be unique so firstly check the existence of this tiny URL in the database (doing get(tiny) on DB). If it’s already present there for some other long URL then generate a new short URL. If the short URL isn’t present in DB then put longURL and TinyURL in DB (put(TinyURL, longURL)). This technique works with one server very well but if there will be multiple servers then this technique will create a race condition. When multiple servers will work together, there will be a possibility that they all can generate the same unique id or same tiny URL for different long URLs, and even after checking the database, they will be allowed to insert the same tiny URLs simultaneously (which is the same for different long URLs) in the database and this may end up corrupting the data. We can use putIfAbsent(TinyURL, long URL) or INSERT-IF-NOT-EXIST condition while inserting the tiny URL but this requires support from DB which is available in RDBMS but not in NoSQL. Data is eventual consistent in NoSQL so putIfAbsent feature support might not be available in the NoSQL database. Encode the long URL using the MD5 approach and take only the first 7 chars to generate TinyURL. The first 7 characters could be the same for different long URLs so check the DB (as we have discussed in technique 1) to verify that TinyURL is not used already Advantages: This approach saves some space in the database but how? If two users want to generate a tiny URL for the same long URL then the first technique will generate two random numbers and it requires two rows in the database but in the second technique, both the longer URL will have the same MD5 so it will have the same first 43 bits which means we will get some deduping and we will end up with saving some space since we only need to store one row instead of two rows in the database. MD5 saves some space in the database for the same URLs but for two long different URLs again we will face the same problem as we have discussed in technique 1. We can use putIfAbsent but NoSQL doesn’t support this feature. So let’s move to the third technique to solve this problem. Using a counter is a good decision for a scalable solution because counters always get incremented so we can get a new value for every new request. Single server approach: A single host or server (say database) will be responsible for maintaining the counter. When the worker host receives a request it talks to the counter host, which returns a unique number and increments the counter. When the next request comes the counter host again returns the unique number and this goes on. Every worker host gets a unique number which is used to generate TinyURL. Problem: If the counter host goes down for some time then it will create a problem, also if the number of requests will be high then the counter host might not be able to handle the load. So challenges are a Single point of failure and a single point of bottleneck. And what if there are multiple servers? You can’t maintain a single counter and returns the output to all the servers. To solve this problem we can use multiple internal counters for multiple servers which use different counter range. For example server 1 ranges from 1 to 1M, server 2 ranges from 1M to 10M, and so on. But again we will face a problem i.e. if one of the counters goes down then for another server it will be difficult to get the range of the failure counter and maintain it again. Also if one counter reaches its maximum limit then resetting the counter will be difficult because there is no single host available for coordination among all these multiple servers. The architecture will be messed up since we don’t know which server is master or which one is a slave and which one is responsible for coordination and synchronization. Solution: To solve this problem we can use a distributed service Zookeeper to manage all these tedious task and to solve the various challenges of a distributed system like a race condition, deadlock, or particle failure of data. Zookeeper is basically a distributed coordination service that manages a large set of hosts. It keeps track of all the things such as the naming of the servers, active servers, dead servers, configuration information of all the hosts. It provides coordination and maintains the synchronization between the multiple servers. Let’s discuss how to maintain a counter for distributed hosts using Zookeeper. From 3.5 trillion combinations take 1st billion combinations. In Zookeeper maintain the range and divide the 1st billion into 1000 ranges of 1 million each i.e. range 1->(1 – 1,000,000), range 2->(1,000,001 – 2,000,000).... range 1000->(999,000,001 – 1,000,000,000) When servers will be added these servers will ask for the unused range from Zookeepers. Suppose the W1 server is assigned range 1, now W1 will generate the tiny URL incrementing the counter and using the encoding technique. Every time it will be a unique number so there is no possibility of collision and also there is no need to keep checking the DB to ensure that if the URL already exists or not. We can directly insert the mapping of a long URL and short URL into the DB. In the worst case, if one of the servers goes down then we will only lose a million combinations in Zookeeper (which will be unused and we can’t reuse it as well) but since we have 3.5 trillion combinations we should not worry about losing this combination. If one of the servers will reach its maximum range or limit then again it can take a new fresh range from Zookeeper. The Addition of a new server is also easy. Zookeeper will assign an unused counter range to this new server. We will take the 2nd billion when the 1st billion is exhausted to continue the process. System-Design GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Feb, 2021" }, { "code": null, "e": 684, "s": 52, "text": "Designing a URL shortener service is one of the frequently asked common questions of system design round in interviews. You will have to tell your approach to design this service within a limited timeframe (45 minutes or less). A lot of candidates get afraid of this round more than the coding round because they don’t get the idea that what topics and tradeoffs they should cover within this limited timeframe. Firstly, remember that the system design round is extremely open-ended and there’s no such thing as a standard answer. Even for the same question, you’ll have a totally different discussion with different interviewers. " }, { "code": null, "e": 1025, "s": 684, "text": "In this blog, we will discuss how to design a URL shortener service but before we go further we want you to read the article “How to Crack System Design Round in Interviews?”. It will give you an idea that what this round looks like, what you are expected to do in this round and what mistakes you should avoid in front of the interviewer. " }, { "code": null, "e": 1375, "s": 1025, "text": "URL shortening services like bit.ly or TinyURL are very popular to generate shorter aliases for long URLs. You need to design this kind of web service where if a user gives a long URL then the service returns a short URL and if the user gives a short URL then it returns the original long URL. For example, shortening the given URL through TinyURL: " }, { "code": null, "e": 1474, "s": 1375, "text": "https://www.geeksforgeeks.org/get-your-dream-job-with-amazon-sde-test-series/?ref=leftbar-rightbar" }, { "code": null, "e": 1505, "s": 1474, "text": "We get the result given below " }, { "code": null, "e": 1534, "s": 1505, "text": "https://tinyurl.com/y7vg2xjl" }, { "code": null, "e": 2371, "s": 1534, "text": "A lot of candidates might be thinking that designing this service is not difficult. When a user gives a long URL convert it into a short URL and updates the database and when the user hits the short URL then search the short URL in the database, get that long URL, and redirect the user to the original URL. Is it really simple? Absolutely not if we think about the scalability of this service. When you’re asked this question in your interviews don’t jump into the technical details immediately. Most of the candidates make mistakes here and immediately they start listing out some bunch of tools, databases, and frameworks. In this kind of question, the interviewer wants a high-level design idea where you can give the solution for the scalability and durability of the service. Let’s start by talking about the requirement first... " }, { "code": null, "e": 2677, "s": 2371, "text": "Before you jump into the solution always clarify all the assumptions you’re making at the beginning of the interview. Ask questions to identify the scope of the system. This will clear the initial doubt, and you will get to know what are the specific detail interviewer wants to consider in this service. " }, { "code": null, "e": 2757, "s": 2677, "text": "Given a long URL, the service should generate a shorter and unique alias of it." }, { "code": null, "e": 2840, "s": 2757, "text": "When the user hits a short link, the service should redirect to the original link." }, { "code": null, "e": 2894, "s": 2840, "text": "Links will expire after a standard default time span." }, { "code": null, "e": 3048, "s": 2894, "text": "The system should be highly available. This is really important to consider because if the service goes down, all the URL redirection will start failing." }, { "code": null, "e": 3113, "s": 3048, "text": "URL redirection should happen in real-time with minimal latency." }, { "code": null, "e": 3156, "s": 3113, "text": "Shortened links should not be predictable." }, { "code": null, "e": 3259, "s": 3156, "text": "Let’s start by making some assumptions about the traffic (for scalability) and the length of the URL. " }, { "code": null, "e": 3483, "s": 3259, "text": "Let’s assume our service has 30M new URL shortenings per month. Let’s assume we store every URL shortening request (and associated shortened link) for 5 years. For this period the service will generate about 1.8 B records. " }, { "code": null, "e": 3523, "s": 3483, "text": "30 million * 5 years * 12 months = 1.8B" }, { "code": null, "e": 3695, "s": 3523, "text": "Let’s consider we are using 7 characters to generate a short URL. These characters are a combination of 62 characters [A-Z, a-z, 0-9] something like http://ad.com/abXdef2." }, { "code": null, "e": 4042, "s": 3695, "text": "Discuss the data capacity model to estimate the storage of the system. We need to understand how much data we might have to insert in our system. Think about the different columns or attributes that will be stored in our database and calculate the storage of data for five years. Let’s make the assumption given below for different attributes... " }, { "code": null, "e": 4104, "s": 4042, "text": "Consider average long URL size of 2KB ie for 2048 characters." }, { "code": null, "e": 4146, "s": 4104, "text": "Short URL size: 17 Bytes for 17 character" }, { "code": null, "e": 4166, "s": 4146, "text": "created_at- 7 bytes" }, { "code": null, "e": 4204, "s": 4166, "text": "expiration_length_in_minutes -7 bytes" }, { "code": null, "e": 4480, "s": 4204, "text": "The above calculation will give a total of 2.031KB per shortened URL entry in the database. If we calculate the total storage then for 30 M active users total size = 30000000 * 2.031 = 60780000 KB = 60.78 GB per month. In a Year of 0.7284 TB and in 5 years 3.642 TB of data. " }, { "code": null, "e": 4652, "s": 4480, "text": "We need to think about the reads and writes that will happen on our system for this amount of data. This will decide what kind of database (RDBMS or NoSQL) we need to use." }, { "code": null, "e": 5399, "s": 4652, "text": "To convert a long URL into a unique short URL we can use some hashing techniques like Base62 or MD5. We will discuss both approaches. Base62 Encoding: Base62 encoder allows us to use the combination of characters and numbers which contains A-Z, a-z, 0–9 total( 26 + 26 + 10 = 62). So for 7 characters short URL, we can serve 62^7 ~= 3500 billion URLs which is quite enough in comparison to base10 (base10 only contains numbers 0-9 so you will get only 10M combinations). If we use base62 making the assumption that the service is generating 1000 tiny URLs/sec then it will take 110 years to exhaust this 3500 billion combination. We can generate a random number for the given long URL and convert it to base62 and use the hash as a short URL id. " }, { "code": null, "e": 5407, "s": 5399, "text": "Python3" }, { "code": "def to_base_62(deci): s = '012345689abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' hash_str = '' while deci > 0: hash_str= s[deci % 62] + hash_str deci /= 62 return hash_str print to_base_62(999)", "e": 5635, "s": 5407, "text": null }, { "code": null, "e": 6132, "s": 5635, "text": "MD5 Encoding: MD5 also gives base62 output but the MD5 hash gives a lengthy output which is more than 7 characters. MD5 hash generates 128-bit long output so out of 128 bit we will take 43 bit to generate a tiny URL of 7 characters. MD5 can create a lot of collisions. For two or many different long URL inputs we may get the same unique id for short URL and that could cause data corruption. So we need to perform some checks to ensure that this unique id doesn’t exist in the database already. " }, { "code": null, "e": 6954, "s": 6132, "text": "We can use RDBMS which uses ACID properties but you will be facing the scalability issue with relational databases. Now if you think you can use sharding and resolve the scalability issue in RDBMS then that will increase the complexity of the system. There are 30M active users so there will be conversions and a lot of Short URL resolution and redirections. Read and write will be heavy for these 30M users so scaling the RDBMS using shard will increase the complexity of the design when we want to have our system in a distributed manner. You may have to use consistent hashing to balance the traffics and DB queries in the case of RDBMS and which is a complicated process. So to handle this amount of huge traffic on our system relational databases are not fit and also it won’t be a good decision to scale the RDBMS. " }, { "code": null, "e": 6982, "s": 6954, "text": "Now let’s talk about NoSQL!" }, { "code": null, "e": 7356, "s": 6982, "text": "The only problem with using the NoSQL database is its eventual consistency. We write something and it takes some time to replicate to a different node but our system needs high availability and NoSQL is fits this requirement. NoSQL can easily handle the 30M of active users and it is easy to scale. We just need to keep adding the nodes when we want to expand the storage. " }, { "code": null, "e": 7534, "s": 7356, "text": "Let’s discuss the mapping of a long URL into a short URL in our database. Assume we generate the Tiny URL using base62 encoding then we need to perform the steps give below... " }, { "code": null, "e": 7738, "s": 7534, "text": "The tiny URL should be unique so firstly check the existence of this tiny URL in the database (doing get(tiny) on DB). If it’s already present there for some other long URL then generate a new short URL." }, { "code": null, "e": 7835, "s": 7738, "text": "If the short URL isn’t present in DB then put longURL and TinyURL in DB (put(TinyURL, longURL))." }, { "code": null, "e": 8631, "s": 7835, "text": "This technique works with one server very well but if there will be multiple servers then this technique will create a race condition. When multiple servers will work together, there will be a possibility that they all can generate the same unique id or same tiny URL for different long URLs, and even after checking the database, they will be allowed to insert the same tiny URLs simultaneously (which is the same for different long URLs) in the database and this may end up corrupting the data. We can use putIfAbsent(TinyURL, long URL) or INSERT-IF-NOT-EXIST condition while inserting the tiny URL but this requires support from DB which is available in RDBMS but not in NoSQL. Data is eventual consistent in NoSQL so putIfAbsent feature support might not be available in the NoSQL database. " }, { "code": null, "e": 8727, "s": 8631, "text": "Encode the long URL using the MD5 approach and take only the first 7 chars to generate TinyURL." }, { "code": null, "e": 8889, "s": 8727, "text": "The first 7 characters could be the same for different long URLs so check the DB (as we have discussed in technique 1) to verify that TinyURL is not used already" }, { "code": null, "e": 9383, "s": 8889, "text": "Advantages: This approach saves some space in the database but how? If two users want to generate a tiny URL for the same long URL then the first technique will generate two random numbers and it requires two rows in the database but in the second technique, both the longer URL will have the same MD5 so it will have the same first 43 bits which means we will get some deduping and we will end up with saving some space since we only need to store one row instead of two rows in the database." }, { "code": null, "e": 9666, "s": 9383, "text": "MD5 saves some space in the database for the same URLs but for two long different URLs again we will face the same problem as we have discussed in technique 1. We can use putIfAbsent but NoSQL doesn’t support this feature. So let’s move to the third technique to solve this problem." }, { "code": null, "e": 9815, "s": 9666, "text": "Using a counter is a good decision for a scalable solution because counters always get incremented so we can get a new value for every new request. " }, { "code": null, "e": 9841, "s": 9815, "text": "Single server approach: " }, { "code": null, "e": 9929, "s": 9841, "text": "A single host or server (say database) will be responsible for maintaining the counter." }, { "code": null, "e": 10152, "s": 9929, "text": "When the worker host receives a request it talks to the counter host, which returns a unique number and increments the counter. When the next request comes the counter host again returns the unique number and this goes on." }, { "code": null, "e": 10226, "s": 10152, "text": "Every worker host gets a unique number which is used to generate TinyURL." }, { "code": null, "e": 10533, "s": 10226, "text": "Problem: If the counter host goes down for some time then it will create a problem, also if the number of requests will be high then the counter host might not be able to handle the load. So challenges are a Single point of failure and a single point of bottleneck. And what if there are multiple servers? " }, { "code": null, "e": 11346, "s": 10533, "text": "You can’t maintain a single counter and returns the output to all the servers. To solve this problem we can use multiple internal counters for multiple servers which use different counter range. For example server 1 ranges from 1 to 1M, server 2 ranges from 1M to 10M, and so on. But again we will face a problem i.e. if one of the counters goes down then for another server it will be difficult to get the range of the failure counter and maintain it again. Also if one counter reaches its maximum limit then resetting the counter will be difficult because there is no single host available for coordination among all these multiple servers. The architecture will be messed up since we don’t know which server is master or which one is a slave and which one is responsible for coordination and synchronization. " }, { "code": null, "e": 11981, "s": 11346, "text": "Solution: To solve this problem we can use a distributed service Zookeeper to manage all these tedious task and to solve the various challenges of a distributed system like a race condition, deadlock, or particle failure of data. Zookeeper is basically a distributed coordination service that manages a large set of hosts. It keeps track of all the things such as the naming of the servers, active servers, dead servers, configuration information of all the hosts. It provides coordination and maintains the synchronization between the multiple servers. Let’s discuss how to maintain a counter for distributed hosts using Zookeeper. " }, { "code": null, "e": 12043, "s": 11981, "text": "From 3.5 trillion combinations take 1st billion combinations." }, { "code": null, "e": 12247, "s": 12043, "text": "In Zookeeper maintain the range and divide the 1st billion into 1000 ranges of 1 million each i.e. range 1->(1 – 1,000,000), range 2->(1,000,001 – 2,000,000).... range 1000->(999,000,001 – 1,000,000,000)" }, { "code": null, "e": 12724, "s": 12247, "text": "When servers will be added these servers will ask for the unused range from Zookeepers. Suppose the W1 server is assigned range 1, now W1 will generate the tiny URL incrementing the counter and using the encoding technique. Every time it will be a unique number so there is no possibility of collision and also there is no need to keep checking the DB to ensure that if the URL already exists or not. We can directly insert the mapping of a long URL and short URL into the DB." }, { "code": null, "e": 12982, "s": 12724, "text": "In the worst case, if one of the servers goes down then we will only lose a million combinations in Zookeeper (which will be unused and we can’t reuse it as well) but since we have 3.5 trillion combinations we should not worry about losing this combination." }, { "code": null, "e": 13099, "s": 12982, "text": "If one of the servers will reach its maximum range or limit then again it can take a new fresh range from Zookeeper." }, { "code": null, "e": 13208, "s": 13099, "text": "The Addition of a new server is also easy. Zookeeper will assign an unused counter range to this new server." }, { "code": null, "e": 13296, "s": 13208, "text": "We will take the 2nd billion when the 1st billion is exhausted to continue the process." }, { "code": null, "e": 13310, "s": 13296, "text": "System-Design" }, { "code": null, "e": 13316, "s": 13310, "text": "GBlog" } ]
3 Tools to Monitor and Optimize your Linux System | by Khuyen Tran | Towards Data Science
If you are a Linux user, you might want to know some important information about your computer such as: System’s CPU usage, memory usage, and disk usage System information Disk usage of each folder or file and when was the last time that you used them. Memory and CPU consumption of the running processes Startup applications Knowing those pieces of information will enable you to optimize your system. In this article, I will show you 3 tools that allow you to do all of the things above and much more! htop is an interactive process viewer. htop allows you to view information related to command lines such as memory, CPU consumption, and how long it has been running. I often use this whenever I notice a slow down in the speed of my computer and want to find out which processes have a major impact on the speed. I also use this to monitor how many cores and how much of the memory is being used when running a program or when training a model. Packages for htop are available in most distros. To run htop, type htop You should see something like below: In the image above, the commands are sorted by CPU%. It seems like the process /opt/brave,com/brave/brave takes the most CPU consumption among all the running processes. Several shortcuts to try: F4 : Show only processes whose names match the input text F5 : Layout the relations between processes as a tree. Type + or - to expand or collapse a subtree. F6 : On the sorted view, select a field for sorting. Home : Scroll to the top of the process list and select the first process. End : Scroll to the bottom of the process list and select the last process. View the list of all shortcuts here. If you want to get a graphical presentation of your disk usage, try Baobab. I often use this tool to figure out which applications take a lot of disk usage but haven’t been used for a while. Knowing this helps me to clean the files or folders that I no longer need. Like htop, Baobab is also available in most distros. To run Baobab, type baobab And you should see something like below: By using the graph to visualize the disk usage of each folder and file, we have a much better understanding of which folders or files take the most disk usage in our computer. We can also see the size of the folders or files, how many files they have, and when was the last time they were modified. Stacer is the tool that I am most excited about among the three tools I have introduced so far. It allows you to monitor many important pieces of information such as: System information Download and upload speed Search System services Processes. You can consider this as a simple version of htop . Even though it doesn’t give you as many options as htop , it is easier to use and understand. Installed packages History of CPU and memory Stacer also allows you to optimize your computer by: Specifying which applications to start when your computer wakes up Cleaning the system Sending alert messages after the CPU percent, memory percent, and disk percent are below certain percentages and much more! You can find how to install Stacer here. Congratulations! You have just learned how to monitor and optimize your Linux machine using htop, Baobab, and Stacer. Having more control over your machine will enable you to prioritize which tasks to run and remove unnecessary applications or processes. I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter. Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
[ { "code": null, "e": 276, "s": 172, "text": "If you are a Linux user, you might want to know some important information about your computer such as:" }, { "code": null, "e": 325, "s": 276, "text": "System’s CPU usage, memory usage, and disk usage" }, { "code": null, "e": 344, "s": 325, "text": "System information" }, { "code": null, "e": 425, "s": 344, "text": "Disk usage of each folder or file and when was the last time that you used them." }, { "code": null, "e": 477, "s": 425, "text": "Memory and CPU consumption of the running processes" }, { "code": null, "e": 498, "s": 477, "text": "Startup applications" }, { "code": null, "e": 575, "s": 498, "text": "Knowing those pieces of information will enable you to optimize your system." }, { "code": null, "e": 676, "s": 575, "text": "In this article, I will show you 3 tools that allow you to do all of the things above and much more!" }, { "code": null, "e": 843, "s": 676, "text": "htop is an interactive process viewer. htop allows you to view information related to command lines such as memory, CPU consumption, and how long it has been running." }, { "code": null, "e": 1121, "s": 843, "text": "I often use this whenever I notice a slow down in the speed of my computer and want to find out which processes have a major impact on the speed. I also use this to monitor how many cores and how much of the memory is being used when running a program or when training a model." }, { "code": null, "e": 1188, "s": 1121, "text": "Packages for htop are available in most distros. To run htop, type" }, { "code": null, "e": 1193, "s": 1188, "text": "htop" }, { "code": null, "e": 1230, "s": 1193, "text": "You should see something like below:" }, { "code": null, "e": 1400, "s": 1230, "text": "In the image above, the commands are sorted by CPU%. It seems like the process /opt/brave,com/brave/brave takes the most CPU consumption among all the running processes." }, { "code": null, "e": 1426, "s": 1400, "text": "Several shortcuts to try:" }, { "code": null, "e": 1484, "s": 1426, "text": "F4 : Show only processes whose names match the input text" }, { "code": null, "e": 1584, "s": 1484, "text": "F5 : Layout the relations between processes as a tree. Type + or - to expand or collapse a subtree." }, { "code": null, "e": 1637, "s": 1584, "text": "F6 : On the sorted view, select a field for sorting." }, { "code": null, "e": 1712, "s": 1637, "text": "Home : Scroll to the top of the process list and select the first process." }, { "code": null, "e": 1788, "s": 1712, "text": "End : Scroll to the bottom of the process list and select the last process." }, { "code": null, "e": 1825, "s": 1788, "text": "View the list of all shortcuts here." }, { "code": null, "e": 2091, "s": 1825, "text": "If you want to get a graphical presentation of your disk usage, try Baobab. I often use this tool to figure out which applications take a lot of disk usage but haven’t been used for a while. Knowing this helps me to clean the files or folders that I no longer need." }, { "code": null, "e": 2164, "s": 2091, "text": "Like htop, Baobab is also available in most distros. To run Baobab, type" }, { "code": null, "e": 2171, "s": 2164, "text": "baobab" }, { "code": null, "e": 2212, "s": 2171, "text": "And you should see something like below:" }, { "code": null, "e": 2388, "s": 2212, "text": "By using the graph to visualize the disk usage of each folder and file, we have a much better understanding of which folders or files take the most disk usage in our computer." }, { "code": null, "e": 2511, "s": 2388, "text": "We can also see the size of the folders or files, how many files they have, and when was the last time they were modified." }, { "code": null, "e": 2678, "s": 2511, "text": "Stacer is the tool that I am most excited about among the three tools I have introduced so far. It allows you to monitor many important pieces of information such as:" }, { "code": null, "e": 2697, "s": 2678, "text": "System information" }, { "code": null, "e": 2723, "s": 2697, "text": "Download and upload speed" }, { "code": null, "e": 2730, "s": 2723, "text": "Search" }, { "code": null, "e": 2746, "s": 2730, "text": "System services" }, { "code": null, "e": 2903, "s": 2746, "text": "Processes. You can consider this as a simple version of htop . Even though it doesn’t give you as many options as htop , it is easier to use and understand." }, { "code": null, "e": 2922, "s": 2903, "text": "Installed packages" }, { "code": null, "e": 2948, "s": 2922, "text": "History of CPU and memory" }, { "code": null, "e": 3001, "s": 2948, "text": "Stacer also allows you to optimize your computer by:" }, { "code": null, "e": 3068, "s": 3001, "text": "Specifying which applications to start when your computer wakes up" }, { "code": null, "e": 3088, "s": 3068, "text": "Cleaning the system" }, { "code": null, "e": 3197, "s": 3088, "text": "Sending alert messages after the CPU percent, memory percent, and disk percent are below certain percentages" }, { "code": null, "e": 3212, "s": 3197, "text": "and much more!" }, { "code": null, "e": 3253, "s": 3212, "text": "You can find how to install Stacer here." }, { "code": null, "e": 3508, "s": 3253, "text": "Congratulations! You have just learned how to monitor and optimize your Linux machine using htop, Baobab, and Stacer. Having more control over your machine will enable you to prioritize which tasks to run and remove unnecessary applications or processes." }, { "code": null, "e": 3668, "s": 3508, "text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter." } ]
Advanced NumPy: Master stride tricks with 25 illustrated exercises | by Raimi Karim | Towards Data Science
Best viewed with a Chrome browser on desktop Update 6 Jan 2022: Updated Problem 19 based on comments from Sirouan Nouriddine.Update 5 Jan 2022: Fix typos and improve clarity.Update 30 Dec 2021: As of NumPy 1.20.0, there is a sliding_window_view API which can also serve as a higher-level API on top of the as_strided API. See here for more. (Jump to the exercises here) The stride tricks API can be seen as an extension of the usual way of accessing and manipulating NumPyndarray’s, giving users more flexibility to control the resulting NumPy view. While it is an esoteric feature, one particularly practical usage is when sliding windows or rolling statistics are concerned. In this article, we will go through 25 different exercises that use this API (and compare to how we would’ve done it normally). For this article, it is recommended that the reader have mid-level knowledge of Python, NumPy, numpy.dtype, numpy.ndarray.strides, and numpy.ndarray.itemsize. For a quick introduction to NumPy arrays and strides, see the section on 💡 A bit of background below. The exercises, which are arranged with increasing difficulty, are formatted in the following order: The question, illustrated as a diagram with NumPy array input and the expected output, a NumPy view. Assume contiguity in the manner that you read the elements. The itemsize varies for every question. The answer — the strides and shape to be used as parameters in numpy.lib.stride_tricks.as_strided to achieve the final NumPy view. The explanation The code, where as_strided is the namespace imported from this import statement:from numpy.lib.stride_tricks import as_strided 💡 A bit of background How would you access a specific item from a block of fixed-size elements which have been (i) placed contiguously, and (ii) organised into nested sub-groups? Answer: strides. What I just briefly described is a NumPy N-dimensional array (ndarray) data structure, and we use an algorithm called the strided indexing scheme together with strides to traverse it. Here are 4 quick bites you should know about NumPy arrays. 1) Elements in NumPy arrays occupy memory. Every element in a NumPy array uniformly occupies n bytes. For example, every element in an array with data type np.int64 occupies 8 bytes. To find out the item size, np.ndarray.itemsize. 2) Elements in NumPy arrays are stored contiguously in memory. This means they are stored side-by-side (unlike elements in Python lists). 3) There is a piece of information called shape that you probably already know, that defines how large this array is for every dimension. To access this information, np.ndarray.shape. 4) There is another piece of information called strides that indicate the number of bytes to jump to reach the next value in the dimension. To access this information, np.ndarray.strides. With these 4 pieces of information, the memory location of an element can be found by a linear combination of the dimension with the strides as the coefficients. For a more in-depth explanation, refer to my references below. Slice first 3 elementsSlice first 8 elementsFlatten a 2D arraySkip every other elementSlice first columnSlice a diagonalRepeat the first elementSimple 2D slicingSlice a zigzagSparse slicingTranspose a 2D arrayRepeat the first column 4 timesReshape 1D array to 2D arraySlide a 1D windowSlide a 2D window then flattenCollapse an axis from a 3D array2 cornersStaggered slicingRepeat a 2D array3D transposeSlide a 2D windowReshape 1D array to 3D arraySlide a 2D receptive field for convolutionsRepeat a 3D tensorReshape 1D array to 4D array Slice first 3 elements Slice first 8 elements Flatten a 2D array Skip every other element Slice first column Slice a diagonal Repeat the first element Simple 2D slicing Slice a zigzag Sparse slicing Transpose a 2D array Repeat the first column 4 times Reshape 1D array to 2D array Slide a 1D window Slide a 2D window then flatten Collapse an axis from a 3D array 2 corners Staggered slicing Repeat a 2D array 3D transpose Slide a 2D window Reshape 1D array to 3D array Slide a 2D receptive field for convolutions Repeat a 3D tensor Reshape 1D array to 4D array Answer strides = (1,) shape = (3,) 💡 ExplanationAdjacent elements in the output (i.e. 1 → 2, 2 → 3) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,), strides=(1,))array([1, 2, 3], dtype=int8) Similar to >>> x[0,:3]array([1, 2, 3], dtype=int8) Answer strides = (1,) shape = (8,) 💡 ExplanationAdjacent elements in the output (eg. 1 → 2, 2 → 3, 6 → 7) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 8. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(8,), strides=(1,))array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int8) Similar to >>> x[0,:8]array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int8) Answer strides = (2,) shape = (25,) 💡 ExplanationAdjacent elements in the output (eg. 1 → 2, 2 → 3, 23 → 24, 24 → 25) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. The shape of this dimension is 25. Code >>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(25,), strides=(2,))array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], dtype=int16) Similar to >>> x.ravel()array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], dtype=int16) Answer strides = (2,) shape = (3,) 💡 ExplanationAdjacent elements in the output (i.e. 1 → 3, 3 → 5) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,), strides=(2,))array([1, 3, 5], dtype=int8) Similar to >>> x[0,::2]array([1, 3, 5], dtype=int8) Answer strides = (40,) shape = (4,) 💡 ExplanationAdjacent elements in the output (i.e. 1 → 6, 6 → 11, 11 → 16) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 4. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(4,), strides=(40,))array([ 1, 6, 11, 16]) Similar to >>> x[:4,0]array([ 1, 6, 11, 16]) Answer strides = (48,) shape = ( 5,) 💡 ExplanationAdjacent elements in the output (i.e. 1 → 7, 7 → 13, 13 → 19, 19 → 25) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 5. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(5,), strides=(48,))array([ 1, 7, 13, 19, 25]) Similar to >>> x.diagonal()array([ 1, 7, 13, 19, 25]) Answer strides = (0,) shape = (5,) 💡 ExplanationAdjacent elements in the output (i.e. 1 → 1) were originally 0 bytes apart (=0 elements away × 8 bytes) in the input. The shape of this dimension is 5. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(5,), strides=(0,))array([ 1, 1, 1, 1, 1]) Similar to >>> np.broadcast_to(x[0,0], (5,))array([1, 1, 1, 1, 1]) Answer strides = (40,8) shape = ( 3,4) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 8 → 9) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 4. Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 9 → 14) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(3,4), strides=(40,8))array([[ 1, 2, 3, 4], [ 6, 7, 8, 9], [11, 12, 13, 14]]) Similar to >>> x[:3,:4]array([[ 1, 2, 3, 4], [ 6, 7, 8, 9], [11, 12, 13, 14]]) Answer strides = (48,8) shape = ( 4,2) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 7 → 8, 13 → 14, 19 → 20) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 2. Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 13 → 19) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 4. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(4,2), strides=(48,8))array([[ 1, 2], [ 7, 8], [13, 14], [19, 20]]) Similar to >>> # this may not be achieved concisely Answer strides = (80,16) shape = ( 3, 3) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 3, 21 → 23, 13 → 15) were originally 16 bytes apart (=2 elements away × 8 bytes) in the input. The shape of this dimension is 3. Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 11, 13 → 23, 15 → 25) were originally 80 bytes apart (=10 elements away × 8 bytes) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(3,3), strides=(80,16))array([[ 1, 3, 5], [11, 13, 15], [21, 23, 25]]) Similar to >>> x[::2,::2]array([[ 1, 3, 5], [11, 13, 15], [21, 23, 25]]) Answer strides = (1,5) shape = (3,3) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 6, 7 → 12, 3 → 8) were originally 5 bytes apart (=5 elements away × 1 byte) in the input. The shape of this dimension is 3. Output’s top-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 11 → 12) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,3), strides=(1,5))array([[ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13]], dtype=int8) Similar to >>> x[:3,:3].Tarray([[ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13]], dtype=int8) Answer strides = (20,0) shape = ( 5,4) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 1, 6 → 6, 16 → 16) were originally 0 bytes apart (=0 elements away × 4 bytes) in the input. The shape of this dimension is 4. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 6 → 11, 11 → 16) were originally 20 bytes apart (=5 elements away × 4 bytes) in the input. The shape of this dimension is 5. Code >>> x = np.asarray(range(1,26), np.int32).reshape(5,5)>>> as_strided(x, shape=(5,4), strides=(20,0))array([[ 1, 1, 1, 1], [ 6, 6, 6, 6], [11, 11, 11, 11], [16, 16, 16, 16], [21, 21, 21, 21]], dtype=int32) Similar to >>> np.broadcast_to(x[:,0,None], (5,4))array([[ 1, 1, 1, 1], [ 6, 6, 6, 6], [11, 11, 11, 11], [16, 16, 16, 16], [21, 21, 21, 21]], dtype=int32) Answer strides = (24,8) shape = ( 4,3) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 7 → 8, 11 → 12) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 3. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 4 → 7, 7 → 10) were originally 24 bytes apart (=3 elements away × 8 bytes) in the input. The shape of this dimension is 4. Code >>> x = np.asarray(range(1,13), np.int64)>>> as_strided(x, shape=(4,3), strides=(24,8))array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) Similar to >>> x.reshape(4,3)array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) Adapted from a StackOverflow post [1]. Similar to [2] and [3]. Answer strides = (1,1) shape = (8,3) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 4 → 5) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 2, 2 → 3, 4 → 5, ..., 7 → 8) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 8. Code >>> x = np.asarray(range(1,26), np.int8)>>> as_strided(x, shape=(8,3), strides=(1,1))array([[ 1, 2, 3], [ 2, 3, 4], [ 3, 4, 5], [ 4, 5, 6], [ 5, 6, 7], [ 6, 7, 8], [ 7, 8, 9], [ 8, 9, 10]], dtype=int8) Similar to >>> # this may not be achieved concisely Question taken from a StackOverflow post [4]. Answer strides = (2,1) shape = (4,6) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 0 → 1, 1 → 10, 31 → 40) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 6. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 0 → 10, 10 → 20, 41 → 51) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 4. Code >>> x = np.asarray(... [0,1,10,11,20,21,30,31,40,41,50,51],... np.int8).reshape(6,2)>>> as_strided(x, shape=(4,6), strides=(2,1))array([[ 0, 1, 10, 11, 20, 21], [10, 11, 20, 21, 30, 31], [20, 21, 30, 31, 40, 41], [30, 31, 40, 41, 50, 51]], dtype=int8) Similar to >>> # this may not be achieved concisely Answer strides = (4,1) shape = (3,4) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 4 → 5) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 4. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 5, 5 → 9, 2 → 6, 6 → 10) were originally 4 bytes apart (=4 elements away × 1 byte) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,13), np.int8).reshape(3,2,2)>>> as_strided(x, shape=(3,4), strides=(4,1))array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], dtype=int8) Similar to >>> x.reshape(3,4)array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], dtype=int8) Answer strides = (30,10, 2) shape = ( 2, 2, 2) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (i.e. 1 → 2, 6 → 7, 16 → 17, 21 → 22) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. The shape of this dimension is 2. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 6, 2 → 7, 16 → 21, 17 → 22) were originally 10 bytes apart (=5 elements away × 2 bytes) in the input. The shape of this dimension is 2. Output’s box-to-box dimension (axis=-3):Adjacent elements in the output (i.e. 1 → 16, 2 → 17, 6 → 21, 7 → 22) were originally 30 bytes apart (=15 elements away × 2 bytes) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(2,2,2), strides=(30,10,2))array([[[ 1, 2], [ 6, 7]], [[16, 17], [21, 22]]], dtype=int16) Similar to >>> # this may not be achieved concisely Answer strides = (10,6,1) shape = ( 2,2,3) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 17 → 18) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 7, 11 → 17, 12 → 18) were originally 6 bytes apart (=6 elements away × 1 byte) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 11, 8 → 18, 9 → 19) were originally 10 bytes apart (=10 elements away × 1 byte) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(2,2,3), strides=(10,6,1))array([[[ 1, 2, 3], [ 7, 8, 9]], [[11, 12, 13], [17, 18, 19]]], dtype=int8) Similar to >>> # this may not be achieved concisely This question is taken from a StackOverflow post here [5]. Answer strides = (0,10,2) shape = (3, 2,4) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 6 → 7) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. Shape of this dimension is 4. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 3 → 8) were originally 10 bytes apart (=5 elements away × 2 bytes) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 3 → 3, 7 → 7) were originally 0 bytes apart (=0 elements away × 2 bytes) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(3,2,4), strides=(0,10,2))array([[[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]]], dtype=int16) Similar to >>> np.broadcast_to(x[0:2, 0:-1], (3, 2, 4)) (Thank you, Sirouan Nouriddine for sharing this!) Answer strides = (16,4,8) shape = ( 3,2,2) 💡 Explanation Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 3, 2 → 4, 10 → 12) were originally 8 bytes apart (=2 elements away × 4 bytes) in the input. The shape of this dimension is 2. Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 9 → 10, 11 → 12) were originally 4 bytes apart (=1 element away × 4 bytes) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 5, 5 → 9) were originally 16 bytes apart (=4 elements away × 4 bytes) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,13), np.int32).reshape(3,2,2)>>> as_strided(x, shape=(3,2,2), strides=(16,4,8))array([[[ 1, 3], [ 2, 4]], [[ 5, 7], [ 6, 8]], [[ 9, 11], [10, 12]]], dtype=int32) Similar to >>> np.swapaxes(x,1,2)array([[[ 1, 3], [ 2, 4]], [[ 5, 7], [ 6, 8]], [[ 9, 11], [10, 12]]], dtype=int32) Question adapted from SciPy 2008 conference [6]. Answer strides = (40,40,8) shape = ( 3, 2,5) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 12 → 13, 16 → 17) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 5. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 8 → 13, 11 → 16) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 9 → 14, 14 → 19) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 3. Code >>> x = np.asarray(range(1,21), np.int64).reshape(4,5)>>> as_strided(x, shape=(3,2,5), strides=(40,40,8))array([[[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10]], [[ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]) Similar to >>> # this may not be achieved concisely Answer strides = (6,3,1) shape = (2,2,3) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 5 → 6, 7 → 8, 10 → 11) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 2 → 5, 8 → 11) were originally 3 bytes apart (=3 elements away × 1 byte) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 6 bytes apart (=6 elements away × 1 byte) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,13), np.int8)>>> as_strided(x, shape=(2,2,3), strides=(6,3,1))array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]], dtype=int8) Similar to >>> x.reshape(2,2,3)array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]], dtype=int8) Adapted from a StackOverflow post on 2D convolution here [7]. Answer strides = (10,2,5,1) shape = ( 2,2,3,3) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 17 → 18, 24 → 25) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 3 → 8) were originally 5 bytes apart (=5 elements away × 1 byte) in the input. The shape of this dimension is 3. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 3, 6 → 8, 21 → 23, 23 → 25) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 2. Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 11, 2 → 12, 15 → 25) were originally 10 bytes apart (=10 elements away × 1 byte) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(2,2,3,3), strides=(10,2,5,1))array([[[[ 1, 2, 3], [ 6, 7, 8], [11, 12, 13]], [[ 3, 4, 5], [ 8, 9, 10], [13, 14, 15]]], [[[11, 12, 13], [16, 17, 18], [21, 22, 23]], [[13, 14, 15], [18, 19, 20], [23, 24, 25]]]], dtype=int8) Similar to >>> # this may not be achieved concisely Answer strides = (48, 0,24, 8) shape = ( 2, 2, 2, 3) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 4 → 5) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 3. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 7 → 10, 8 → 11) were originally 24 bytes apart (=3 elements away × 8 bytes) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 10 → 10, 12 → 12) were originally 0 bytes apart (=0 elements away × 8 bytes) in the input. The shape of this dimension is 2. Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,13), np.int64).reshape(2,2,3)>>> as_strided(x, shape=(2,2,2,3), strides=(48,0,24,8))array([[[[ 1, 2, 3], [ 4, 5, 6]], [[ 1, 2, 3], [ 4, 5, 6]]], [[[ 7, 8, 9], [10, 11, 12]], [[ 7, 8, 9], [10, 11, 12]]]]) Similar to >>> np.broadcast_to(x,(2,2,2,3)).swapaxes(0,1)array([[[[ 1, 2, 3], [ 4, 5, 6]], [[ 1, 2, 3], [ 4, 5, 6]]], [[[ 7, 8, 9], [10, 11, 12]], [[ 7, 8, 9], [10, 11, 12]]]]) Answer strides = (64,32,16, 8) shape = ( 2, 2, 2, 2) 💡 Explanation Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 4 → 5) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 2. Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 7 → 10, 8 → 11) were originally 16 bytes apart (=2 elements away × 8 bytes) in the input. The shape of this dimension is 2. Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 10 → 10, 12 → 12) were originally 32 bytes apart (=4 elements away × 8 bytes) in the input. The shape of this dimension is 2. Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 64 bytes apart (=8 elements away × 8 bytes) in the input. The shape of this dimension is 2. Code >>> x = np.asarray(range(1,17), np.int64)>>> as_strided(x, shape=(2,2,2,2), strides=(64,32,16,8))array([[[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]], [[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]]) Similar to >>> x.reshape(2,2,2,2)array([[[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]], [[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]]) ⚠️ While stride tricks give you more control over the resulting NumPy view, the API is not memory-safe — things can get pretty nasty if you miscalculate the itemsize (honestly I think this API should not allow client code to have to deal with item size as I haven’t seen any benefits of exposing this) or the shape or the existing strides, returning data that is actually not the initial array you created, but from a different array altogether which you probably defined few lines back 😱. This is known as buffer overflow and it’s not hard to encounter this using the stride tricks API. What’s worse is when you decide to write to this data 😱😱. It is for this reason that the stride tricks documentation cautions the user to exercise extreme care when using it. Understanding the stride tricks API can be challenging, and I had problems with that. However, the trick (no pun intended) is to start with smaller dimensions and visualise the output of the tensors. Have fun! Found a mistake? Let me know in the comments! :) Shoutout to David Chong for reviewing this article. If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees. The N-dimensional array (ndarray) (numpy.org) Advanced NumPy (scipy-lectures.org) An Illustrated Guide to Shape and Strides (ajcr.net) Using stride tricks with NumPy (ipython-books.github.io)
[ { "code": null, "e": 216, "s": 171, "text": "Best viewed with a Chrome browser on desktop" }, { "code": null, "e": 512, "s": 216, "text": "Update 6 Jan 2022: Updated Problem 19 based on comments from Sirouan Nouriddine.Update 5 Jan 2022: Fix typos and improve clarity.Update 30 Dec 2021: As of NumPy 1.20.0, there is a sliding_window_view API which can also serve as a higher-level API on top of the as_strided API. See here for more." }, { "code": null, "e": 541, "s": 512, "text": "(Jump to the exercises here)" }, { "code": null, "e": 976, "s": 541, "text": "The stride tricks API can be seen as an extension of the usual way of accessing and manipulating NumPyndarray’s, giving users more flexibility to control the resulting NumPy view. While it is an esoteric feature, one particularly practical usage is when sliding windows or rolling statistics are concerned. In this article, we will go through 25 different exercises that use this API (and compare to how we would’ve done it normally)." }, { "code": null, "e": 1237, "s": 976, "text": "For this article, it is recommended that the reader have mid-level knowledge of Python, NumPy, numpy.dtype, numpy.ndarray.strides, and numpy.ndarray.itemsize. For a quick introduction to NumPy arrays and strides, see the section on 💡 A bit of background below." }, { "code": null, "e": 1337, "s": 1237, "text": "The exercises, which are arranged with increasing difficulty, are formatted in the following order:" }, { "code": null, "e": 1538, "s": 1337, "text": "The question, illustrated as a diagram with NumPy array input and the expected output, a NumPy view. Assume contiguity in the manner that you read the elements. The itemsize varies for every question." }, { "code": null, "e": 1669, "s": 1538, "text": "The answer — the strides and shape to be used as parameters in numpy.lib.stride_tricks.as_strided to achieve the final NumPy view." }, { "code": null, "e": 1685, "s": 1669, "text": "The explanation" }, { "code": null, "e": 1812, "s": 1685, "text": "The code, where as_strided is the namespace imported from this import statement:from numpy.lib.stride_tricks import as_strided" }, { "code": null, "e": 1834, "s": 1812, "text": "💡 A bit of background" }, { "code": null, "e": 2192, "s": 1834, "text": "How would you access a specific item from a block of fixed-size elements which have been (i) placed contiguously, and (ii) organised into nested sub-groups? Answer: strides. What I just briefly described is a NumPy N-dimensional array (ndarray) data structure, and we use an algorithm called the strided indexing scheme together with strides to traverse it." }, { "code": null, "e": 2251, "s": 2192, "text": "Here are 4 quick bites you should know about NumPy arrays." }, { "code": null, "e": 2482, "s": 2251, "text": "1) Elements in NumPy arrays occupy memory. Every element in a NumPy array uniformly occupies n bytes. For example, every element in an array with data type np.int64 occupies 8 bytes. To find out the item size, np.ndarray.itemsize." }, { "code": null, "e": 2620, "s": 2482, "text": "2) Elements in NumPy arrays are stored contiguously in memory. This means they are stored side-by-side (unlike elements in Python lists)." }, { "code": null, "e": 2804, "s": 2620, "text": "3) There is a piece of information called shape that you probably already know, that defines how large this array is for every dimension. To access this information, np.ndarray.shape." }, { "code": null, "e": 2992, "s": 2804, "text": "4) There is another piece of information called strides that indicate the number of bytes to jump to reach the next value in the dimension. To access this information, np.ndarray.strides." }, { "code": null, "e": 3217, "s": 2992, "text": "With these 4 pieces of information, the memory location of an element can be found by a linear combination of the dimension with the strides as the coefficients. For a more in-depth explanation, refer to my references below." }, { "code": null, "e": 3754, "s": 3217, "text": "Slice first 3 elementsSlice first 8 elementsFlatten a 2D arraySkip every other elementSlice first columnSlice a diagonalRepeat the first elementSimple 2D slicingSlice a zigzagSparse slicingTranspose a 2D arrayRepeat the first column 4 timesReshape 1D array to 2D arraySlide a 1D windowSlide a 2D window then flattenCollapse an axis from a 3D array2 cornersStaggered slicingRepeat a 2D array3D transposeSlide a 2D windowReshape 1D array to 3D arraySlide a 2D receptive field for convolutionsRepeat a 3D tensorReshape 1D array to 4D array" }, { "code": null, "e": 3777, "s": 3754, "text": "Slice first 3 elements" }, { "code": null, "e": 3800, "s": 3777, "text": "Slice first 8 elements" }, { "code": null, "e": 3819, "s": 3800, "text": "Flatten a 2D array" }, { "code": null, "e": 3844, "s": 3819, "text": "Skip every other element" }, { "code": null, "e": 3863, "s": 3844, "text": "Slice first column" }, { "code": null, "e": 3880, "s": 3863, "text": "Slice a diagonal" }, { "code": null, "e": 3905, "s": 3880, "text": "Repeat the first element" }, { "code": null, "e": 3923, "s": 3905, "text": "Simple 2D slicing" }, { "code": null, "e": 3938, "s": 3923, "text": "Slice a zigzag" }, { "code": null, "e": 3953, "s": 3938, "text": "Sparse slicing" }, { "code": null, "e": 3974, "s": 3953, "text": "Transpose a 2D array" }, { "code": null, "e": 4006, "s": 3974, "text": "Repeat the first column 4 times" }, { "code": null, "e": 4035, "s": 4006, "text": "Reshape 1D array to 2D array" }, { "code": null, "e": 4053, "s": 4035, "text": "Slide a 1D window" }, { "code": null, "e": 4084, "s": 4053, "text": "Slide a 2D window then flatten" }, { "code": null, "e": 4117, "s": 4084, "text": "Collapse an axis from a 3D array" }, { "code": null, "e": 4127, "s": 4117, "text": "2 corners" }, { "code": null, "e": 4145, "s": 4127, "text": "Staggered slicing" }, { "code": null, "e": 4163, "s": 4145, "text": "Repeat a 2D array" }, { "code": null, "e": 4176, "s": 4163, "text": "3D transpose" }, { "code": null, "e": 4194, "s": 4176, "text": "Slide a 2D window" }, { "code": null, "e": 4223, "s": 4194, "text": "Reshape 1D array to 3D array" }, { "code": null, "e": 4267, "s": 4223, "text": "Slide a 2D receptive field for convolutions" }, { "code": null, "e": 4286, "s": 4267, "text": "Repeat a 3D tensor" }, { "code": null, "e": 4315, "s": 4286, "text": "Reshape 1D array to 4D array" }, { "code": null, "e": 4322, "s": 4315, "text": "Answer" }, { "code": null, "e": 4351, "s": 4322, "text": "strides = (1,) shape = (3,)" }, { "code": null, "e": 4520, "s": 4351, "text": "💡 ExplanationAdjacent elements in the output (i.e. 1 → 2, 2 → 3) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 4525, "s": 4520, "text": "Code" }, { "code": null, "e": 4650, "s": 4525, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,), strides=(1,))array([1, 2, 3], dtype=int8)" }, { "code": null, "e": 4661, "s": 4650, "text": "Similar to" }, { "code": null, "e": 4701, "s": 4661, "text": ">>> x[0,:3]array([1, 2, 3], dtype=int8)" }, { "code": null, "e": 4708, "s": 4701, "text": "Answer" }, { "code": null, "e": 4737, "s": 4708, "text": "strides = (1,) shape = (8,)" }, { "code": null, "e": 4912, "s": 4737, "text": "💡 ExplanationAdjacent elements in the output (eg. 1 → 2, 2 → 3, 6 → 7) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 8." }, { "code": null, "e": 4917, "s": 4912, "text": "Code" }, { "code": null, "e": 5057, "s": 4917, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(8,), strides=(1,))array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int8)" }, { "code": null, "e": 5068, "s": 5057, "text": "Similar to" }, { "code": null, "e": 5123, "s": 5068, "text": ">>> x[0,:8]array([1, 2, 3, 4, 5, 6, 7, 8], dtype=int8)" }, { "code": null, "e": 5130, "s": 5123, "text": "Answer" }, { "code": null, "e": 5160, "s": 5130, "text": "strides = (2,) shape = (25,)" }, { "code": null, "e": 5349, "s": 5160, "text": "💡 ExplanationAdjacent elements in the output (eg. 1 → 2, 2 → 3, 23 → 24, 24 → 25) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. The shape of this dimension is 25." }, { "code": null, "e": 5354, "s": 5349, "text": "Code" }, { "code": null, "e": 5585, "s": 5354, "text": ">>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(25,), strides=(2,))array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], dtype=int16)" }, { "code": null, "e": 5596, "s": 5585, "text": "Similar to" }, { "code": null, "e": 5742, "s": 5596, "text": ">>> x.ravel()array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25], dtype=int16)" }, { "code": null, "e": 5749, "s": 5742, "text": "Answer" }, { "code": null, "e": 5778, "s": 5749, "text": "strides = (2,) shape = (3,)" }, { "code": null, "e": 5949, "s": 5778, "text": "💡 ExplanationAdjacent elements in the output (i.e. 1 → 3, 3 → 5) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 5954, "s": 5949, "text": "Code" }, { "code": null, "e": 6079, "s": 5954, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,), strides=(2,))array([1, 3, 5], dtype=int8)" }, { "code": null, "e": 6090, "s": 6079, "text": "Similar to" }, { "code": null, "e": 6131, "s": 6090, "text": ">>> x[0,::2]array([1, 3, 5], dtype=int8)" }, { "code": null, "e": 6138, "s": 6131, "text": "Answer" }, { "code": null, "e": 6168, "s": 6138, "text": "strides = (40,) shape = (4,)" }, { "code": null, "e": 6351, "s": 6168, "text": "💡 ExplanationAdjacent elements in the output (i.e. 1 → 6, 6 → 11, 11 → 16) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 4." }, { "code": null, "e": 6356, "s": 6351, "text": "Code" }, { "code": null, "e": 6478, "s": 6356, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(4,), strides=(40,))array([ 1, 6, 11, 16])" }, { "code": null, "e": 6489, "s": 6478, "text": "Similar to" }, { "code": null, "e": 6524, "s": 6489, "text": ">>> x[:4,0]array([ 1, 6, 11, 16])" }, { "code": null, "e": 6531, "s": 6524, "text": "Answer" }, { "code": null, "e": 6562, "s": 6531, "text": "strides = (48,) shape = ( 5,)" }, { "code": null, "e": 6754, "s": 6562, "text": "💡 ExplanationAdjacent elements in the output (i.e. 1 → 7, 7 → 13, 13 → 19, 19 → 25) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 5." }, { "code": null, "e": 6759, "s": 6754, "text": "Code" }, { "code": null, "e": 6885, "s": 6759, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(5,), strides=(48,))array([ 1, 7, 13, 19, 25])" }, { "code": null, "e": 6896, "s": 6885, "text": "Similar to" }, { "code": null, "e": 6940, "s": 6896, "text": ">>> x.diagonal()array([ 1, 7, 13, 19, 25])" }, { "code": null, "e": 6947, "s": 6940, "text": "Answer" }, { "code": null, "e": 6976, "s": 6947, "text": "strides = (0,) shape = (5,)" }, { "code": null, "e": 7141, "s": 6976, "text": "💡 ExplanationAdjacent elements in the output (i.e. 1 → 1) were originally 0 bytes apart (=0 elements away × 8 bytes) in the input. The shape of this dimension is 5." }, { "code": null, "e": 7146, "s": 7141, "text": "Code" }, { "code": null, "e": 7267, "s": 7146, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(5,), strides=(0,))array([ 1, 1, 1, 1, 1])" }, { "code": null, "e": 7278, "s": 7267, "text": "Similar to" }, { "code": null, "e": 7334, "s": 7278, "text": ">>> np.broadcast_to(x[0,0], (5,))array([1, 1, 1, 1, 1])" }, { "code": null, "e": 7341, "s": 7334, "text": "Answer" }, { "code": null, "e": 7374, "s": 7341, "text": "strides = (40,8) shape = ( 3,4)" }, { "code": null, "e": 7388, "s": 7374, "text": "💡 Explanation" }, { "code": null, "e": 7595, "s": 7388, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 8 → 9) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 4." }, { "code": null, "e": 7805, "s": 7595, "text": "Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 9 → 14) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 7810, "s": 7805, "text": "Code" }, { "code": null, "e": 7984, "s": 7810, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(3,4), strides=(40,8))array([[ 1, 2, 3, 4], [ 6, 7, 8, 9], [11, 12, 13, 14]])" }, { "code": null, "e": 7995, "s": 7984, "text": "Similar to" }, { "code": null, "e": 8081, "s": 7995, "text": ">>> x[:3,:4]array([[ 1, 2, 3, 4], [ 6, 7, 8, 9], [11, 12, 13, 14]])" }, { "code": null, "e": 8088, "s": 8081, "text": "Answer" }, { "code": null, "e": 8121, "s": 8088, "text": "strides = (48,8) shape = ( 4,2)" }, { "code": null, "e": 8135, "s": 8121, "text": "💡 Explanation" }, { "code": null, "e": 8353, "s": 8135, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 7 → 8, 13 → 14, 19 → 20) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 8564, "s": 8353, "text": "Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 13 → 19) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 4." }, { "code": null, "e": 8569, "s": 8564, "text": "Code" }, { "code": null, "e": 8735, "s": 8569, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(4,2), strides=(48,8))array([[ 1, 2], [ 7, 8], [13, 14], [19, 20]])" }, { "code": null, "e": 8746, "s": 8735, "text": "Similar to" }, { "code": null, "e": 8787, "s": 8746, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 8794, "s": 8787, "text": "Answer" }, { "code": null, "e": 8829, "s": 8794, "text": "strides = (80,16) shape = ( 3, 3)" }, { "code": null, "e": 8843, "s": 8829, "text": "💡 Explanation" }, { "code": null, "e": 9056, "s": 8843, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 3, 21 → 23, 13 → 15) were originally 16 bytes apart (=2 elements away × 8 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 9271, "s": 9056, "text": "Output’s left-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 11, 13 → 23, 15 → 25) were originally 80 bytes apart (=10 elements away × 8 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 9276, "s": 9271, "text": "Code" }, { "code": null, "e": 9439, "s": 9276, "text": ">>> x = np.asarray(range(1,26), np.int64).reshape(5,5)>>> as_strided(x, shape=(3,3), strides=(80,16))array([[ 1, 3, 5], [11, 13, 15], [21, 23, 25]])" }, { "code": null, "e": 9450, "s": 9439, "text": "Similar to" }, { "code": null, "e": 9526, "s": 9450, "text": ">>> x[::2,::2]array([[ 1, 3, 5], [11, 13, 15], [21, 23, 25]])" }, { "code": null, "e": 9533, "s": 9526, "text": "Answer" }, { "code": null, "e": 9564, "s": 9533, "text": "strides = (1,5) shape = (3,3)" }, { "code": null, "e": 9578, "s": 9564, "text": "💡 Explanation" }, { "code": null, "e": 9786, "s": 9578, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 6, 7 → 12, 3 → 8) were originally 5 bytes apart (=5 elements away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 9992, "s": 9786, "text": "Output’s top-to-right dimension (axis=-2):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 11 → 12) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 9997, "s": 9992, "text": "Code" }, { "code": null, "e": 10169, "s": 9997, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(3,3), strides=(1,5))array([[ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13]], dtype=int8)" }, { "code": null, "e": 10180, "s": 10169, "text": "Similar to" }, { "code": null, "e": 10268, "s": 10180, "text": ">>> x[:3,:3].Tarray([[ 1, 6, 11], [ 2, 7, 12], [ 3, 8, 13]], dtype=int8)" }, { "code": null, "e": 10275, "s": 10268, "text": "Answer" }, { "code": null, "e": 10308, "s": 10275, "text": "strides = (20,0) shape = ( 5,4)" }, { "code": null, "e": 10322, "s": 10308, "text": "💡 Explanation" }, { "code": null, "e": 10532, "s": 10322, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 1, 6 → 6, 16 → 16) were originally 0 bytes apart (=0 elements away × 4 bytes) in the input. The shape of this dimension is 4." }, { "code": null, "e": 10744, "s": 10532, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 6 → 11, 11 → 16) were originally 20 bytes apart (=5 elements away × 4 bytes) in the input. The shape of this dimension is 5." }, { "code": null, "e": 10749, "s": 10744, "text": "Code" }, { "code": null, "e": 10984, "s": 10749, "text": ">>> x = np.asarray(range(1,26), np.int32).reshape(5,5)>>> as_strided(x, shape=(5,4), strides=(20,0))array([[ 1, 1, 1, 1], [ 6, 6, 6, 6], [11, 11, 11, 11], [16, 16, 16, 16], [21, 21, 21, 21]], dtype=int32)" }, { "code": null, "e": 10995, "s": 10984, "text": "Similar to" }, { "code": null, "e": 11169, "s": 10995, "text": ">>> np.broadcast_to(x[:,0,None], (5,4))array([[ 1, 1, 1, 1], [ 6, 6, 6, 6], [11, 11, 11, 11], [16, 16, 16, 16], [21, 21, 21, 21]], dtype=int32)" }, { "code": null, "e": 11176, "s": 11169, "text": "Answer" }, { "code": null, "e": 11209, "s": 11176, "text": "strides = (24,8) shape = ( 4,3)" }, { "code": null, "e": 11223, "s": 11209, "text": "💡 Explanation" }, { "code": null, "e": 11439, "s": 11223, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 7 → 8, 11 → 12) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 11649, "s": 11439, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 4 → 7, 7 → 10) were originally 24 bytes apart (=3 elements away × 8 bytes) in the input. The shape of this dimension is 4." }, { "code": null, "e": 11654, "s": 11649, "text": "Code" }, { "code": null, "e": 11823, "s": 11654, "text": ">>> x = np.asarray(range(1,13), np.int64)>>> as_strided(x, shape=(4,3), strides=(24,8))array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]])" }, { "code": null, "e": 11834, "s": 11823, "text": "Similar to" }, { "code": null, "e": 11934, "s": 11834, "text": ">>> x.reshape(4,3)array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]])" }, { "code": null, "e": 11997, "s": 11934, "text": "Adapted from a StackOverflow post [1]. Similar to [2] and [3]." }, { "code": null, "e": 12004, "s": 11997, "text": "Answer" }, { "code": null, "e": 12035, "s": 12004, "text": "strides = (1,1) shape = (8,3)" }, { "code": null, "e": 12049, "s": 12035, "text": "💡 Explanation" }, { "code": null, "e": 12254, "s": 12049, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 4 → 5) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 12472, "s": 12254, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 2, 2 → 3, 4 → 5, ..., 7 → 8) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 8." }, { "code": null, "e": 12477, "s": 12472, "text": "Code" }, { "code": null, "e": 12736, "s": 12477, "text": ">>> x = np.asarray(range(1,26), np.int8)>>> as_strided(x, shape=(8,3), strides=(1,1))array([[ 1, 2, 3], [ 2, 3, 4], [ 3, 4, 5], [ 4, 5, 6], [ 5, 6, 7], [ 6, 7, 8], [ 7, 8, 9], [ 8, 9, 10]], dtype=int8)" }, { "code": null, "e": 12747, "s": 12736, "text": "Similar to" }, { "code": null, "e": 12788, "s": 12747, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 12834, "s": 12788, "text": "Question taken from a StackOverflow post [4]." }, { "code": null, "e": 12841, "s": 12834, "text": "Answer" }, { "code": null, "e": 12872, "s": 12841, "text": "strides = (2,1) shape = (4,6)" }, { "code": null, "e": 12886, "s": 12872, "text": "💡 Explanation" }, { "code": null, "e": 13094, "s": 12886, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 0 → 1, 1 → 10, 31 → 40) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 6." }, { "code": null, "e": 13306, "s": 13094, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 0 → 10, 10 → 20, 41 → 51) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 4." }, { "code": null, "e": 13311, "s": 13306, "text": "Code" }, { "code": null, "e": 13598, "s": 13311, "text": ">>> x = np.asarray(... [0,1,10,11,20,21,30,31,40,41,50,51],... np.int8).reshape(6,2)>>> as_strided(x, shape=(4,6), strides=(2,1))array([[ 0, 1, 10, 11, 20, 21], [10, 11, 20, 21, 30, 31], [20, 21, 30, 31, 40, 41], [30, 31, 40, 41, 50, 51]], dtype=int8)" }, { "code": null, "e": 13609, "s": 13598, "text": "Similar to" }, { "code": null, "e": 13650, "s": 13609, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 13657, "s": 13650, "text": "Answer" }, { "code": null, "e": 13688, "s": 13657, "text": "strides = (4,1) shape = (3,4)" }, { "code": null, "e": 13702, "s": 13688, "text": "💡 Explanation" }, { "code": null, "e": 13907, "s": 13702, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 4 → 5) were originally 1 byte apart (=1 element away × 1 byte) in the input. The shape of this dimension is 4." }, { "code": null, "e": 14123, "s": 13907, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 5, 5 → 9, 2 → 6, 6 → 10) were originally 4 bytes apart (=4 elements away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 14128, "s": 14123, "text": "Code" }, { "code": null, "e": 14314, "s": 14128, "text": ">>> x = np.asarray(range(1,13), np.int8).reshape(3,2,2)>>> as_strided(x, shape=(3,4), strides=(4,1))array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], dtype=int8)" }, { "code": null, "e": 14325, "s": 14314, "text": "Similar to" }, { "code": null, "e": 14429, "s": 14325, "text": ">>> x.reshape(3,4)array([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12]], dtype=int8)" }, { "code": null, "e": 14436, "s": 14429, "text": "Answer" }, { "code": null, "e": 14477, "s": 14436, "text": "strides = (30,10, 2) shape = ( 2, 2, 2)" }, { "code": null, "e": 14491, "s": 14477, "text": "💡 Explanation" }, { "code": null, "e": 14710, "s": 14491, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (i.e. 1 → 2, 6 → 7, 16 → 17, 21 → 22) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 14931, "s": 14710, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (i.e. 1 → 6, 2 → 7, 16 → 21, 17 → 22) were originally 10 bytes apart (=5 elements away × 2 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 15150, "s": 14931, "text": "Output’s box-to-box dimension (axis=-3):Adjacent elements in the output (i.e. 1 → 16, 2 → 17, 6 → 21, 7 → 22) were originally 30 bytes apart (=15 elements away × 2 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 15155, "s": 15150, "text": "Code" }, { "code": null, "e": 15345, "s": 15155, "text": ">>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(2,2,2), strides=(30,10,2))array([[[ 1, 2], [ 6, 7]], [[16, 17], [21, 22]]], dtype=int16)" }, { "code": null, "e": 15356, "s": 15345, "text": "Similar to" }, { "code": null, "e": 15397, "s": 15356, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 15404, "s": 15397, "text": "Answer" }, { "code": null, "e": 15441, "s": 15404, "text": "strides = (10,6,1) shape = ( 2,2,3)" }, { "code": null, "e": 15455, "s": 15441, "text": "💡 Explanation" }, { "code": null, "e": 15667, "s": 15455, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 17 → 18) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3." }, { "code": null, "e": 15887, "s": 15667, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 7, 11 → 17, 12 → 18) were originally 6 bytes apart (=6 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 16107, "s": 15887, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 11, 8 → 18, 9 → 19) were originally 10 bytes apart (=10 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 16112, "s": 16107, "text": "Code" }, { "code": null, "e": 16315, "s": 16112, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(2,2,3), strides=(10,6,1))array([[[ 1, 2, 3], [ 7, 8, 9]], [[11, 12, 13], [17, 18, 19]]], dtype=int8)" }, { "code": null, "e": 16326, "s": 16315, "text": "Similar to" }, { "code": null, "e": 16367, "s": 16326, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 16426, "s": 16367, "text": "This question is taken from a StackOverflow post here [5]." }, { "code": null, "e": 16433, "s": 16426, "text": "Answer" }, { "code": null, "e": 16470, "s": 16433, "text": "strides = (0,10,2) shape = (3, 2,4)" }, { "code": null, "e": 16484, "s": 16470, "text": "💡 Explanation" }, { "code": null, "e": 16696, "s": 16484, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 6 → 7) were originally 2 bytes apart (=1 element away × 2 bytes) in the input. Shape of this dimension is 4." }, { "code": null, "e": 16914, "s": 16696, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 3 → 8) were originally 10 bytes apart (=5 elements away × 2 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 17130, "s": 16914, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 3 → 3, 7 → 7) were originally 0 bytes apart (=0 elements away × 2 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 17135, "s": 17130, "text": "Code" }, { "code": null, "e": 17383, "s": 17135, "text": ">>> x = np.asarray(range(1,26), np.int16).reshape(5,5)>>> as_strided(x, shape=(3,2,4), strides=(0,10,2))array([[[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]], [[1, 2, 3, 4], [6, 7, 8, 9]]], dtype=int16)" }, { "code": null, "e": 17394, "s": 17383, "text": "Similar to" }, { "code": null, "e": 17439, "s": 17394, "text": ">>> np.broadcast_to(x[0:2, 0:-1], (3, 2, 4))" }, { "code": null, "e": 17489, "s": 17439, "text": "(Thank you, Sirouan Nouriddine for sharing this!)" }, { "code": null, "e": 17496, "s": 17489, "text": "Answer" }, { "code": null, "e": 17533, "s": 17496, "text": "strides = (16,4,8) shape = ( 3,2,2)" }, { "code": null, "e": 17547, "s": 17533, "text": "💡 Explanation" }, { "code": null, "e": 17757, "s": 17547, "text": "Output’s left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 3, 2 → 4, 10 → 12) were originally 8 bytes apart (=2 elements away × 4 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 17974, "s": 17757, "text": "Output’s top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 2, 3 → 4, 9 → 10, 11 → 12) were originally 4 bytes apart (=1 element away × 4 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 18184, "s": 17974, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 5, 5 → 9) were originally 16 bytes apart (=4 elements away × 4 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 18189, "s": 18184, "text": "Code" }, { "code": null, "e": 18415, "s": 18189, "text": ">>> x = np.asarray(range(1,13), np.int32).reshape(3,2,2)>>> as_strided(x, shape=(3,2,2), strides=(16,4,8))array([[[ 1, 3], [ 2, 4]], [[ 5, 7], [ 6, 8]], [[ 9, 11], [10, 12]]], dtype=int32)" }, { "code": null, "e": 18426, "s": 18415, "text": "Similar to" }, { "code": null, "e": 18568, "s": 18426, "text": ">>> np.swapaxes(x,1,2)array([[[ 1, 3], [ 2, 4]], [[ 5, 7], [ 6, 8]], [[ 9, 11], [10, 12]]], dtype=int32)" }, { "code": null, "e": 18617, "s": 18568, "text": "Question adapted from SciPy 2008 conference [6]." }, { "code": null, "e": 18624, "s": 18617, "text": "Answer" }, { "code": null, "e": 18663, "s": 18624, "text": "strides = (40,40,8) shape = ( 3, 2,5)" }, { "code": null, "e": 18677, "s": 18663, "text": "💡 Explanation" }, { "code": null, "e": 18893, "s": 18677, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 12 → 13, 16 → 17) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 5." }, { "code": null, "e": 19114, "s": 18893, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 8 → 13, 11 → 16) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 19327, "s": 19114, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 9 → 14, 14 → 19) were originally 40 bytes apart (=5 elements away × 8 bytes) in the input. The shape of this dimension is 3." }, { "code": null, "e": 19332, "s": 19327, "text": "Code" }, { "code": null, "e": 19616, "s": 19332, "text": ">>> x = np.asarray(range(1,21), np.int64).reshape(4,5)>>> as_strided(x, shape=(3,2,5), strides=(40,40,8))array([[[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10]], [[ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]])" }, { "code": null, "e": 19627, "s": 19616, "text": "Similar to" }, { "code": null, "e": 19668, "s": 19627, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 19675, "s": 19668, "text": "Answer" }, { "code": null, "e": 19710, "s": 19675, "text": "strides = (6,3,1) shape = (2,2,3)" }, { "code": null, "e": 19724, "s": 19710, "text": "💡 Explanation" }, { "code": null, "e": 19943, "s": 19724, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 5 → 6, 7 → 8, 10 → 11) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3." }, { "code": null, "e": 20160, "s": 19943, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 2 → 5, 8 → 11) were originally 3 bytes apart (=3 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 20375, "s": 20160, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 6 bytes apart (=6 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 20380, "s": 20375, "text": "Code" }, { "code": null, "e": 20569, "s": 20380, "text": ">>> x = np.asarray(range(1,13), np.int8)>>> as_strided(x, shape=(2,2,3), strides=(6,3,1))array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]], dtype=int8)" }, { "code": null, "e": 20580, "s": 20569, "text": "Similar to" }, { "code": null, "e": 20700, "s": 20580, "text": ">>> x.reshape(2,2,3)array([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [10, 11, 12]]], dtype=int8)" }, { "code": null, "e": 20762, "s": 20700, "text": "Adapted from a StackOverflow post on 2D convolution here [7]." }, { "code": null, "e": 20769, "s": 20762, "text": "Answer" }, { "code": null, "e": 20810, "s": 20769, "text": "strides = (10,2,5,1) shape = ( 2,2,3,3)" }, { "code": null, "e": 20824, "s": 20810, "text": "💡 Explanation" }, { "code": null, "e": 21038, "s": 20824, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 17 → 18, 24 → 25) were originally 1 byte apart (=1 element away × 1 byte) in the input. Shape of this dimension is 3." }, { "code": null, "e": 21254, "s": 21038, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 6, 2 → 7, 3 → 8) were originally 5 bytes apart (=5 elements away × 1 byte) in the input. The shape of this dimension is 3." }, { "code": null, "e": 21480, "s": 21254, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 3, 6 → 8, 21 → 23, 23 → 25) were originally 2 bytes apart (=2 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 21701, "s": 21480, "text": "Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 11, 2 → 12, 15 → 25) were originally 10 bytes apart (=10 elements away × 1 byte) in the input. The shape of this dimension is 2." }, { "code": null, "e": 21706, "s": 21701, "text": "Code" }, { "code": null, "e": 22097, "s": 21706, "text": ">>> x = np.asarray(range(1,26), np.int8).reshape(5,5)>>> as_strided(x, shape=(2,2,3,3), strides=(10,2,5,1))array([[[[ 1, 2, 3], [ 6, 7, 8], [11, 12, 13]], [[ 3, 4, 5], [ 8, 9, 10], [13, 14, 15]]], [[[11, 12, 13], [16, 17, 18], [21, 22, 23]], [[13, 14, 15], [18, 19, 20], [23, 24, 25]]]], dtype=int8)" }, { "code": null, "e": 22108, "s": 22097, "text": "Similar to" }, { "code": null, "e": 22149, "s": 22108, "text": ">>> # this may not be achieved concisely" }, { "code": null, "e": 22156, "s": 22149, "text": "Answer" }, { "code": null, "e": 22203, "s": 22156, "text": "strides = (48, 0,24, 8) shape = ( 2, 2, 2, 3)" }, { "code": null, "e": 22217, "s": 22203, "text": "💡 Explanation" }, { "code": null, "e": 22429, "s": 22217, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 4 → 5) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 3." }, { "code": null, "e": 22649, "s": 22429, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 7 → 10, 8 → 11) were originally 24 bytes apart (=3 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 22869, "s": 22649, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 10 → 10, 12 → 12) were originally 0 bytes apart (=0 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 23086, "s": 22869, "text": "Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 48 bytes apart (=6 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 23091, "s": 23086, "text": "Code" }, { "code": null, "e": 23386, "s": 23091, "text": ">>> x = np.asarray(range(1,13), np.int64).reshape(2,2,3)>>> as_strided(x, shape=(2,2,2,3), strides=(48,0,24,8))array([[[[ 1, 2, 3], [ 4, 5, 6]], [[ 1, 2, 3], [ 4, 5, 6]]], [[[ 7, 8, 9], [10, 11, 12]], [[ 7, 8, 9], [10, 11, 12]]]])" }, { "code": null, "e": 23397, "s": 23386, "text": "Similar to" }, { "code": null, "e": 23627, "s": 23397, "text": ">>> np.broadcast_to(x,(2,2,2,3)).swapaxes(0,1)array([[[[ 1, 2, 3], [ 4, 5, 6]], [[ 1, 2, 3], [ 4, 5, 6]]], [[[ 7, 8, 9], [10, 11, 12]], [[ 7, 8, 9], [10, 11, 12]]]])" }, { "code": null, "e": 23634, "s": 23627, "text": "Answer" }, { "code": null, "e": 23681, "s": 23634, "text": "strides = (64,32,16, 8) shape = ( 2, 2, 2, 2)" }, { "code": null, "e": 23695, "s": 23681, "text": "💡 Explanation" }, { "code": null, "e": 23907, "s": 23695, "text": "Output’s intrabox left-to-right dimension (axis=-1):Adjacent elements in the output (eg. 1 → 2, 2 → 3, 4 → 5) were originally 8 bytes apart (=1 element away × 8 bytes) in the input. Shape of this dimension is 2." }, { "code": null, "e": 24127, "s": 23907, "text": "Output’s intrabox top-to-bottom dimension (axis=-2):Adjacent elements in the output (eg. 1 → 4, 7 → 10, 8 → 11) were originally 16 bytes apart (=2 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 24348, "s": 24127, "text": "Output’s left box-to-right box dimension (axis=-3):Adjacent elements in the output (eg. 1 → 1, 10 → 10, 12 → 12) were originally 32 bytes apart (=4 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 24565, "s": 24348, "text": "Output’s top box-to-bottom box dimension (axis=-4):Adjacent elements in the output (eg. 1 → 7, 2 → 8, 3 → 9) were originally 64 bytes apart (=8 elements away × 8 bytes) in the input. The shape of this dimension is 2." }, { "code": null, "e": 24570, "s": 24565, "text": "Code" }, { "code": null, "e": 24819, "s": 24570, "text": ">>> x = np.asarray(range(1,17), np.int64)>>> as_strided(x, shape=(2,2,2,2), strides=(64,32,16,8))array([[[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]], [[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]])" }, { "code": null, "e": 24830, "s": 24819, "text": "Similar to" }, { "code": null, "e": 25004, "s": 24830, "text": ">>> x.reshape(2,2,2,2)array([[[[ 1, 2], [ 3, 4]], [[ 5, 6], [ 7, 8]]], [[[ 9, 10], [11, 12]], [[13, 14], [15, 16]]]])" }, { "code": null, "e": 25767, "s": 25004, "text": "⚠️ While stride tricks give you more control over the resulting NumPy view, the API is not memory-safe — things can get pretty nasty if you miscalculate the itemsize (honestly I think this API should not allow client code to have to deal with item size as I haven’t seen any benefits of exposing this) or the shape or the existing strides, returning data that is actually not the initial array you created, but from a different array altogether which you probably defined few lines back 😱. This is known as buffer overflow and it’s not hard to encounter this using the stride tricks API. What’s worse is when you decide to write to this data 😱😱. It is for this reason that the stride tricks documentation cautions the user to exercise extreme care when using it." }, { "code": null, "e": 25977, "s": 25767, "text": "Understanding the stride tricks API can be challenging, and I had problems with that. However, the trick (no pun intended) is to start with smaller dimensions and visualise the output of the tensors. Have fun!" }, { "code": null, "e": 26078, "s": 25977, "text": "Found a mistake? Let me know in the comments! :) Shoutout to David Chong for reviewing this article." }, { "code": null, "e": 26264, "s": 26078, "text": "If you like my content and haven’t already subscribed to Medium, subscribe via my referral link here! NOTE: A portion of your membership fees will be apportioned to me as referral fees." }, { "code": null, "e": 26310, "s": 26264, "text": "The N-dimensional array (ndarray) (numpy.org)" }, { "code": null, "e": 26346, "s": 26310, "text": "Advanced NumPy (scipy-lectures.org)" }, { "code": null, "e": 26399, "s": 26346, "text": "An Illustrated Guide to Shape and Strides (ajcr.net)" } ]
What does ** (double star) and * (star) do for parameters in Python?
In Python function, an argument with single asterisk (star) prefixed to it helps in receiving variable number of argument from calling environment >>> def function(*arg): for i in arg: print (i) >>> function(1,2,3,4,5) 1 2 3 4 5 Argument with double asterisks (stars) is used in function definition when variable number of keyword arguments have to be passed to a function >>> def function(**arg): for i in arg: print (i,arg[i]) >>> function(a=1, b=2, c=3, d=4) a 1 b 2 c 3 d 4 In Python 3, it is possible to define a variable with asterisk in assignment statement to enable extended unpacking of iterables. >>> a,*b=[1,2,3,4] >>> a 1 >>> b [2, 3, 4] >>> a,*b,c=[1,2,3,4] >>> a 1 >>> b [2, 3] >>> c 4
[ { "code": null, "e": 1209, "s": 1062, "text": "In Python function, an argument with single asterisk (star) prefixed to it helps in receiving variable number of argument from calling environment" }, { "code": null, "e": 1306, "s": 1209, "text": ">>> def function(*arg):\n for i in arg:\n print (i)\n\n>>> function(1,2,3,4,5)\n1\n2\n3\n4\n5" }, { "code": null, "e": 1450, "s": 1306, "text": "Argument with double asterisks (stars) is used in function definition when variable number of keyword arguments have to be passed to a function" }, { "code": null, "e": 1571, "s": 1450, "text": ">>> def function(**arg):\n for i in arg:\n print (i,arg[i])\n\n\n>>> function(a=1, b=2, c=3, d=4)\na 1\nb 2\nc 3\nd 4" }, { "code": null, "e": 1701, "s": 1571, "text": "In Python 3, it is possible to define a variable with asterisk in assignment statement to enable extended unpacking of iterables." }, { "code": null, "e": 1794, "s": 1701, "text": ">>> a,*b=[1,2,3,4]\n>>> a\n1\n>>> b\n[2, 3, 4]\n>>> a,*b,c=[1,2,3,4]\n>>> a\n1\n>>> b\n[2, 3]\n>>> c\n4" } ]
Connell sequence in Python
Suppose we have a number n, we have to find the nth term of Connell sequence. The Connell sequence is as follows: 1. Take first odd integer: 1 2. Take next two even integers 2, 4 3. Then take the next three odd integers 5, 7, 9 4. After that take the next four even integers 10, 12, 14, 16 And so on. So, if the input is like 12, then the output will be 21 To solve this, we will follow these steps − i := 1 while quotient of (i *(i + 1) / 2) < n + 1, doi := i + 1 i := i + 1 idx := i *(i + 1) / 2, take only quotient num := i^2 return num - 2 *(idx - n - 1) Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, n): i = 1 while (i * (i + 1) // 2) < n + 1: i += 1 idx = i * (i + 1) // 2 num = i**2 return num - 2 * (idx - n - 1) ob = Solution() print(ob.solve(12)) 12 21
[ { "code": null, "e": 1363, "s": 1062, "text": "Suppose we have a number n, we have to find the nth term of Connell sequence. The Connell\nsequence is as follows: 1. Take first odd integer: 1 2. Take next two even integers 2, 4 3. Then\ntake the next three odd integers 5, 7, 9 4. After that take the next four even integers 10, 12, 14,\n16 And so on." }, { "code": null, "e": 1419, "s": 1363, "text": "So, if the input is like 12, then the output will be 21" }, { "code": null, "e": 1463, "s": 1419, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1470, "s": 1463, "text": "i := 1" }, { "code": null, "e": 1527, "s": 1470, "text": "while quotient of (i *(i + 1) / 2) < n + 1, doi := i + 1" }, { "code": null, "e": 1538, "s": 1527, "text": "i := i + 1" }, { "code": null, "e": 1580, "s": 1538, "text": "idx := i *(i + 1) / 2, take only quotient" }, { "code": null, "e": 1591, "s": 1580, "text": "num := i^2" }, { "code": null, "e": 1621, "s": 1591, "text": "return num - 2 *(idx - n - 1)" }, { "code": null, "e": 1691, "s": 1621, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1702, "s": 1691, "text": " Live Demo" }, { "code": null, "e": 1925, "s": 1702, "text": "class Solution:\n def solve(self, n):\n i = 1\n while (i * (i + 1) // 2) < n + 1:\n i += 1\n idx = i * (i + 1) // 2\n num = i**2\n return num - 2 * (idx - n - 1)\nob = Solution()\nprint(ob.solve(12))" }, { "code": null, "e": 1928, "s": 1925, "text": "12" }, { "code": null, "e": 1931, "s": 1928, "text": "21" } ]
JavaScript | Spread Operator - GeeksforGeeks
21 Jul, 2021 Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is same as Rest parameter but it works completely opposite of it. Syntax: var variablename1 = [...value]; In the above syntax, ... is spread operator which will target all values in particular variable. When ... occurs in function call or alike,its called a spread operator. Spread operator can be used in many cases,like when we want to expand,copy,concat,with math object. Let’s look at each of them one by one: Note: In order to run the code in this article make use of the console provided by the browser. Concat() The concat() method provided by javascript helps in concatenation of two or more strings(String concat() ) or is used to merge two or more arrays. In case of arrays,this method does not change the existing arrays but instead returns a new array. // normal array concat() methodlet arr = [1,2,3];let arr2 = [4,5]; arr = arr.concat(arr2); console.log(arr); // [ 1, 2, 3, 4, 5 ] Output:We can achieve the same output with the help of the spread operator, the code will look something like this: // spread operator doing the concat joblet arr = [1,2,3];let arr2 = [4,5]; arr = [...arr,...arr2];console.log(arr); // [ 1, 2, 3, 4, 5 ] Output:Note: Though we can achieve the same result, but it is not recommended to use the spread in this particular case, as for a large data set it will work slower as when compared to the native concat() method. Copy(like splice method) In order to copy the content of array to another we can do something like this: // copying without the spread operatorlet arr = ['a','b','c'];let arr2 = arr; console.log(arr2); // [ 'a', 'b', 'c' ] Output: The above code works fine because we can copy the contents of one array to another, but under the hood, it’s very different as when we mutate new array it will also affect the old array(the one which we copied). See the code below: // changed the original arraylet arr = ['a','b','c'];let arr2 = arr; arr2.push('d'); console.log(arr2);console.log(arr); // even affected the original array(arr) Output: In the above code we can clearly see that when we tried to insert an element inside the array, the original array is also altered which we didn’t intended and is not recommended. We can make use of the spread operator in this case, like this: // spread operator for copying let arr = ['a','b','c'];let arr2 = [...arr]; console.log(arr); // [ 'a', 'b', 'c' ] arr2.push('d'); //inserting an element at the end of arr2 console.log(arr2); // [ 'a', 'b', 'c', 'd' ]console.log(arr); // [ 'a', 'b', 'c' ] Output: By using the spread operator we made sure that the original array is not affected whenever we alter the new array. Expand Whenever we want to expand an array into another we do something like this: // normally used expand methodlet arr = ['a','b'];let arr2 = [arr,'c','d']; console.log(arr2); // [ [ 'a', 'b' ], 'c', 'd' ] Output:Even though we get the content on one array inside the other one, but actually it is array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator. // expand using spread operator let arr = ['a','b'];let arr2 = [...arr,'c','d']; console.log(arr2); // [ 'a', 'b', 'c', 'd' ] Output: Math The Math object in javascript has different properties that we can make use of to do what we want like finding the minimum from a list of numbers, finding maximum etc. Consider the case that we want to find the minimum from a list of numbers,we will write something like this: console.log(Math.min(1,2,3,-1)); //-1 Output:Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like: // min in an array using Math.min()let arr = [1,2,3,-1];console.log(Math.min(arr)); //NaN Output:When ...arr is used in the function call, it “expands” an iterable object arr into the list of argumentsIn order to avoid this NaN output, we make use of spread operator, like: // with spread let arr = [1,2,3,-1]; console.log(Math.min(...arr)); //-1 Output: Example of spread operator with objects ES6 has added spread property to object literals in javascript. The spread operator (...) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take at an example of how to use the spread operator on an object, const user1 = { name: 'Jen', age: 22}; const clonedUser = { ...user1 };console.log(clonedUser); Output: Here we are spreading the user1 object. All key-value pairs of the user1 object are copied into the clonedUser object. Let’s look on another example of merging two objects using the spread operator, const user1 = { name: 'Jen', age: 22,}; const user2 = { name: "Andrew", location: "Philadelphia" }; const mergedUsers = {...user1, ...user2};console.log(mergedUsers) Output: mergedUsers is a copy of user1 and user2. Actually, every enumerable property on the objects will be copied to mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, they are some differences between the two. JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. immukul pranav1698 javascript-operators JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Hide or show elements in HTML using display property JavaScript | console.log() with Examples How to read a local text file using JavaScript?
[ { "code": null, "e": 29691, "s": 29663, "text": "\n21 Jul, 2021" }, { "code": null, "e": 30032, "s": 29691, "text": "Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array. Syntax of Spread operator is same as Rest parameter but it works completely opposite of it." }, { "code": null, "e": 30040, "s": 30032, "text": "Syntax:" }, { "code": null, "e": 30073, "s": 30040, "text": "var variablename1 = [...value]; " }, { "code": null, "e": 30381, "s": 30073, "text": "In the above syntax, ... is spread operator which will target all values in particular variable. When ... occurs in function call or alike,its called a spread operator. Spread operator can be used in many cases,like when we want to expand,copy,concat,with math object. Let’s look at each of them one by one:" }, { "code": null, "e": 30477, "s": 30381, "text": "Note: In order to run the code in this article make use of the console provided by the browser." }, { "code": null, "e": 30486, "s": 30477, "text": "Concat()" }, { "code": null, "e": 30732, "s": 30486, "text": "The concat() method provided by javascript helps in concatenation of two or more strings(String concat() ) or is used to merge two or more arrays. In case of arrays,this method does not change the existing arrays but instead returns a new array." }, { "code": "// normal array concat() methodlet arr = [1,2,3];let arr2 = [4,5]; arr = arr.concat(arr2); console.log(arr); // [ 1, 2, 3, 4, 5 ]", "e": 30864, "s": 30732, "text": null }, { "code": null, "e": 30980, "s": 30864, "text": "Output:We can achieve the same output with the help of the spread operator, the code will look something like this:" }, { "code": "// spread operator doing the concat joblet arr = [1,2,3];let arr2 = [4,5]; arr = [...arr,...arr2];console.log(arr); // [ 1, 2, 3, 4, 5 ]", "e": 31118, "s": 30980, "text": null }, { "code": null, "e": 31331, "s": 31118, "text": "Output:Note: Though we can achieve the same result, but it is not recommended to use the spread in this particular case, as for a large data set it will work slower as when compared to the native concat() method." }, { "code": null, "e": 31356, "s": 31331, "text": "Copy(like splice method)" }, { "code": null, "e": 31436, "s": 31356, "text": "In order to copy the content of array to another we can do something like this:" }, { "code": "// copying without the spread operatorlet arr = ['a','b','c'];let arr2 = arr; console.log(arr2); // [ 'a', 'b', 'c' ]", "e": 31555, "s": 31436, "text": null }, { "code": null, "e": 31563, "s": 31555, "text": "Output:" }, { "code": null, "e": 31795, "s": 31563, "text": "The above code works fine because we can copy the contents of one array to another, but under the hood, it’s very different as when we mutate new array it will also affect the old array(the one which we copied). See the code below:" }, { "code": "// changed the original arraylet arr = ['a','b','c'];let arr2 = arr; arr2.push('d'); console.log(arr2);console.log(arr); // even affected the original array(arr) ", "e": 31960, "s": 31795, "text": null }, { "code": null, "e": 31968, "s": 31960, "text": "Output:" }, { "code": null, "e": 32211, "s": 31968, "text": "In the above code we can clearly see that when we tried to insert an element inside the array, the original array is also altered which we didn’t intended and is not recommended. We can make use of the spread operator in this case, like this:" }, { "code": "// spread operator for copying let arr = ['a','b','c'];let arr2 = [...arr]; console.log(arr); // [ 'a', 'b', 'c' ] arr2.push('d'); //inserting an element at the end of arr2 console.log(arr2); // [ 'a', 'b', 'c', 'd' ]console.log(arr); // [ 'a', 'b', 'c' ]", "e": 32470, "s": 32211, "text": null }, { "code": null, "e": 32478, "s": 32470, "text": "Output:" }, { "code": null, "e": 32593, "s": 32478, "text": "By using the spread operator we made sure that the original array is not affected whenever we alter the new array." }, { "code": null, "e": 32600, "s": 32593, "text": "Expand" }, { "code": null, "e": 32676, "s": 32600, "text": "Whenever we want to expand an array into another we do something like this:" }, { "code": "// normally used expand methodlet arr = ['a','b'];let arr2 = [arr,'c','d']; console.log(arr2); // [ [ 'a', 'b' ], 'c', 'd' ]", "e": 32802, "s": 32676, "text": null }, { "code": null, "e": 33053, "s": 32802, "text": "Output:Even though we get the content on one array inside the other one, but actually it is array inside another array which is definitely what we didn’t want. If we want the content to be inside a single array we can make use of the spread operator." }, { "code": "// expand using spread operator let arr = ['a','b'];let arr2 = [...arr,'c','d']; console.log(arr2); // [ 'a', 'b', 'c', 'd' ]", "e": 33181, "s": 33053, "text": null }, { "code": null, "e": 33189, "s": 33181, "text": "Output:" }, { "code": null, "e": 33194, "s": 33189, "text": "Math" }, { "code": null, "e": 33471, "s": 33194, "text": "The Math object in javascript has different properties that we can make use of to do what we want like finding the minimum from a list of numbers, finding maximum etc. Consider the case that we want to find the minimum from a list of numbers,we will write something like this:" }, { "code": "console.log(Math.min(1,2,3,-1)); //-1 ", "e": 33510, "s": 33471, "text": null }, { "code": null, "e": 33639, "s": 33510, "text": "Output:Now consider that we have an array instead of a list, this above Math object method won’t work and will return NaN, like:" }, { "code": "// min in an array using Math.min()let arr = [1,2,3,-1];console.log(Math.min(arr)); //NaN", "e": 33729, "s": 33639, "text": null }, { "code": null, "e": 33913, "s": 33729, "text": "Output:When ...arr is used in the function call, it “expands” an iterable object arr into the list of argumentsIn order to avoid this NaN output, we make use of spread operator, like:" }, { "code": "// with spread let arr = [1,2,3,-1]; console.log(Math.min(...arr)); //-1", "e": 33987, "s": 33913, "text": null }, { "code": null, "e": 33995, "s": 33987, "text": "Output:" }, { "code": null, "e": 34035, "s": 33995, "text": "Example of spread operator with objects" }, { "code": null, "e": 34336, "s": 34035, "text": "ES6 has added spread property to object literals in javascript. The spread operator (...) with objects is used to create copies of existing objects with new or updated values or to make a copy of an object with more properties. Let’s take at an example of how to use the spread operator on an object," }, { "code": "const user1 = { name: 'Jen', age: 22}; const clonedUser = { ...user1 };console.log(clonedUser);", "e": 34439, "s": 34336, "text": null }, { "code": null, "e": 34447, "s": 34439, "text": "Output:" }, { "code": null, "e": 34646, "s": 34447, "text": "Here we are spreading the user1 object. All key-value pairs of the user1 object are copied into the clonedUser object. Let’s look on another example of merging two objects using the spread operator," }, { "code": "const user1 = { name: 'Jen', age: 22,}; const user2 = { name: \"Andrew\", location: \"Philadelphia\" }; const mergedUsers = {...user1, ...user2};console.log(mergedUsers)", "e": 34826, "s": 34646, "text": null }, { "code": null, "e": 34834, "s": 34826, "text": "Output:" }, { "code": null, "e": 35084, "s": 34834, "text": "mergedUsers is a copy of user1 and user2. Actually, every enumerable property on the objects will be copied to mergedUsers object. The spread operator is just a shorthand for the Object.assign() method but, they are some differences between the two." }, { "code": null, "e": 35303, "s": 35084, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 35311, "s": 35303, "text": "immukul" }, { "code": null, "e": 35322, "s": 35311, "text": "pranav1698" }, { "code": null, "e": 35343, "s": 35322, "text": "javascript-operators" }, { "code": null, "e": 35354, "s": 35343, "text": "JavaScript" }, { "code": null, "e": 35452, "s": 35354, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35461, "s": 35452, "text": "Comments" }, { "code": null, "e": 35474, "s": 35461, "text": "Old Comments" }, { "code": null, "e": 35535, "s": 35474, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 35580, "s": 35535, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35652, "s": 35580, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 35721, "s": 35652, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35748, "s": 35721, "text": "File uploading in React.js" }, { "code": null, "e": 35800, "s": 35748, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 35846, "s": 35800, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 35899, "s": 35846, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35940, "s": 35899, "text": "JavaScript | console.log() with Examples" } ]
Pair with a given sum in BST | Set 2 - GeeksforGeeks
18 Aug, 2021 Given a binary search tree, and an integer X, the task is to check if there exists a pair of distinct nodes in BST with sum equal to X. If yes then print Yes else print No. Examples: Input: X = 5 5 / \ 3 7 / \ / \ 2 4 6 8 Output: Yes 2 + 3 = 5. Thus, the answer is "Yes" Input: X = 10 1 \ 2 \ 3 \ 4 \ 5 Output: No Approach: We have already discussed a hash based approach in this article. The space complexity of this is O(N) where N is the number of nodes in BST. In this article, we will solve the same problem using a space efficient method by reducing the space complexity to O(H) where H is the height of BST. For that, we will use two pointer technique on BST. Thus, we will maintain a forward and a backward iterator that will iterate the BST in the order of in-order and reverse in-order traversal respectively. Following are the steps to solve the problem: Create a forward and backward iterator for BST. Let’s say the value of nodes they are pointing at are v1 and v2.Now at each step, If v1 + v2 = X, we found a pair.If v1 + v2 < x, we will make forward iterator point to the next element.If v1 + v2 > x, we will make backward iterator point to the previous element.If we find no such pair, answer will be “No”. Create a forward and backward iterator for BST. Let’s say the value of nodes they are pointing at are v1 and v2. Now at each step, If v1 + v2 = X, we found a pair.If v1 + v2 < x, we will make forward iterator point to the next element.If v1 + v2 > x, we will make backward iterator point to the previous element. If v1 + v2 = X, we found a pair. If v1 + v2 < x, we will make forward iterator point to the next element. If v1 + v2 > x, we will make backward iterator point to the previous element. If we find no such pair, answer will be “No”. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to find a pair with given sumbool existsPair(node* root, int x){ // Iterators for BST stack<node *> it1, it2; // Initializing forward iterator node* c = root; while (c != NULL) it1.push(c), c = c->left; // Initializing backward iterator c = root; while (c != NULL) it2.push(c), c = c->right; // Two pointer technique while (it1.top() != it2.top()) { // Variables to store values at // it1 and it2 int v1 = it1.top()->data, v2 = it2.top()->data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.top()->right; it1.pop(); while (c != NULL) it1.push(c), c = c->left; } // Moving backward pointer else { c = it2.top()->left; it2.pop(); while (c != NULL) it2.push(c), c = c->right; } } // Case when no pair is found return false;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) cout << "Yes"; else cout << "No"; return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to find a pair with given sumstatic boolean existsPair(node root, int x){ // Iterators for BST Stack<node > it1 = new Stack<node>(), it2 = new Stack<node>(); // Initializing forward iterator node c = root; while (c != null) { it1.push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.push(c); c = c.right; } // Two pointer technique while (it1.peek() != it2.peek()) { // Variables to store values at // it1 and it2 int v1 = it1.peek().data, v2 = it2.peek().data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.peek().right; it1.pop(); while (c != null) { it1.push(c); c = c.left; } } // Moving backward pointer else { c = it2.peek().left; it2.pop(); while (c != null) { it2.push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) System.out.print("Yes"); else System.out.print("No"); }} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Node of the binary treeclass node: def __init__ (self, key): self.data = key self.left = None self.right = None # Function that returns true if a pair# with given sum exists in the given BSTsdef existsPair(root1, x): # Stack to store nodes for forward # and backward iterator it1, it2 = [], [] # Initializing forward iterator c = root1 while (c != None): it1.append(c) c = c.left # Initializing backward iterator c = root1 while (c != None): it2.append(c) c = c.right # Two pointer technique while (it1[-1] != it2[-1]): # To store the value of the nodes # current iterators are pointing to v1 = it1[-1].data v2 = it2[-1].data # Base case if (v1 + v2 == x): return True # Moving forward iterator if (v1 + v2 < x): c = it1[-1].right del it1[-1] while (c != None): it1.append(c) c = c.left # Moving backward iterator else: c = it2[-1].left del it2[-1] while (c != None): it2.append(c) c = c.right # If no such pair found return False # Driver codeif __name__ == '__main__': root2 = node(5) root2.left = node(3) root2.right = node(7) root2.left.left = node(2) root2.left.right = node(4) root2.right.left = node(6) root2.right.right = node(8) x = 5 # Calling required function if (existsPair(root2, x)): print("Yes") else: print("No") # This code is contributed by mohit kumar 29 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to find a pair with given sumstatic bool existsPair(node root, int x){ // Iterators for BST Stack<node > it1 = new Stack<node>(), it2 = new Stack<node>(); // Initializing forward iterator node c = root; while (c != null) { it1.Push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.Push(c); c = c.right; } // Two pointer technique while (it1.Peek() != it2.Peek()) { // Variables to store values at // it1 and it2 int v1 = it1.Peek().data, v2 = it2.Peek().data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.Peek().right; it1.Pop(); while (c != null) { it1.Push(c); c = c.left; } } // Moving backward pointer else { c = it2.Peek().left; it2.Pop(); while (c != null) { it2.Push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Function to find a pair with given sumfunction existsPair(root, x){ // Iterators for BST let it1 = [], it2 = []; // Initializing forward iterator let c = root; while (c != null) { it1.push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.push(c); c = c.right; } // Two pointer technique while (it1[it1.length-1] != it2[it2.length-1]) { // Variables to store values at // it1 and it2 let v1 = it1[it1.length - 1].data, v2 = it2[it2.length - 1].data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1[it1.length - 1].right; it1.pop(); while (c != null) { it1.push(c); c = c.left; } } // Moving backward pointer else { c = it2[it2.length - 1].left; it2.pop(); while (c != null) { it2.push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); let x = 5; // Calling required functionif (existsPair(root, x)) document.write("Yes");else document.write("No"); // This code is contributed by unknown2108 </script> Yes Time Complexity: O(N). Auxiliary Space: O(N). 29AjayKumar Rajput-Ji mohit kumar 29 unknown2108 pankajsharmagfg Binary Search Tree Data Structures Graph Tree Data Structures Graph Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments set vs unordered_set in C++ STL Construct a Binary Search Tree from given postorder Construct BST from given preorder traversal | Set 2 Find the largest BST subtree in a given Binary Tree | Set 1 Red Black Tree vs AVL Tree SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews DSA Sheet by Love Babbar Doubly Linked List | Set 1 (Introduction and Insertion) Implementing a Linked List in Java using Class
[ { "code": null, "e": 25146, "s": 25118, "text": "\n18 Aug, 2021" }, { "code": null, "e": 25319, "s": 25146, "text": "Given a binary search tree, and an integer X, the task is to check if there exists a pair of distinct nodes in BST with sum equal to X. If yes then print Yes else print No." }, { "code": null, "e": 25330, "s": 25319, "text": "Examples: " }, { "code": null, "e": 25604, "s": 25330, "text": "Input: X = 5\n 5 \n / \\ \n 3 7 \n / \\ / \\ \n 2 4 6 8\nOutput: Yes\n2 + 3 = 5. Thus, the answer is \"Yes\"\n\nInput: X = 10\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\nOutput: No" }, { "code": null, "e": 25755, "s": 25604, "text": "Approach: We have already discussed a hash based approach in this article. The space complexity of this is O(N) where N is the number of nodes in BST." }, { "code": null, "e": 26157, "s": 25755, "text": "In this article, we will solve the same problem using a space efficient method by reducing the space complexity to O(H) where H is the height of BST. For that, we will use two pointer technique on BST. Thus, we will maintain a forward and a backward iterator that will iterate the BST in the order of in-order and reverse in-order traversal respectively. Following are the steps to solve the problem: " }, { "code": null, "e": 26514, "s": 26157, "text": "Create a forward and backward iterator for BST. Let’s say the value of nodes they are pointing at are v1 and v2.Now at each step, If v1 + v2 = X, we found a pair.If v1 + v2 < x, we will make forward iterator point to the next element.If v1 + v2 > x, we will make backward iterator point to the previous element.If we find no such pair, answer will be “No”." }, { "code": null, "e": 26627, "s": 26514, "text": "Create a forward and backward iterator for BST. Let’s say the value of nodes they are pointing at are v1 and v2." }, { "code": null, "e": 26827, "s": 26627, "text": "Now at each step, If v1 + v2 = X, we found a pair.If v1 + v2 < x, we will make forward iterator point to the next element.If v1 + v2 > x, we will make backward iterator point to the previous element." }, { "code": null, "e": 26860, "s": 26827, "text": "If v1 + v2 = X, we found a pair." }, { "code": null, "e": 26933, "s": 26860, "text": "If v1 + v2 < x, we will make forward iterator point to the next element." }, { "code": null, "e": 27011, "s": 26933, "text": "If v1 + v2 > x, we will make backward iterator point to the previous element." }, { "code": null, "e": 27057, "s": 27011, "text": "If we find no such pair, answer will be “No”." }, { "code": null, "e": 27109, "s": 27057, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27113, "s": 27109, "text": "C++" }, { "code": null, "e": 27118, "s": 27113, "text": "Java" }, { "code": null, "e": 27126, "s": 27118, "text": "Python3" }, { "code": null, "e": 27129, "s": 27126, "text": "C#" }, { "code": null, "e": 27140, "s": 27129, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Node of the binary treestruct node { int data; node* left; node* right; node(int data) { this->data = data; left = NULL; right = NULL; }}; // Function to find a pair with given sumbool existsPair(node* root, int x){ // Iterators for BST stack<node *> it1, it2; // Initializing forward iterator node* c = root; while (c != NULL) it1.push(c), c = c->left; // Initializing backward iterator c = root; while (c != NULL) it2.push(c), c = c->right; // Two pointer technique while (it1.top() != it2.top()) { // Variables to store values at // it1 and it2 int v1 = it1.top()->data, v2 = it2.top()->data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.top()->right; it1.pop(); while (c != NULL) it1.push(c), c = c->left; } // Moving backward pointer else { c = it2.top()->left; it2.pop(); while (c != NULL) it2.push(c), c = c->right; } } // Case when no pair is found return false;} // Driver codeint main(){ node* root = new node(5); root->left = new node(3); root->right = new node(7); root->left->left = new node(2); root->left->right = new node(4); root->right->left = new node(6); root->right->right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) cout << \"Yes\"; else cout << \"No\"; return 0;}", "e": 28833, "s": 27140, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Node of the binary treestatic class node{ int data; node left; node right; node(int data) { this.data = data; left = null; right = null; }}; // Function to find a pair with given sumstatic boolean existsPair(node root, int x){ // Iterators for BST Stack<node > it1 = new Stack<node>(), it2 = new Stack<node>(); // Initializing forward iterator node c = root; while (c != null) { it1.push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.push(c); c = c.right; } // Two pointer technique while (it1.peek() != it2.peek()) { // Variables to store values at // it1 and it2 int v1 = it1.peek().data, v2 = it2.peek().data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.peek().right; it1.pop(); while (c != null) { it1.push(c); c = c.left; } } // Moving backward pointer else { c = it2.peek().left; it2.pop(); while (c != null) { it2.push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codepublic static void main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }} // This code is contributed by 29AjayKumar", "e": 30773, "s": 28833, "text": null }, { "code": "# Python3 implementation of the approach # Node of the binary treeclass node: def __init__ (self, key): self.data = key self.left = None self.right = None # Function that returns true if a pair# with given sum exists in the given BSTsdef existsPair(root1, x): # Stack to store nodes for forward # and backward iterator it1, it2 = [], [] # Initializing forward iterator c = root1 while (c != None): it1.append(c) c = c.left # Initializing backward iterator c = root1 while (c != None): it2.append(c) c = c.right # Two pointer technique while (it1[-1] != it2[-1]): # To store the value of the nodes # current iterators are pointing to v1 = it1[-1].data v2 = it2[-1].data # Base case if (v1 + v2 == x): return True # Moving forward iterator if (v1 + v2 < x): c = it1[-1].right del it1[-1] while (c != None): it1.append(c) c = c.left # Moving backward iterator else: c = it2[-1].left del it2[-1] while (c != None): it2.append(c) c = c.right # If no such pair found return False # Driver codeif __name__ == '__main__': root2 = node(5) root2.left = node(3) root2.right = node(7) root2.left.left = node(2) root2.left.right = node(4) root2.right.left = node(6) root2.right.right = node(8) x = 5 # Calling required function if (existsPair(root2, x)): print(\"Yes\") else: print(\"No\") # This code is contributed by mohit kumar 29", "e": 32496, "s": 30773, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Node of the binary treepublic class node{ public int data; public node left; public node right; public node(int data) { this.data = data; left = null; right = null; }}; // Function to find a pair with given sumstatic bool existsPair(node root, int x){ // Iterators for BST Stack<node > it1 = new Stack<node>(), it2 = new Stack<node>(); // Initializing forward iterator node c = root; while (c != null) { it1.Push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.Push(c); c = c.right; } // Two pointer technique while (it1.Peek() != it2.Peek()) { // Variables to store values at // it1 and it2 int v1 = it1.Peek().data, v2 = it2.Peek().data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1.Peek().right; it1.Pop(); while (c != null) { it1.Push(c); c = c.left; } } // Moving backward pointer else { c = it2.Peek().left; it2.Pop(); while (c != null) { it2.Push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codepublic static void Main(String[] args){ node root = new node(5); root.left = new node(3); root.right = new node(7); root.left.left = new node(2); root.left.right = new node(4); root.right.left = new node(6); root.right.right = new node(8); int x = 5; // Calling required function if (existsPair(root, x)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by Rajput-Ji", "e": 34504, "s": 32496, "text": null }, { "code": "<script> // Javascript implementation of the approach // Node of the binary treeclass node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Function to find a pair with given sumfunction existsPair(root, x){ // Iterators for BST let it1 = [], it2 = []; // Initializing forward iterator let c = root; while (c != null) { it1.push(c); c = c.left; } // Initializing backward iterator c = root; while (c != null) { it2.push(c); c = c.right; } // Two pointer technique while (it1[it1.length-1] != it2[it2.length-1]) { // Variables to store values at // it1 and it2 let v1 = it1[it1.length - 1].data, v2 = it2[it2.length - 1].data; // Base case if (v1 + v2 == x) return true; // Moving forward pointer if (v1 + v2 < x) { c = it1[it1.length - 1].right; it1.pop(); while (c != null) { it1.push(c); c = c.left; } } // Moving backward pointer else { c = it2[it2.length - 1].left; it2.pop(); while (c != null) { it2.push(c); c = c.right; } } } // Case when no pair is found return false;} // Driver codelet root = new node(5);root.left = new node(3);root.right = new node(7);root.left.left = new node(2);root.left.right = new node(4);root.right.left = new node(6);root.right.right = new node(8); let x = 5; // Calling required functionif (existsPair(root, x)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by unknown2108 </script>", "e": 36335, "s": 34504, "text": null }, { "code": null, "e": 36339, "s": 36335, "text": "Yes" }, { "code": null, "e": 36390, "s": 36341, "text": "Time Complexity: O(N). Auxiliary Space: O(N). " }, { "code": null, "e": 36402, "s": 36390, "text": "29AjayKumar" }, { "code": null, "e": 36412, "s": 36402, "text": "Rajput-Ji" }, { "code": null, "e": 36427, "s": 36412, "text": "mohit kumar 29" }, { "code": null, "e": 36439, "s": 36427, "text": "unknown2108" }, { "code": null, "e": 36455, "s": 36439, "text": "pankajsharmagfg" }, { "code": null, "e": 36474, "s": 36455, "text": "Binary Search Tree" }, { "code": null, "e": 36490, "s": 36474, "text": "Data Structures" }, { "code": null, "e": 36496, "s": 36490, "text": "Graph" }, { "code": null, "e": 36501, "s": 36496, "text": "Tree" }, { "code": null, "e": 36517, "s": 36501, "text": "Data Structures" }, { "code": null, "e": 36523, "s": 36517, "text": "Graph" }, { "code": null, "e": 36542, "s": 36523, "text": "Binary Search Tree" }, { "code": null, "e": 36547, "s": 36542, "text": "Tree" }, { "code": null, "e": 36645, "s": 36547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36654, "s": 36645, "text": "Comments" }, { "code": null, "e": 36667, "s": 36654, "text": "Old Comments" }, { "code": null, "e": 36699, "s": 36667, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 36751, "s": 36699, "text": "Construct a Binary Search Tree from given postorder" }, { "code": null, "e": 36803, "s": 36751, "text": "Construct BST from given preorder traversal | Set 2" }, { "code": null, "e": 36863, "s": 36803, "text": "Find the largest BST subtree in a given Binary Tree | Set 1" }, { "code": null, "e": 36890, "s": 36863, "text": "Red Black Tree vs AVL Tree" }, { "code": null, "e": 36939, "s": 36890, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36983, "s": 36939, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 37008, "s": 36983, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37064, "s": 37008, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" } ]
Solving business usecases by recommender system using lightFM | by Aayush Agrawal | Towards Data Science
In this post, I am going to write about Recommender systems, how they are used in many e-commerce websites. The post will also cover about building simple recommender system models using Matrix Factorization algorithm using lightFM package and my recommender system cookbook. The post will focus on business use cases and simple implementations. The post only cover basic intuition around algorithms and will provide links to resources if you want to understand the math behind the algorithm. I am an avid reader and a believer in open source education and continuously expand my knowledge around data science & computer science using online courses, blogs, Github repositories and participating in data science competitions. While searching for quality content on the internet, I have come across various learning links which either focus on the implementation of the algorithm using specific data/modeling technique in ABC language or focus on business impact/results using the broad concept of a family of algorithms(like classification, forecasting, recommender systems etc.) but don’t go into details of how to do it. So the idea is to write some blogs which can combine both business use cases with codes & algorithmic intuition to provide a holistic view of how data science is used in business scenarios. As the world is becoming more digital, we are already getting used to a lot of personalized experience and the algorithm which help us achieve this falls in the family of recommender systems. Almost every web-based platform is using some recommender system to provide customized content. Following are the companies I admire the most. Personalization is a technique of dynamically tailoring your content based on needs of each user. Simple examples of personalization could be movie recommendation on Netflix, personalized email targeting/re-targeting by e-commerce platforms, item recommendation on Amazon, etc. Personalization helps us achieve these four Rs - Recognize: Know customer’s and prospects’ profiles, including demographics, geography, and expressed and shared interests. Remember: Recall customers’ history, primarily how they act as expressed by what they browse and buy Reach: Deliver the right promotion, content, recommendation for a customer based on actions, preferences, and interests Relevance: Deliver personalization within the context of the digital experience based on who customers are, where they are located and what time of year it is Personalization has a lot of benefits for both users and companies. For users, it makes their life easy as they only get to see more relevant stuff to them (unless it’s an advertisement, even they are personalized). For business benefits are countless but here are few which I would like to mention - Enhance customer experience: Personalization reduces the clutter and enhances the customer experience by showing relevant content Cross-sell/ Up-sell opportunities: Relevant product offerings based on customer preferences can lead to increasing products visibility and eventually selling more products Increased basket size: Personalized experience and targeting ultimately leads to increased basket size and frequent purchases Increased customer loyalty: In the digital world, customer retention/loyalty is the most prominent problem faced by many companies as finding a replacement for a particular service is quite easy. According to a Forbes article, Forty-four percent of consumers say they will likely repeat after a personalized experience Matrix factorization is one of the algorithms from recommender systems family and as the name suggests it factorize a matrix, i.e., decompose a matrix in two(or more) matrices such that once you multiply them you get your original matrix back. In case of the recommendation system, we will typically start with an interaction/rating matrix between users and items and matrix factorization algorithm will decompose this matrix in user and item feature matrix which is also known as embeddings. Example of interaction matrix would be user-movie ratings for movie recommender, user-product purchase flag for transaction data, etc. Typically user/item embeddings capture latent features about attributes of users and item respectively. Essentially, latent features are the representation of user/item in an arbitrary space which represents how a user rate a movie. In the example of a movie recommender, an example of user embedding might represent affinity of a user to watch serious kind of movie when the value of the latent feature is high and comedy type of movie when the value is low. Similarly, a movie latent feature may have a high value when the movie is more male driven and when it’s more female-driven the value is typically low. For more information on matrix factorization and factorization machines you can read these articles — Matrix Factorization: A Simple Tutorial and Implementation in Python Introductory Guide — Factorization Machines & their application on huge datasets (with codes in Python) In the hands-on section, we will be building recommender system for different scenarios which we typically see in many companies using LightFM package and MovieLens data. We are using small size data which contains 100,000 ratings and 1,300 tag applications applied to 9,000 movies by 700 users Let’s start by importing data, recommender system cookbook and preprocessing cookbook files for this hands-on section. I have written these reusable generic cookbook codes to increase productivity and write clean/modular codes; you will see we can build a recommender system using 10–15 lines of code by using these cookbooks(do more with less!). # Importing Libraries and cookbooksfrom recsys import * ## recommender system cookbookfrom generic_preprocessing import * ## pre-processing codefrom IPython.display import HTML ## Setting display options for Ipython Notebook# Importing rating data and having a lookratings = pd.read_csv('./ml-latest-small/ratings.csv')ratings.head() As we can see rating data contain user id, movie id and a rating between 0.5 to 5 with a timestamp representing when the rating was given. # Importing movie data and having a look at first five columnsmovies = pd.read_csv('./ml-latest-small/movies.csv')movies.head() Movie data consist of movie id, their title, and genre they belong. As I mentioned before, to create a recommender system we need to start by creating an interaction matrix. For this task, we will use the create_interaction_matrix function from the recsys cookbook. This function requires you to input a pandas dataframe and necessary information like column name for user id, item id, and rating. It also takes an additional parameter threshold if norm=True which means any rating above the mentioned threshold is considered a positive rating. In our case, we don’t have to normalize our data, but in cases of retail data any purchase of a particular type of item can be considered a positive rating, quantity doesn’t matter. # Creating interaction matrix using rating datainteractions = create_interaction_matrix(df = ratings, user_col = 'userId', item_col = 'movieId', rating_col = 'rating')interactions.head() As we can see the data is created in an interaction format where rows represent each user and columns represent each movie id with ratings as values. We will also create user and item dictionaries to later convert user_id to user_name or movie_id to movie_name by using create_user_dict and create_item dict function. # Create User Dictuser_dict = create_user_dict(interactions=interactions)# Create Item dictmovies_dict = create_item_dict(df = movies, id_col = 'movieId', name_col = 'title') To build a matrix factorization model, we will use the runMF function which will take following input - interaction matrix: Interaction matrix created in the previous section n_components: Number of embedding generated for each user and item loss: We need to define a loss function, in this case, we are using warp loss because we mostly care about the ranking of data, i.e, which items should we show first epoch: Number of times to run n_jobs: Number of cores to use in parallel processing mf_model = runMF(interactions = interactions, n_components = 30, loss = 'warp', epoch = 30, n_jobs = 4) Now we have built our matrix factorization model we can now do some interesting things. There are various use cases which can be solved by using this model for a web platform let’s look into them. In this use case, we want to show a user, items he might be interested in buying/viewing based on his/her interactions done in the past. Typical industry examples for this are like “Deals recommended for you” on Amazon or “Top pics for a user” on Netflix or personalized email campaigns. We can use the sample_recommendation_user function for this case. This functions take matrix factorization model, interaction matrix, user dictionary, item dictionary, user_id and the number of items as input and return the list of item id’s a user may be interested in interacting. ## Calling 10 movie recommendation for user id 11rec_list = sample_recommendation_user(model = mf_model, interactions = interactions, user_id = 11, user_dict = user_dict, item_dict = movies_dict, threshold = 4, nrec_items = 10, show = True)Known Likes:1- The Hunger Games: Catching Fire (2013)2- Gravity (2013)3- Dark Knight Rises, The (2012)4- The Hunger Games (2012)5- Town, The (2010)6- Exit Through the Gift Shop (2010)7- Bank Job, The (2008)8- Departed, The (2006)9- Bourne Identity, The (1988)10- Step Into Liquid (2002)11- SLC Punk! (1998)12- Last of the Mohicans, The (1992)13- Good, the Bad and the Ugly, The (Buono, il brutto, il cattivo, Il) (1966)14- Robin Hood: Prince of Thieves (1991)15- Citizen Kane (1941)16- Trainspotting (1996)17- Pulp Fiction (1994)18- Usual Suspects, The (1995) Recommended Items:1- Dark Knight, The (2008)2- Inception (2010)3- Iron Man (2008)4- Shutter Island (2010)5- Fight Club (1999)6- Avatar (2009)7- Forrest Gump (1994)8- District 9 (2009)9- WALL·E (2008)10- Matrix, The (1999)print(rec_list)[593L, 260L, 110L, 480L, 47L, 527L, 344L, 858L, 231L, 780L] As we can see in this case user is interested in “Dark Knight Rises(2012)” so the first recommendation is “The Dark Knight(2008)”. This user also seems to have a strong liking towards movies in drama, sci-fi and thriller genre and there are many movies recommended in the same genre like Dark Knight(Drama/Crime), Inception(Sci-Fi, Thriller), Iron Man(Sci-FI thriller), Shutter Island(Drame/Thriller), Fight club(drama), Avatar(Sci-fi), Forrest Gump(Drama), District 9(Thriller), Wall-E(Sci-fi), The Matrix(Sci-Fi) Similar models can also be used for building sections like “Based on your recent browsing history” recommendations by just changing the rating matrix only to contain interaction which is recent and based on browsing history visits on specific items. In this use case, we will discuss how we can recommend a list of users specific to a particular item. Example of such cases is when you are running a promotion on an item and want to run an e-mail campaign around this promotional item to only 10,000 users who might be interested in this item. We can use the sample_recommendation_item function for this case. This functions take matrix factorization model, interaction matrix, user dictionary, item dictionary, item_id and the number of users as input and return the list of user id’s who are more likely be interested in the item. ## Calling 15 user recommendation for item id 1sample_recommendation_item(model = mf_model, interactions = interactions, item_id = 1, user_dict = user_dict, item_dict = movies_dict, number_of_user = 15)[116, 410, 449, 657, 448, 633, 172, 109, 513, 44, 498, 459, 317, 415, 495] As you can see function return a list of userID who might be interested in item id 1. Another example why you might need such model is when there is an old inventory sitting in your warehouse which needs to clear up otherwise you might have to write it off, and you want to clear it by giving some discount to users who might be interested in buying. In this use case, we will discuss how we can recommend a list of items specific to a particular item. This kind of models will help you to find similar/related items or items which can be bundled together. Typical industry use case for such models are in cross-selling and up-selling opportunities on product page like “Products related to this item”, “Frequently bought together”, “Customers who bought this also bought this” and “Customers who viewed this item also viewed”. “Customers who bought this also bought this” and “Customers who viewed this item also viewed” can also be solved through market basket analysis. To achieve this use case, we will create a cosine distance matrix using item embeddings generated by matrix factorization model. This will help us calculate similarity b/w items, and then we can recommend top N similar item to an item of interest. First step is to create a item-item distance matrix using the create_item_emdedding_distance_matrix function. This function takes matrix factorization models and interaction matrix as input and returns an item_embedding_distance_matrix. ## Creating item-item distance matrixitem_item_dist = create_item_emdedding_distance_matrix(model = mf_model, interactions = interactions)## Checking item embedding distance matrixitem_item_dist.head() As we can see the matrix have movies as both row and columns and the value represents the cosine distance between them. Next step is to use item_item_recommendation function to get top N items with respect to an item_id. This function takes item embedding distance matrix, item_id, item_dictionary and number of items to be recommended as input and return similar item list as output. ## Calling 10 recommended items for item id rec_list = item_item_recommendation(item_emdedding_distance_matrix = item_item_dist, item_id = 5378, item_dict = movies_dict, n_items = 10)Item of interest :Star Wars: Episode II - Attack of the Clones (2002)Item similar to the above item:1- Star Wars: Episode III - Revenge of the Sith (2005)2- Lord of the Rings: The Two Towers, The (2002)3- Lord of the Rings: The Fellowship of the Ring, The (2001)4- Lord of the Rings: The Return of the King, The (2003)5- Matrix Reloaded, The (2003)6- Harry Potter and the Sorcerer's Stone (a.k.a. Harry Potter and the Philosopher's Stone) (2001)7- Gladiator (2000)8- Spider-Man (2002)9- Minority Report (2002)10- Mission: Impossible II (2000) As we can see for “Star Wars: Episode II — Attack of the Clones (2002)” movie we are getting it’s next released movies which is “Star Wars: Episode III — Revenge of the Sith (2005)” as the first recommendation. Like any other blog, this method isn’t perfect for every application, but the same ideas can work if we use it effectively. There is a lot of advancements in recommender systems with the advent of Deep learning. While there is room for improvement, I am pleased with how it has been working for me so far. I might write about deep learning based recommender systems later sometime. In the meantime, I hope you enjoyed reading, and feel free to use my code to try it out for your purposes. Also, if there is any feedback on code or just the blog post, feel free to reach out on LinkedIn or email me at aayushmnit@gmail.com.
[ { "code": null, "e": 665, "s": 172, "text": "In this post, I am going to write about Recommender systems, how they are used in many e-commerce websites. The post will also cover about building simple recommender system models using Matrix Factorization algorithm using lightFM package and my recommender system cookbook. The post will focus on business use cases and simple implementations. The post only cover basic intuition around algorithms and will provide links to resources if you want to understand the math behind the algorithm." }, { "code": null, "e": 1485, "s": 665, "text": "I am an avid reader and a believer in open source education and continuously expand my knowledge around data science & computer science using online courses, blogs, Github repositories and participating in data science competitions. While searching for quality content on the internet, I have come across various learning links which either focus on the implementation of the algorithm using specific data/modeling technique in ABC language or focus on business impact/results using the broad concept of a family of algorithms(like classification, forecasting, recommender systems etc.) but don’t go into details of how to do it. So the idea is to write some blogs which can combine both business use cases with codes & algorithmic intuition to provide a holistic view of how data science is used in business scenarios." }, { "code": null, "e": 1820, "s": 1485, "text": "As the world is becoming more digital, we are already getting used to a lot of personalized experience and the algorithm which help us achieve this falls in the family of recommender systems. Almost every web-based platform is using some recommender system to provide customized content. Following are the companies I admire the most." }, { "code": null, "e": 2147, "s": 1820, "text": "Personalization is a technique of dynamically tailoring your content based on needs of each user. Simple examples of personalization could be movie recommendation on Netflix, personalized email targeting/re-targeting by e-commerce platforms, item recommendation on Amazon, etc. Personalization helps us achieve these four Rs -" }, { "code": null, "e": 2270, "s": 2147, "text": "Recognize: Know customer’s and prospects’ profiles, including demographics, geography, and expressed and shared interests." }, { "code": null, "e": 2371, "s": 2270, "text": "Remember: Recall customers’ history, primarily how they act as expressed by what they browse and buy" }, { "code": null, "e": 2491, "s": 2371, "text": "Reach: Deliver the right promotion, content, recommendation for a customer based on actions, preferences, and interests" }, { "code": null, "e": 2650, "s": 2491, "text": "Relevance: Deliver personalization within the context of the digital experience based on who customers are, where they are located and what time of year it is" }, { "code": null, "e": 2951, "s": 2650, "text": "Personalization has a lot of benefits for both users and companies. For users, it makes their life easy as they only get to see more relevant stuff to them (unless it’s an advertisement, even they are personalized). For business benefits are countless but here are few which I would like to mention -" }, { "code": null, "e": 3081, "s": 2951, "text": "Enhance customer experience: Personalization reduces the clutter and enhances the customer experience by showing relevant content" }, { "code": null, "e": 3253, "s": 3081, "text": "Cross-sell/ Up-sell opportunities: Relevant product offerings based on customer preferences can lead to increasing products visibility and eventually selling more products" }, { "code": null, "e": 3379, "s": 3253, "text": "Increased basket size: Personalized experience and targeting ultimately leads to increased basket size and frequent purchases" }, { "code": null, "e": 3698, "s": 3379, "text": "Increased customer loyalty: In the digital world, customer retention/loyalty is the most prominent problem faced by many companies as finding a replacement for a particular service is quite easy. According to a Forbes article, Forty-four percent of consumers say they will likely repeat after a personalized experience" }, { "code": null, "e": 4326, "s": 3698, "text": "Matrix factorization is one of the algorithms from recommender systems family and as the name suggests it factorize a matrix, i.e., decompose a matrix in two(or more) matrices such that once you multiply them you get your original matrix back. In case of the recommendation system, we will typically start with an interaction/rating matrix between users and items and matrix factorization algorithm will decompose this matrix in user and item feature matrix which is also known as embeddings. Example of interaction matrix would be user-movie ratings for movie recommender, user-product purchase flag for transaction data, etc." }, { "code": null, "e": 4938, "s": 4326, "text": "Typically user/item embeddings capture latent features about attributes of users and item respectively. Essentially, latent features are the representation of user/item in an arbitrary space which represents how a user rate a movie. In the example of a movie recommender, an example of user embedding might represent affinity of a user to watch serious kind of movie when the value of the latent feature is high and comedy type of movie when the value is low. Similarly, a movie latent feature may have a high value when the movie is more male driven and when it’s more female-driven the value is typically low." }, { "code": null, "e": 5213, "s": 4938, "text": "For more information on matrix factorization and factorization machines you can read these articles — Matrix Factorization: A Simple Tutorial and Implementation in Python Introductory Guide — Factorization Machines & their application on huge datasets (with codes in Python)" }, { "code": null, "e": 5508, "s": 5213, "text": "In the hands-on section, we will be building recommender system for different scenarios which we typically see in many companies using LightFM package and MovieLens data. We are using small size data which contains 100,000 ratings and 1,300 tag applications applied to 9,000 movies by 700 users" }, { "code": null, "e": 5855, "s": 5508, "text": "Let’s start by importing data, recommender system cookbook and preprocessing cookbook files for this hands-on section. I have written these reusable generic cookbook codes to increase productivity and write clean/modular codes; you will see we can build a recommender system using 10–15 lines of code by using these cookbooks(do more with less!)." }, { "code": null, "e": 6189, "s": 5855, "text": "# Importing Libraries and cookbooksfrom recsys import * ## recommender system cookbookfrom generic_preprocessing import * ## pre-processing codefrom IPython.display import HTML ## Setting display options for Ipython Notebook# Importing rating data and having a lookratings = pd.read_csv('./ml-latest-small/ratings.csv')ratings.head()" }, { "code": null, "e": 6328, "s": 6189, "text": "As we can see rating data contain user id, movie id and a rating between 0.5 to 5 with a timestamp representing when the rating was given." }, { "code": null, "e": 6456, "s": 6328, "text": "# Importing movie data and having a look at first five columnsmovies = pd.read_csv('./ml-latest-small/movies.csv')movies.head()" }, { "code": null, "e": 6524, "s": 6456, "text": "Movie data consist of movie id, their title, and genre they belong." }, { "code": null, "e": 7183, "s": 6524, "text": "As I mentioned before, to create a recommender system we need to start by creating an interaction matrix. For this task, we will use the create_interaction_matrix function from the recsys cookbook. This function requires you to input a pandas dataframe and necessary information like column name for user id, item id, and rating. It also takes an additional parameter threshold if norm=True which means any rating above the mentioned threshold is considered a positive rating. In our case, we don’t have to normalize our data, but in cases of retail data any purchase of a particular type of item can be considered a positive rating, quantity doesn’t matter." }, { "code": null, "e": 7490, "s": 7183, "text": "# Creating interaction matrix using rating datainteractions = create_interaction_matrix(df = ratings, user_col = 'userId', item_col = 'movieId', rating_col = 'rating')interactions.head()" }, { "code": null, "e": 7808, "s": 7490, "text": "As we can see the data is created in an interaction format where rows represent each user and columns represent each movie id with ratings as values. We will also create user and item dictionaries to later convert user_id to user_name or movie_id to movie_name by using create_user_dict and create_item dict function." }, { "code": null, "e": 8043, "s": 7808, "text": "# Create User Dictuser_dict = create_user_dict(interactions=interactions)# Create Item dictmovies_dict = create_item_dict(df = movies, id_col = 'movieId', name_col = 'title')" }, { "code": null, "e": 8147, "s": 8043, "text": "To build a matrix factorization model, we will use the runMF function which will take following input -" }, { "code": null, "e": 8218, "s": 8147, "text": "interaction matrix: Interaction matrix created in the previous section" }, { "code": null, "e": 8285, "s": 8218, "text": "n_components: Number of embedding generated for each user and item" }, { "code": null, "e": 8451, "s": 8285, "text": "loss: We need to define a loss function, in this case, we are using warp loss because we mostly care about the ranking of data, i.e, which items should we show first" }, { "code": null, "e": 8481, "s": 8451, "text": "epoch: Number of times to run" }, { "code": null, "e": 8535, "s": 8481, "text": "n_jobs: Number of cores to use in parallel processing" }, { "code": null, "e": 8703, "s": 8535, "text": "mf_model = runMF(interactions = interactions, n_components = 30, loss = 'warp', epoch = 30, n_jobs = 4)" }, { "code": null, "e": 8900, "s": 8703, "text": "Now we have built our matrix factorization model we can now do some interesting things. There are various use cases which can be solved by using this model for a web platform let’s look into them." }, { "code": null, "e": 9188, "s": 8900, "text": "In this use case, we want to show a user, items he might be interested in buying/viewing based on his/her interactions done in the past. Typical industry examples for this are like “Deals recommended for you” on Amazon or “Top pics for a user” on Netflix or personalized email campaigns." }, { "code": null, "e": 9471, "s": 9188, "text": "We can use the sample_recommendation_user function for this case. This functions take matrix factorization model, interaction matrix, user dictionary, item dictionary, user_id and the number of items as input and return the list of item id’s a user may be interested in interacting." }, { "code": null, "e": 10830, "s": 9471, "text": "## Calling 10 movie recommendation for user id 11rec_list = sample_recommendation_user(model = mf_model, interactions = interactions, user_id = 11, user_dict = user_dict, item_dict = movies_dict, threshold = 4, nrec_items = 10, show = True)Known Likes:1- The Hunger Games: Catching Fire (2013)2- Gravity (2013)3- Dark Knight Rises, The (2012)4- The Hunger Games (2012)5- Town, The (2010)6- Exit Through the Gift Shop (2010)7- Bank Job, The (2008)8- Departed, The (2006)9- Bourne Identity, The (1988)10- Step Into Liquid (2002)11- SLC Punk! (1998)12- Last of the Mohicans, The (1992)13- Good, the Bad and the Ugly, The (Buono, il brutto, il cattivo, Il) (1966)14- Robin Hood: Prince of Thieves (1991)15- Citizen Kane (1941)16- Trainspotting (1996)17- Pulp Fiction (1994)18- Usual Suspects, The (1995) Recommended Items:1- Dark Knight, The (2008)2- Inception (2010)3- Iron Man (2008)4- Shutter Island (2010)5- Fight Club (1999)6- Avatar (2009)7- Forrest Gump (1994)8- District 9 (2009)9- WALL·E (2008)10- Matrix, The (1999)print(rec_list)[593L, 260L, 110L, 480L, 47L, 527L, 344L, 858L, 231L, 780L]" }, { "code": null, "e": 11345, "s": 10830, "text": "As we can see in this case user is interested in “Dark Knight Rises(2012)” so the first recommendation is “The Dark Knight(2008)”. This user also seems to have a strong liking towards movies in drama, sci-fi and thriller genre and there are many movies recommended in the same genre like Dark Knight(Drama/Crime), Inception(Sci-Fi, Thriller), Iron Man(Sci-FI thriller), Shutter Island(Drame/Thriller), Fight club(drama), Avatar(Sci-fi), Forrest Gump(Drama), District 9(Thriller), Wall-E(Sci-fi), The Matrix(Sci-Fi)" }, { "code": null, "e": 11595, "s": 11345, "text": "Similar models can also be used for building sections like “Based on your recent browsing history” recommendations by just changing the rating matrix only to contain interaction which is recent and based on browsing history visits on specific items." }, { "code": null, "e": 11889, "s": 11595, "text": "In this use case, we will discuss how we can recommend a list of users specific to a particular item. Example of such cases is when you are running a promotion on an item and want to run an e-mail campaign around this promotional item to only 10,000 users who might be interested in this item." }, { "code": null, "e": 12178, "s": 11889, "text": "We can use the sample_recommendation_item function for this case. This functions take matrix factorization model, interaction matrix, user dictionary, item dictionary, item_id and the number of users as input and return the list of user id’s who are more likely be interested in the item." }, { "code": null, "e": 12585, "s": 12178, "text": "## Calling 15 user recommendation for item id 1sample_recommendation_item(model = mf_model, interactions = interactions, item_id = 1, user_dict = user_dict, item_dict = movies_dict, number_of_user = 15)[116, 410, 449, 657, 448, 633, 172, 109, 513, 44, 498, 459, 317, 415, 495]" }, { "code": null, "e": 12936, "s": 12585, "text": "As you can see function return a list of userID who might be interested in item id 1. Another example why you might need such model is when there is an old inventory sitting in your warehouse which needs to clear up otherwise you might have to write it off, and you want to clear it by giving some discount to users who might be interested in buying." }, { "code": null, "e": 13558, "s": 12936, "text": "In this use case, we will discuss how we can recommend a list of items specific to a particular item. This kind of models will help you to find similar/related items or items which can be bundled together. Typical industry use case for such models are in cross-selling and up-selling opportunities on product page like “Products related to this item”, “Frequently bought together”, “Customers who bought this also bought this” and “Customers who viewed this item also viewed”. “Customers who bought this also bought this” and “Customers who viewed this item also viewed” can also be solved through market basket analysis." }, { "code": null, "e": 14043, "s": 13558, "text": "To achieve this use case, we will create a cosine distance matrix using item embeddings generated by matrix factorization model. This will help us calculate similarity b/w items, and then we can recommend top N similar item to an item of interest. First step is to create a item-item distance matrix using the create_item_emdedding_distance_matrix function. This function takes matrix factorization models and interaction matrix as input and returns an item_embedding_distance_matrix." }, { "code": null, "e": 14299, "s": 14043, "text": "## Creating item-item distance matrixitem_item_dist = create_item_emdedding_distance_matrix(model = mf_model, interactions = interactions)## Checking item embedding distance matrixitem_item_dist.head()" }, { "code": null, "e": 14684, "s": 14299, "text": "As we can see the matrix have movies as both row and columns and the value represents the cosine distance between them. Next step is to use item_item_recommendation function to get top N items with respect to an item_id. This function takes item embedding distance matrix, item_id, item_dictionary and number of items to be recommended as input and return similar item list as output." }, { "code": null, "e": 15515, "s": 14684, "text": "## Calling 10 recommended items for item id rec_list = item_item_recommendation(item_emdedding_distance_matrix = item_item_dist, item_id = 5378, item_dict = movies_dict, n_items = 10)Item of interest :Star Wars: Episode II - Attack of the Clones (2002)Item similar to the above item:1- Star Wars: Episode III - Revenge of the Sith (2005)2- Lord of the Rings: The Two Towers, The (2002)3- Lord of the Rings: The Fellowship of the Ring, The (2001)4- Lord of the Rings: The Return of the King, The (2003)5- Matrix Reloaded, The (2003)6- Harry Potter and the Sorcerer's Stone (a.k.a. Harry Potter and the Philosopher's Stone) (2001)7- Gladiator (2000)8- Spider-Man (2002)9- Minority Report (2002)10- Mission: Impossible II (2000)" }, { "code": null, "e": 15726, "s": 15515, "text": "As we can see for “Star Wars: Episode II — Attack of the Clones (2002)” movie we are getting it’s next released movies which is “Star Wars: Episode III — Revenge of the Sith (2005)” as the first recommendation." }, { "code": null, "e": 16108, "s": 15726, "text": "Like any other blog, this method isn’t perfect for every application, but the same ideas can work if we use it effectively. There is a lot of advancements in recommender systems with the advent of Deep learning. While there is room for improvement, I am pleased with how it has been working for me so far. I might write about deep learning based recommender systems later sometime." } ]
The Three Keys to Experimental Design | by Robert Wood | Towards Data Science
This quick blog is designed to help you get off to the races quickly in world of data science; and here specifically, Experimental design. Enjoy! When it comes to experimental design there are three main steps it can be broken down to: Planning Design Analysis Planning should always begin with a well formed hypothesis. Some of the major considerations you want to make in this process are as follows: What is the question you want answered? What is the population in question? What are your dependent and independent variables? When conducting an experiment, there are 3 key components to consider. These three aspects of an experiment allows us to assess our population’s variability. Randomization Replication Blocking The purpose of randomization is to make sure that if there is variation in outcomes that is related to outside factors, then it is distributed across treatment groups. When conducting an experiment, we seek to understand the variability of outcomes. For instance; if I were to run a given experiment but once, and I was depending on an outcome that may have occurred due to random chance. The point here is to understand the broad spectrum of possibilities or outcomes, it’s important that we replicate the experiment accordingly. Statistical Power The concept of statistical power means that if your experiment concludes such that you reject the NULL hypothesis and accept the alternative hypothesis, it is the likelihood that it would not be due to random chance. Best practice is 80% statistical power. So to simplify this even further; If your hypothesis appears to be correct, what’s the likelihood that you didn’t get that outcome just due to random chance. Blocking is used to help control variability by making treatment groups more alike. Inside of a given group, you might see that differences are minimal, however across other groups that could be much larger. One example of this might be blocking an experiment by gender. Blocking by variables — use aov for the sake of blocking Randomized Complete Block Design (RCBD) experiment After accumulating data from your experiment; one quick and east test of statistical significance you might run is called a t-test. Consider your hypothesis or central research question:NULL hypothesis — lets keep this simple, the null hypothesis is pretty much when you’re wrong. For the mtcars dataset, the null hypothesis might be something like a vehicles horse power has no effect on miles per gallon.Alternative hypothesis — conversely the alternative hypothesis means that there was a difference. If you are able to determine with statistical significance the effect of the independent variable on the dependent variable, you would say that you reject the null hypothesis and accept the alternative hypothesis.Is this a one or two sided test?One sided test — when you are testing whether a given variable is greater than another then it’s a one-sided test; if you’re testing whether it’s less than another... still one-sided.Two sided test — when you are testing that a given variable is not equal to another, then that is two sided. Greater or less than in a single test.Were your results statistically significant?People use the term statistically significant left and right with little consideration of what it actually means. What that is saying is that if you run your test and your data is suggesting a that your hypothesis is correct, statistical significance is effectively knowing that it’s not likely due to random chance.The standard here is 95% confidence, or a less than or equal to likelihood of 5%.What is statistical power?Similar to statistical significance; given that the alternative hypothesis is true, power represents the likelihood that the null hypothesis will be rejected.The standard for power is 80%. Consider your hypothesis or central research question: NULL hypothesis — lets keep this simple, the null hypothesis is pretty much when you’re wrong. For the mtcars dataset, the null hypothesis might be something like a vehicles horse power has no effect on miles per gallon. Alternative hypothesis — conversely the alternative hypothesis means that there was a difference. If you are able to determine with statistical significance the effect of the independent variable on the dependent variable, you would say that you reject the null hypothesis and accept the alternative hypothesis. Is this a one or two sided test? One sided test — when you are testing whether a given variable is greater than another then it’s a one-sided test; if you’re testing whether it’s less than another... still one-sided. Two sided test — when you are testing that a given variable is not equal to another, then that is two sided. Greater or less than in a single test. Were your results statistically significant? People use the term statistically significant left and right with little consideration of what it actually means. What that is saying is that if you run your test and your data is suggesting a that your hypothesis is correct, statistical significance is effectively knowing that it’s not likely due to random chance. The standard here is 95% confidence, or a less than or equal to likelihood of 5%. What is statistical power? Similar to statistical significance; given that the alternative hypothesis is true, power represents the likelihood that the null hypothesis will be rejected. The standard for power is 80%. For a given experiment one thing to consider is the sample size. In order to arrive at a required number for this is requires a handful of other variables including targeted statistical power & significance. Another measure is that of effect size. Effect size represents the difference between the average of two groups divided by the standard deviation of both groups combined. The greater the distance between groups the less of a sample to validate it. The smaller the difference the greater the likelihood that the observed distance is only due to chance. In order to calculate any of these values including effect size, statistical power, p-value, etc. you need all but one of them. Load up the package pwr and use the pwr.anova.test to identify the odd variable out here. k — number of groupsn — sample size per groupf = effect sizesig.level = significance levelpower = statistical power library(pwr) pwr.anova.test(k = 2, n = NULL, f = .1, sig.level = 0.05, power = .8) As you can see above, given the demands that we passed to the pwr.anova.test function, we can see that for those things to hold true, we at least 394 samples per group. I hope this helps to get you started in experimental design! Come check out some of my other posts at datasciencelessons.com & happy data science-ing!
[ { "code": null, "e": 317, "s": 171, "text": "This quick blog is designed to help you get off to the races quickly in world of data science; and here specifically, Experimental design. Enjoy!" }, { "code": null, "e": 407, "s": 317, "text": "When it comes to experimental design there are three main steps it can be broken down to:" }, { "code": null, "e": 416, "s": 407, "text": "Planning" }, { "code": null, "e": 423, "s": 416, "text": "Design" }, { "code": null, "e": 432, "s": 423, "text": "Analysis" }, { "code": null, "e": 492, "s": 432, "text": "Planning should always begin with a well formed hypothesis." }, { "code": null, "e": 574, "s": 492, "text": "Some of the major considerations you want to make in this process are as follows:" }, { "code": null, "e": 614, "s": 574, "text": "What is the question you want answered?" }, { "code": null, "e": 650, "s": 614, "text": "What is the population in question?" }, { "code": null, "e": 701, "s": 650, "text": "What are your dependent and independent variables?" }, { "code": null, "e": 859, "s": 701, "text": "When conducting an experiment, there are 3 key components to consider. These three aspects of an experiment allows us to assess our population’s variability." }, { "code": null, "e": 873, "s": 859, "text": "Randomization" }, { "code": null, "e": 885, "s": 873, "text": "Replication" }, { "code": null, "e": 894, "s": 885, "text": "Blocking" }, { "code": null, "e": 1062, "s": 894, "text": "The purpose of randomization is to make sure that if there is variation in outcomes that is related to outside factors, then it is distributed across treatment groups." }, { "code": null, "e": 1425, "s": 1062, "text": "When conducting an experiment, we seek to understand the variability of outcomes. For instance; if I were to run a given experiment but once, and I was depending on an outcome that may have occurred due to random chance. The point here is to understand the broad spectrum of possibilities or outcomes, it’s important that we replicate the experiment accordingly." }, { "code": null, "e": 1443, "s": 1425, "text": "Statistical Power" }, { "code": null, "e": 1700, "s": 1443, "text": "The concept of statistical power means that if your experiment concludes such that you reject the NULL hypothesis and accept the alternative hypothesis, it is the likelihood that it would not be due to random chance. Best practice is 80% statistical power." }, { "code": null, "e": 1858, "s": 1700, "text": "So to simplify this even further; If your hypothesis appears to be correct, what’s the likelihood that you didn’t get that outcome just due to random chance." }, { "code": null, "e": 2129, "s": 1858, "text": "Blocking is used to help control variability by making treatment groups more alike. Inside of a given group, you might see that differences are minimal, however across other groups that could be much larger. One example of this might be blocking an experiment by gender." }, { "code": null, "e": 2186, "s": 2129, "text": "Blocking by variables — use aov for the sake of blocking" }, { "code": null, "e": 2237, "s": 2186, "text": "Randomized Complete Block Design (RCBD) experiment" }, { "code": null, "e": 2369, "s": 2237, "text": "After accumulating data from your experiment; one quick and east test of statistical significance you might run is called a t-test." }, { "code": null, "e": 3972, "s": 2369, "text": "Consider your hypothesis or central research question:NULL hypothesis — lets keep this simple, the null hypothesis is pretty much when you’re wrong. For the mtcars dataset, the null hypothesis might be something like a vehicles horse power has no effect on miles per gallon.Alternative hypothesis — conversely the alternative hypothesis means that there was a difference. If you are able to determine with statistical significance the effect of the independent variable on the dependent variable, you would say that you reject the null hypothesis and accept the alternative hypothesis.Is this a one or two sided test?One sided test — when you are testing whether a given variable is greater than another then it’s a one-sided test; if you’re testing whether it’s less than another... still one-sided.Two sided test — when you are testing that a given variable is not equal to another, then that is two sided. Greater or less than in a single test.Were your results statistically significant?People use the term statistically significant left and right with little consideration of what it actually means. What that is saying is that if you run your test and your data is suggesting a that your hypothesis is correct, statistical significance is effectively knowing that it’s not likely due to random chance.The standard here is 95% confidence, or a less than or equal to likelihood of 5%.What is statistical power?Similar to statistical significance; given that the alternative hypothesis is true, power represents the likelihood that the null hypothesis will be rejected.The standard for power is 80%." }, { "code": null, "e": 4027, "s": 3972, "text": "Consider your hypothesis or central research question:" }, { "code": null, "e": 4248, "s": 4027, "text": "NULL hypothesis — lets keep this simple, the null hypothesis is pretty much when you’re wrong. For the mtcars dataset, the null hypothesis might be something like a vehicles horse power has no effect on miles per gallon." }, { "code": null, "e": 4560, "s": 4248, "text": "Alternative hypothesis — conversely the alternative hypothesis means that there was a difference. If you are able to determine with statistical significance the effect of the independent variable on the dependent variable, you would say that you reject the null hypothesis and accept the alternative hypothesis." }, { "code": null, "e": 4593, "s": 4560, "text": "Is this a one or two sided test?" }, { "code": null, "e": 4777, "s": 4593, "text": "One sided test — when you are testing whether a given variable is greater than another then it’s a one-sided test; if you’re testing whether it’s less than another... still one-sided." }, { "code": null, "e": 4925, "s": 4777, "text": "Two sided test — when you are testing that a given variable is not equal to another, then that is two sided. Greater or less than in a single test." }, { "code": null, "e": 4970, "s": 4925, "text": "Were your results statistically significant?" }, { "code": null, "e": 5287, "s": 4970, "text": "People use the term statistically significant left and right with little consideration of what it actually means. What that is saying is that if you run your test and your data is suggesting a that your hypothesis is correct, statistical significance is effectively knowing that it’s not likely due to random chance." }, { "code": null, "e": 5369, "s": 5287, "text": "The standard here is 95% confidence, or a less than or equal to likelihood of 5%." }, { "code": null, "e": 5396, "s": 5369, "text": "What is statistical power?" }, { "code": null, "e": 5555, "s": 5396, "text": "Similar to statistical significance; given that the alternative hypothesis is true, power represents the likelihood that the null hypothesis will be rejected." }, { "code": null, "e": 5586, "s": 5555, "text": "The standard for power is 80%." }, { "code": null, "e": 5794, "s": 5586, "text": "For a given experiment one thing to consider is the sample size. In order to arrive at a required number for this is requires a handful of other variables including targeted statistical power & significance." }, { "code": null, "e": 5965, "s": 5794, "text": "Another measure is that of effect size. Effect size represents the difference between the average of two groups divided by the standard deviation of both groups combined." }, { "code": null, "e": 6146, "s": 5965, "text": "The greater the distance between groups the less of a sample to validate it. The smaller the difference the greater the likelihood that the observed distance is only due to chance." }, { "code": null, "e": 6274, "s": 6146, "text": "In order to calculate any of these values including effect size, statistical power, p-value, etc. you need all but one of them." }, { "code": null, "e": 6364, "s": 6274, "text": "Load up the package pwr and use the pwr.anova.test to identify the odd variable out here." }, { "code": null, "e": 6480, "s": 6364, "text": "k — number of groupsn — sample size per groupf = effect sizesig.level = significance levelpower = statistical power" }, { "code": null, "e": 6623, "s": 6480, "text": "library(pwr) pwr.anova.test(k = 2, n = NULL, f = .1, sig.level = 0.05, power = .8)" }, { "code": null, "e": 6792, "s": 6623, "text": "As you can see above, given the demands that we passed to the pwr.anova.test function, we can see that for those things to hold true, we at least 394 samples per group." } ]
When are Constructors Called in C++?
Here we will see, when constructors are called. Here constructors are of different types. Global, local, static local, dynamic. For the global object, the constructors are called before entering into the main function. #include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "Calling Constructor" << endl; } }; MyClass myObj; //Global object int main() { cout << "Inside Main"; } Calling Constructor Inside Main When the object is non-static, then, constructor is called when the execution reaches the point, where object is created. #include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "Calling Constructor" << endl; } }; int main() { cout << "Inside Main\n"; MyClass myObj; //Local object cout << "After creating object"; } Inside Main Calling Constructor After creating object When the object is local static, then only for the first time, its constructor will be called, if the same function is used again, it will not affect. #include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "Calling Constructor" << endl; } }; void func() { static MyClass myObj; //Local static object } int main() { cout << "Inside Main\n"; func(); cout << "After creating object\n"; func(); cout << "After second time"; } Inside Main Calling Constructor After creating object After second time Finally for the dynamic object, the constructor will be called, when object is created using new operator. #include <iostream> using namespace std; class MyClass { public: MyClass() { cout << "Calling Constructor" << endl; } }; int main() { cout << "Inside Main\n"; MyClass *ptr; cout << "Declaring pointer\n"; ptr = new MyClass; cout << "After creating dynamic object"; } Inside Main Declaring pointer Calling Constructor After creating dynamic object
[ { "code": null, "e": 1190, "s": 1062, "text": "Here we will see, when constructors are called. Here constructors are of different types. Global, local, static local, dynamic." }, { "code": null, "e": 1281, "s": 1190, "text": "For the global object, the constructors are called before entering into the main function." }, { "code": null, "e": 1498, "s": 1281, "text": "#include <iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n cout << \"Calling Constructor\" << endl;\n }\n};\nMyClass myObj; //Global object\nint main() {\n cout << \"Inside Main\";\n}" }, { "code": null, "e": 1530, "s": 1498, "text": "Calling Constructor\nInside Main" }, { "code": null, "e": 1652, "s": 1530, "text": "When the object is non-static, then, constructor is called when the execution reaches the point, where object is created." }, { "code": null, "e": 1909, "s": 1652, "text": "#include <iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n cout << \"Calling Constructor\" << endl;\n }\n};\nint main() {\n cout << \"Inside Main\\n\";\n MyClass myObj; //Local object\n cout << \"After creating object\";\n}" }, { "code": null, "e": 1963, "s": 1909, "text": "Inside Main\nCalling Constructor\nAfter creating object" }, { "code": null, "e": 2114, "s": 1963, "text": "When the object is local static, then only for the first time, its constructor will be called, if the same function is used again, it will not affect." }, { "code": null, "e": 2457, "s": 2114, "text": "#include <iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n cout << \"Calling Constructor\" << endl;\n }\n};\nvoid func() {\n static MyClass myObj; //Local static object\n}\nint main() {\n cout << \"Inside Main\\n\";\n func();\n cout << \"After creating object\\n\";\n func();\n cout << \"After second time\";\n}" }, { "code": null, "e": 2529, "s": 2457, "text": "Inside Main\nCalling Constructor\nAfter creating object\nAfter second time" }, { "code": null, "e": 2636, "s": 2529, "text": "Finally for the dynamic object, the constructor will be called, when object is created using new operator." }, { "code": null, "e": 2941, "s": 2636, "text": "#include <iostream>\nusing namespace std;\nclass MyClass {\n public:\n MyClass() {\n cout << \"Calling Constructor\" << endl;\n }\n};\nint main() {\n cout << \"Inside Main\\n\";\n MyClass *ptr;\n cout << \"Declaring pointer\\n\";\n ptr = new MyClass;\n cout << \"After creating dynamic object\";\n}" }, { "code": null, "e": 3021, "s": 2941, "text": "Inside Main\nDeclaring pointer\nCalling Constructor\nAfter creating dynamic object" } ]
Python Pandas - Options and Customization
Pandas provide API to customize some aspects of its behavior, display is being mostly used. The API is composed of five relevant functions. They are − get_option() set_option() reset_option() describe_option() option_context() Let us now understand how the functions operate. get_option takes a single parameter and returns the value as given in the output below − Displays the default number of value. Interpreter reads this value and displays the rows with this value as upper limit to display. import pandas as pd print pd.get_option("display.max_rows") Its output is as follows − 60 Displays the default number of value. Interpreter reads this value and displays the rows with this value as upper limit to display. import pandas as pd print pd.get_option("display.max_columns") Its output is as follows − 20 Here, 60 and 20 are the default configuration parameter values. set_option takes two arguments and sets the value to the parameter as shown below − Using set_option(), we can change the default number of rows to be displayed. import pandas as pd pd.set_option("display.max_rows",80) print pd.get_option("display.max_rows") Its output is as follows − 80 Using set_option(), we can change the default number of rows to be displayed. import pandas as pd pd.set_option("display.max_columns",30) print pd.get_option("display.max_columns") Its output is as follows − 30 reset_option takes an argument and sets the value back to the default value. Using reset_option(), we can change the value back to the default number of rows to be displayed. import pandas as pd pd.reset_option("display.max_rows") print pd.get_option("display.max_rows") Its output is as follows − 60 describe_option prints the description of the argument. Using reset_option(), we can change the value back to the default number of rows to be displayed. import pandas as pd pd.describe_option("display.max_rows") Its output is as follows − display.max_rows : int If max_rows is exceeded, switch to truncate view. Depending on 'large_repr', objects are either centrally truncated or printed as a summary view. 'None' value means unlimited. In case python/IPython is running in a terminal and `large_repr` equals 'truncate' this can be set to 0 and pandas will auto-detect the height of the terminal and print a truncated object which fits the screen height. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. [default: 60] [currently: 60] option_context context manager is used to set the option in with statement temporarily. Option values are restored automatically when you exit the with block − Using option_context(), we can set the value temporarily. import pandas as pd with pd.option_context("display.max_rows",10): print(pd.get_option("display.max_rows")) print(pd.get_option("display.max_rows")) Its output is as follows − 10 10 See, the difference between the first and the second print statements. The first statement prints the value set by option_context() which is temporary within the with context itself. After the with context, the second print statement prints the configured value. display.max_rows Displays maximum number of rows to display 2 display.max_columns Displays maximum number of columns to display display.expand_frame_repr Displays DataFrames to Stretch Pages display.max_colwidth Displays maximum column width display.precision Displays precision for decimal numbers 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": 2535, "s": 2443, "text": "Pandas provide API to customize some aspects of its behavior, display is being mostly used." }, { "code": null, "e": 2594, "s": 2535, "text": "The API is composed of five relevant functions. They are −" }, { "code": null, "e": 2607, "s": 2594, "text": "get_option()" }, { "code": null, "e": 2620, "s": 2607, "text": "set_option()" }, { "code": null, "e": 2635, "s": 2620, "text": "reset_option()" }, { "code": null, "e": 2653, "s": 2635, "text": "describe_option()" }, { "code": null, "e": 2670, "s": 2653, "text": "option_context()" }, { "code": null, "e": 2719, "s": 2670, "text": "Let us now understand how the functions operate." }, { "code": null, "e": 2808, "s": 2719, "text": "get_option takes a single parameter and returns the value as given in the output below −" }, { "code": null, "e": 2940, "s": 2808, "text": "Displays the default number of value. Interpreter reads this value and displays the rows with this value as upper limit to display." }, { "code": null, "e": 3000, "s": 2940, "text": "import pandas as pd\nprint pd.get_option(\"display.max_rows\")" }, { "code": null, "e": 3027, "s": 3000, "text": "Its output is as follows −" }, { "code": null, "e": 3031, "s": 3027, "text": "60\n" }, { "code": null, "e": 3163, "s": 3031, "text": "Displays the default number of value. Interpreter reads this value and displays the rows with this value as upper limit to display." }, { "code": null, "e": 3226, "s": 3163, "text": "import pandas as pd\nprint pd.get_option(\"display.max_columns\")" }, { "code": null, "e": 3253, "s": 3226, "text": "Its output is as follows −" }, { "code": null, "e": 3257, "s": 3253, "text": "20\n" }, { "code": null, "e": 3321, "s": 3257, "text": "Here, 60 and 20 are the default configuration parameter values." }, { "code": null, "e": 3405, "s": 3321, "text": "set_option takes two arguments and sets the value to the parameter as shown below −" }, { "code": null, "e": 3483, "s": 3405, "text": "Using set_option(), we can change the default number of rows to be displayed." }, { "code": null, "e": 3582, "s": 3483, "text": "import pandas as pd\n\npd.set_option(\"display.max_rows\",80)\n\nprint pd.get_option(\"display.max_rows\")" }, { "code": null, "e": 3609, "s": 3582, "text": "Its output is as follows −" }, { "code": null, "e": 3613, "s": 3609, "text": "80\n" }, { "code": null, "e": 3691, "s": 3613, "text": "Using set_option(), we can change the default number of rows to be displayed." }, { "code": null, "e": 3796, "s": 3691, "text": "import pandas as pd\n\npd.set_option(\"display.max_columns\",30)\n\nprint pd.get_option(\"display.max_columns\")" }, { "code": null, "e": 3823, "s": 3796, "text": "Its output is as follows −" }, { "code": null, "e": 3827, "s": 3823, "text": "30\n" }, { "code": null, "e": 3904, "s": 3827, "text": "reset_option takes an argument and sets the value back to the default value." }, { "code": null, "e": 4002, "s": 3904, "text": "Using reset_option(), we can change the value back to the default number of rows to be displayed." }, { "code": null, "e": 4099, "s": 4002, "text": "import pandas as pd\n\npd.reset_option(\"display.max_rows\")\nprint pd.get_option(\"display.max_rows\")" }, { "code": null, "e": 4126, "s": 4099, "text": "Its output is as follows −" }, { "code": null, "e": 4130, "s": 4126, "text": "60\n" }, { "code": null, "e": 4187, "s": 4130, "text": "describe_option prints the description of the argument." }, { "code": null, "e": 4285, "s": 4187, "text": "Using reset_option(), we can change the value back to the default number of rows to be displayed." }, { "code": null, "e": 4344, "s": 4285, "text": "import pandas as pd\npd.describe_option(\"display.max_rows\")" }, { "code": null, "e": 4371, "s": 4344, "text": "Its output is as follows −" }, { "code": null, "e": 4983, "s": 4371, "text": "display.max_rows : int\n If max_rows is exceeded, switch to truncate view. Depending on\n 'large_repr', objects are either centrally truncated or printed as\n a summary view. 'None' value means unlimited.\n\n In case python/IPython is running in a terminal and `large_repr`\n equals 'truncate' this can be set to 0 and pandas will auto-detect\n the height of the terminal and print a truncated object which fits\n the screen height. The IPython notebook, IPython qtconsole, or\n IDLE do not run in a terminal and hence it is not possible to do\n correct auto-detection.\n [default: 60] [currently: 60]\n" }, { "code": null, "e": 5143, "s": 4983, "text": "option_context context manager is used to set the option in with statement temporarily. Option values are restored automatically when you exit the with block −" }, { "code": null, "e": 5201, "s": 5143, "text": "Using option_context(), we can set the value temporarily." }, { "code": null, "e": 5356, "s": 5201, "text": "import pandas as pd\nwith pd.option_context(\"display.max_rows\",10):\n print(pd.get_option(\"display.max_rows\"))\n print(pd.get_option(\"display.max_rows\"))" }, { "code": null, "e": 5383, "s": 5356, "text": "Its output is as follows −" }, { "code": null, "e": 5390, "s": 5383, "text": "10\n10\n" }, { "code": null, "e": 5653, "s": 5390, "text": "See, the difference between the first and the second print statements. The first statement prints the value set by option_context() which is temporary within the with context itself. After the with context, the second print statement prints the configured value." }, { "code": null, "e": 5670, "s": 5653, "text": "display.max_rows" }, { "code": null, "e": 5713, "s": 5670, "text": "Displays maximum number of rows to display" }, { "code": null, "e": 5735, "s": 5713, "text": "2 display.max_columns" }, { "code": null, "e": 5781, "s": 5735, "text": "Displays maximum number of columns to display" }, { "code": null, "e": 5807, "s": 5781, "text": "display.expand_frame_repr" }, { "code": null, "e": 5844, "s": 5807, "text": "Displays DataFrames to Stretch Pages" }, { "code": null, "e": 5865, "s": 5844, "text": "display.max_colwidth" }, { "code": null, "e": 5895, "s": 5865, "text": "Displays maximum column width" }, { "code": null, "e": 5913, "s": 5895, "text": "display.precision" }, { "code": null, "e": 5952, "s": 5913, "text": "Displays precision for decimal numbers" }, { "code": null, "e": 5989, "s": 5952, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6005, "s": 5989, "text": " Malhar Lathkar" }, { "code": null, "e": 6038, "s": 6005, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6057, "s": 6038, "text": " Arnab Chakraborty" }, { "code": null, "e": 6092, "s": 6057, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6114, "s": 6092, "text": " In28Minutes Official" }, { "code": null, "e": 6148, "s": 6114, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6176, "s": 6148, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6211, "s": 6176, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6225, "s": 6211, "text": " Lets Kode It" }, { "code": null, "e": 6258, "s": 6225, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6275, "s": 6258, "text": " Abhilash Nelson" }, { "code": null, "e": 6282, "s": 6275, "text": " Print" }, { "code": null, "e": 6293, "s": 6282, "text": " Add Notes" } ]
First Bad Version in Python
Suppose in a company, one product manager is leading a team who develops a new product. Suppose latest version fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version will be bad. So we have an array A with n elements [1, 2, ... n] and we have to find the first bad version from this array. Consider we have a function isBadVersion(version_id), this will return whether the version is bad or not. For an example, suppose n = 5, and version = 4 is first bad version. So if the isBadVersion(3) returns false isBadVersion(5) returns true, and isBadVersion(4) also returns true, then the first bad version is 4 To solve this, we will follow these steps − When n < 2, then return n Perform binary search approach to detect bad version using the given function. Let us see the following implementation to get better understanding − Live Demo first_bad = 0 def isBadVersion(version): if version >= first_bad: return True return False class Solution: def firstBadVersion(self, n): if n <2: return n start = 1 end = n while(start<=end): mid = (start+end)//2 if isBadVersion(mid) and not isBadVersion(mid-1): return mid elif isBadVersion(mid-1): end = mid-1 else: start = mid+1 ob1 = Solution() first_bad = 4 op = ob1.firstBadVersion(5) print(op) 5 4 4
[ { "code": null, "e": 1422, "s": 1062, "text": "Suppose in a company, one product manager is leading a team who develops a new product. Suppose latest version fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version will be bad. So we have an array A with n elements [1, 2, ... n] and we have to find the first bad version from this array." }, { "code": null, "e": 1738, "s": 1422, "text": "Consider we have a function isBadVersion(version_id), this will return whether the version is bad or not. For an example, suppose n = 5, and version = 4 is first bad version. So if the isBadVersion(3) returns false isBadVersion(5) returns true, and isBadVersion(4) also returns true, then the first bad version is 4" }, { "code": null, "e": 1782, "s": 1738, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1808, "s": 1782, "text": "When n < 2, then return n" }, { "code": null, "e": 1887, "s": 1808, "text": "Perform binary search approach to detect bad version using the given function." }, { "code": null, "e": 1957, "s": 1887, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1968, "s": 1957, "text": " Live Demo" }, { "code": null, "e": 2489, "s": 1968, "text": "first_bad = 0\ndef isBadVersion(version):\n if version >= first_bad:\n return True\n return False\nclass Solution:\n def firstBadVersion(self, n):\n if n <2:\n return n\n start = 1\n end = n\n while(start<=end):\n mid = (start+end)//2\n if isBadVersion(mid) and not isBadVersion(mid-1):\n return mid\n elif isBadVersion(mid-1):\n end = mid-1\n else:\n start = mid+1\nob1 = Solution()\nfirst_bad = 4\nop = ob1.firstBadVersion(5)\nprint(op)" }, { "code": null, "e": 2493, "s": 2489, "text": "5\n4" }, { "code": null, "e": 2495, "s": 2493, "text": "4" } ]
How to Automate the Storage using Dropbox API in Python ?
21 Apr, 2021 In this Data Era Storing, Managing, and organizing the Data is an important factor considered by every business. Dropbox is one of the most popular cloud storage systems on the market, and it continues to improve its features. In this article, we will be demonstrating how one can connect to dropbox API using Python and perform Storage Automation efficiently. Go to https://www.dropbox.com/developers/apps/create, You will see a Page like this. Select the “Scoped Access” option and in step 2 select “Full Dropbox”, Name your app with any significant name. In the Oauth2 Section, Set Access Token Expiration to “No Expiration“, generate an Access Token. Go to Permissions Tab, Select Appropriate Permissions that are required, and click Submit. With The Token Key Generated from the Above steps, We can use this token to connect to dropbox and perform storage Automation. You can install the python library using the below command: pip install dropbox Demonstration video to generate a token: Use the token generated to connect to dropbox and create an object. Python3 # importing necessary librariesimport dropbox # Token Generated from dropboxTOKEN = "access_token" # Establish connectiondef connect_to_dropbox(): try: dbx = dropbox.Dropbox(TOKEN) print('Connected to Dropbox successfully') except Exception as e: print(str(e)) return dbx dbx = connect_to_dropbox() Output: Connected to Dropbox successfully We have successfully connected to Dropbox. We can now list folders/files, read files, upload files, delete files, etc. First, call the above method to connect and create a dropbox object, then assign a path for the folder to be scanned, then iterate through the older using file_list_folder() method and for a loop. Python3 # explicit function to list filesdef list_files_in_folder(): # here dbx is an object which is obtained # by connecting to dropbox via token dbx = connect_to_dropbox() try: folder_path = "/folder_path" # dbx object contains all functions that # are required to perform actions with dropbox files = dbx.files_list_folder(folder_path).entries print("------------Listing Files in Folder------------ ") for file in files: # listing print(file.name) except Exception as e: print(str(e)) list_files_in_folder() Output: Now we have successfully connected to dropbox using python, Listed the Folders present in it. python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 390, "s": 28, "text": "In this Data Era Storing, Managing, and organizing the Data is an important factor considered by every business. Dropbox is one of the most popular cloud storage systems on the market, and it continues to improve its features. In this article, we will be demonstrating how one can connect to dropbox API using Python and perform Storage Automation efficiently." }, { "code": null, "e": 588, "s": 390, "text": " Go to https://www.dropbox.com/developers/apps/create, You will see a Page like this. Select the “Scoped Access” option and in step 2 select “Full Dropbox”, Name your app with any significant name." }, { "code": null, "e": 685, "s": 588, "text": "In the Oauth2 Section, Set Access Token Expiration to “No Expiration“, generate an Access Token." }, { "code": null, "e": 776, "s": 685, "text": "Go to Permissions Tab, Select Appropriate Permissions that are required, and click Submit." }, { "code": null, "e": 963, "s": 776, "text": "With The Token Key Generated from the Above steps, We can use this token to connect to dropbox and perform storage Automation. You can install the python library using the below command:" }, { "code": null, "e": 984, "s": 963, "text": "pip install dropbox " }, { "code": null, "e": 1025, "s": 984, "text": "Demonstration video to generate a token:" }, { "code": null, "e": 1093, "s": 1025, "text": "Use the token generated to connect to dropbox and create an object." }, { "code": null, "e": 1101, "s": 1093, "text": "Python3" }, { "code": "# importing necessary librariesimport dropbox # Token Generated from dropboxTOKEN = \"access_token\" # Establish connectiondef connect_to_dropbox(): try: dbx = dropbox.Dropbox(TOKEN) print('Connected to Dropbox successfully') except Exception as e: print(str(e)) return dbx dbx = connect_to_dropbox()", "e": 1449, "s": 1101, "text": null }, { "code": null, "e": 1457, "s": 1449, "text": "Output:" }, { "code": null, "e": 1491, "s": 1457, "text": "Connected to Dropbox successfully" }, { "code": null, "e": 1612, "s": 1491, "text": "We have successfully connected to Dropbox. We can now list folders/files, read files, upload files, delete files, etc. " }, { "code": null, "e": 1809, "s": 1612, "text": "First, call the above method to connect and create a dropbox object, then assign a path for the folder to be scanned, then iterate through the older using file_list_folder() method and for a loop." }, { "code": null, "e": 1817, "s": 1809, "text": "Python3" }, { "code": "# explicit function to list filesdef list_files_in_folder(): # here dbx is an object which is obtained # by connecting to dropbox via token dbx = connect_to_dropbox() try: folder_path = \"/folder_path\" # dbx object contains all functions that # are required to perform actions with dropbox files = dbx.files_list_folder(folder_path).entries print(\"------------Listing Files in Folder------------ \") for file in files: # listing print(file.name) except Exception as e: print(str(e)) list_files_in_folder()", "e": 2459, "s": 1817, "text": null }, { "code": null, "e": 2467, "s": 2459, "text": "Output:" }, { "code": null, "e": 2561, "s": 2467, "text": "Now we have successfully connected to dropbox using python, Listed the Folders present in it." }, { "code": null, "e": 2576, "s": 2561, "text": "python-utility" }, { "code": null, "e": 2583, "s": 2576, "text": "Python" } ]
runBlocking in Kotlin Coroutines with Example
10 Sep, 2021 Prerequisite: Kotlin Coroutines on Android Suspend Function In Kotlin Coroutines As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI and many more things. As the delay function is a suspend function it has to be called from the coroutine or another suspend function. According to official documentation, the runBlocking() function may be defined as: runBlocking is a coroutine function. By not providing any context, it will get run on the main thread.Runs a new coroutine and blocks the current thread interruptible until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests. Kotlin // sample program in android studio to demonstrate coroutinespackage com.example.gfgcoroutines import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG:String="Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) GlobalScope.launch(Dispatchers.Main) { delay(3000) Log.d(TAG,"User is in the Global Scope ") Toast.makeText(applicationContext,"User is in the Global Scope ",Toast.LENGTH_SHORT).show() } Log.d(TAG,"User is not in the Global Scope ") Toast.makeText(applicationContext,"User is not in the Global Scope ",Toast.LENGTH_SHORT).show() }} Log Output: Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image) As it can be seen in the log-output that the “User is in the Global Scope” gets printed after the Log of “User is not in the Global Scope” which shows that the GlobalScope start a coroutine, which does not block the main thread, and the other operations can be performed while the delay time get’s over. But when someone wants to call only the suspend function and do not need the coroutine behavior, one can call the suspend function from the runBlocking. So when one wants to call any suspend functions such as delay() and do not care about the asynchronous nature, one can use the runBlocking function. The difference between the calling the suspend function from the GlobalScope.launch{ } and calling the suspend function (eg delay()) from runBlocking{ } is that runBlocking will block the main thread or the thread in which it is used and GlobalScope.launch{ } will not block the main thread, in this case, UI operations can be performed while the thread is delayed. Another use-case of runBlocking is for testing of the JUnit, in which one needs to access the suspend function from within the test function. One case also uses the runBlocking in order to learn the coroutines in-depth in order to figure out how they work behind the scenes. Let’s see from the examples below how runBlocking actually works: Kotlin package com.example.gfgcoroutinesimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG="Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"Before run-blocking") runBlocking { Log.d(TAG,"just entered into the runBlocking ") delay(5000) Log.d(TAG,"start of the run-blocking") Log.d(TAG,"End of the runBlocking") } Log.d(TAG,"after the run blocking") }} Log Output: Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image) The Round oval circle in the above log-output shows the timestamps in which the log output is being printed. It can be clearly seen that when the “just entered into the runBlocking” the delay of 5 sec is encountered, so other operations can not be performed and have to wait for 5 seconds. The Log statement “after the run blocking” which is outside of the runBlocking function too, has to wait for the whole runBlocking function to finish its work. Let’s take another example and try to learn how runBlocking works and how different coroutines can be launched within it. Kotlin package com.example.gfgcoroutinesimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG="Main Activity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,"Before run-blocking") runBlocking { Log.d(TAG,"just entered into the runBlocking ") delay(5000) launch(Dispatchers.IO) { delay(3000L) Log.d(TAG,"Finished to coroutine 1") } launch(Dispatchers.IO) { delay(3000L) Log.d(TAG,"Finished to coroutine 2") } Log.d(TAG,"start of the run-blocking") Log.d(TAG,"End of the runBlocking") } Log.d(TAG,"after the run blocking") GlobalScope.launch { Log.d(TAG,"Logging in the globalScope") } }} Log Output: Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image) It can be seen in the above log-output that both GlobalScope and launch will execute after the delay of runBlocking. As both the coroutine which are launched within runBlocking with launch function will be executed within the same thread, it seems like both the coroutine are running in parallel, but it is not possible since both are running in the same thread, but they are running in an asynchronous manner. So it can be said that users should use coroutine runBlocking only when the user wants to do a JUnit test or want to call only the suspend functions. sagar0719kumar android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Sep, 2021" }, { "code": null, "e": 42, "s": 28, "text": "Prerequisite:" }, { "code": null, "e": 71, "s": 42, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 109, "s": 71, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 462, "s": 109, "text": "As it is known that when the user calls the delay() function in any coroutine, it will not block the thread in which it is running, while the delay() function is called one can do some other operations like updating UI and many more things. As the delay function is a suspend function it has to be called from the coroutine or another suspend function." }, { "code": null, "e": 545, "s": 462, "text": "According to official documentation, the runBlocking() function may be defined as:" }, { "code": null, "e": 926, "s": 545, "text": "runBlocking is a coroutine function. By not providing any context, it will get run on the main thread.Runs a new coroutine and blocks the current thread interruptible until its completion. This function should not be used from a coroutine. It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests." }, { "code": null, "e": 933, "s": 926, "text": "Kotlin" }, { "code": "// sample program in android studio to demonstrate coroutinespackage com.example.gfgcoroutines import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG:String=\"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) GlobalScope.launch(Dispatchers.Main) { delay(3000) Log.d(TAG,\"User is in the Global Scope \") Toast.makeText(applicationContext,\"User is in the Global Scope \",Toast.LENGTH_SHORT).show() } Log.d(TAG,\"User is not in the Global Scope \") Toast.makeText(applicationContext,\"User is not in the Global Scope \",Toast.LENGTH_SHORT).show() }}", "e": 1869, "s": 933, "text": null }, { "code": null, "e": 1881, "s": 1869, "text": "Log Output:" }, { "code": null, "e": 1970, "s": 1881, "text": "Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)" }, { "code": null, "e": 2942, "s": 1970, "text": "As it can be seen in the log-output that the “User is in the Global Scope” gets printed after the Log of “User is not in the Global Scope” which shows that the GlobalScope start a coroutine, which does not block the main thread, and the other operations can be performed while the delay time get’s over. But when someone wants to call only the suspend function and do not need the coroutine behavior, one can call the suspend function from the runBlocking. So when one wants to call any suspend functions such as delay() and do not care about the asynchronous nature, one can use the runBlocking function. The difference between the calling the suspend function from the GlobalScope.launch{ } and calling the suspend function (eg delay()) from runBlocking{ } is that runBlocking will block the main thread or the thread in which it is used and GlobalScope.launch{ } will not block the main thread, in this case, UI operations can be performed while the thread is delayed." }, { "code": null, "e": 3283, "s": 2942, "text": "Another use-case of runBlocking is for testing of the JUnit, in which one needs to access the suspend function from within the test function. One case also uses the runBlocking in order to learn the coroutines in-depth in order to figure out how they work behind the scenes. Let’s see from the examples below how runBlocking actually works:" }, { "code": null, "e": 3290, "s": 3283, "text": "Kotlin" }, { "code": "package com.example.gfgcoroutinesimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG=\"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,\"Before run-blocking\") runBlocking { Log.d(TAG,\"just entered into the runBlocking \") delay(5000) Log.d(TAG,\"start of the run-blocking\") Log.d(TAG,\"End of the runBlocking\") } Log.d(TAG,\"after the run blocking\") }}", "e": 4104, "s": 3290, "text": null }, { "code": null, "e": 4116, "s": 4104, "text": "Log Output:" }, { "code": null, "e": 4206, "s": 4116, "text": "Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)" }, { "code": null, "e": 4778, "s": 4206, "text": "The Round oval circle in the above log-output shows the timestamps in which the log output is being printed. It can be clearly seen that when the “just entered into the runBlocking” the delay of 5 sec is encountered, so other operations can not be performed and have to wait for 5 seconds. The Log statement “after the run blocking” which is outside of the runBlocking function too, has to wait for the whole runBlocking function to finish its work. Let’s take another example and try to learn how runBlocking works and how different coroutines can be launched within it." }, { "code": null, "e": 4785, "s": 4778, "text": "Kotlin" }, { "code": "package com.example.gfgcoroutinesimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.widget.Toastimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { val TAG=\"Main Activity\" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d(TAG,\"Before run-blocking\") runBlocking { Log.d(TAG,\"just entered into the runBlocking \") delay(5000) launch(Dispatchers.IO) { delay(3000L) Log.d(TAG,\"Finished to coroutine 1\") } launch(Dispatchers.IO) { delay(3000L) Log.d(TAG,\"Finished to coroutine 2\") } Log.d(TAG,\"start of the run-blocking\") Log.d(TAG,\"End of the runBlocking\") } Log.d(TAG,\"after the run blocking\") GlobalScope.launch { Log.d(TAG,\"Logging in the globalScope\") } }}", "e": 5989, "s": 4785, "text": null }, { "code": null, "e": 6001, "s": 5989, "text": "Log Output:" }, { "code": null, "e": 6091, "s": 6001, "text": "Log-Output of the above program (Timestamps in seconds is shown by Oval Circle in image)" }, { "code": null, "e": 6652, "s": 6091, "text": "It can be seen in the above log-output that both GlobalScope and launch will execute after the delay of runBlocking. As both the coroutine which are launched within runBlocking with launch function will be executed within the same thread, it seems like both the coroutine are running in parallel, but it is not possible since both are running in the same thread, but they are running in an asynchronous manner. So it can be said that users should use coroutine runBlocking only when the user wants to do a JUnit test or want to call only the suspend functions." }, { "code": null, "e": 6667, "s": 6652, "text": "sagar0719kumar" }, { "code": null, "e": 6675, "s": 6667, "text": "android" }, { "code": null, "e": 6683, "s": 6675, "text": "Android" }, { "code": null, "e": 6690, "s": 6683, "text": "Kotlin" }, { "code": null, "e": 6698, "s": 6690, "text": "Android" } ]
Format Specifiers in Julia - GeeksforGeeks
12 Oct, 2020 Format Specifiers are used to format the Input and Output of a Programming language. It tell the compiler about the data type of the Input that is being passed to it. Julia contains a package Printf and using its macro @printf takes input string value to be formatted and accepts parameters as variables to apply to the string.@printf is a macro in Julia, which has the following syntax: @printf([io::IOstream], "%Fmt", args...) It is used to print a space before the variable value over which it is specified. The variable value can belong to any data type, numeric, or strings. Julia # declaring a variable string val = "Space" # importing moduleusing Printf # adding space identifier after a string “Added” @printf("Added, % s \n", val) Output: Added, Space On specifying a numeric value as argument with the %+d format, ‘+’ sign is added before it. On specifying floating-point number as argument only the part before decimal is returned as output with +ve sign. Julia # declaring numeric value num1 = 111 # importing required moduleusing Printf # adding positive sign before numerical value@printf("Adding %+d", num1) # declaring floating point numbernum2 = 10.1 # adding positive sign before floating number@printf("Adding positive sign %+d", num2) Output: +111 +11 The floating numbers are converted to integers with a positive sign. The output returned can be explicitly left-justified by applying a minus sign after the symbol %. The following code, for example, % 16.4f justifies the passed parameter in a field of 16 characters with two decimal places. Julia # importing moduleusing Printf # declaring a floating point numbernum1 = 10.1234 # left justifying the number @printf("|%-16.4f|", num1) Output: |10.1234 | This format specifier can be used to insert a % sign. There are no parameters specified explicitly. It can be used for both strings or numbers. Julia # importing moduleusing Printf # embedded in numerical values@printf("2 %% 8 = 0") # embedding in strings @printf("hello %% gfg ") Output: 2 % 8 = 0 hello % gfg This representation is used to donate a hexadecimal number of the specified numeric value in either lower case or upper case characters %x in lower case and %X in upper case. Only numerical values can be specified as parameters in this argument list. Julia # importing moduleusing Printf # converting 100 to lower case hexadecimal@printf("% x", 100) # converting 13 to lower case hexadecimal@printf("% x", 13) # converting 234 to upper case hexadecimal@printf("% X", 234) Output: 64 d EA This representation is used to denote the number specified as the argument in the octal form. The variable to be converted cannot be a floating-point number. Julia # importing moduleusing Printf # converting 372 from decimal # to octal representation@printf("% o", 372) # converting 9 to octal@printf("% o", 9) Output: 564 11 This format specifier is used to express the value in a scientific way with %E expressing the output in upper case characters and %e in lower case characters. Julia using Printf # converting numerical and floating numbers# scientific notation in lower case@printf("% e", 100)@printf("% e", 12.56) # converting numerical and floating numbers# scientific notation in upper case@printf("% E", 100)@printf("% E", 99.78) Output: 1.000000e+02 1.256000e+01 1.000000E+02 9.978000E+01 Used to convert a number into floating-point integer values. Works both the numerical and decimal point numbers. It appends exactly 6 digits after the decimal, by default. We can specify the number of digits in %.xf parameter, where x indicates the number of digits. Julia using Printf # converting numerical to decimal point@printf("% f", 100) # converting floating to decimal point@printf("% f", 12.56) # printing decimal number upto 4 places only@printf("%.4f", 12.56) Output: 100.000000 12.560000 12.5600 Julia Input/Output Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Get array dimensions and size of a dimension in Julia - size() Method Searching in Array for a given element in Julia Find maximum element along with its index in Julia - findmax() Method Working with Excel Files in Julia Getting the maximum value from a list in Julia - max() Method Get number of elements of array in Julia - length() Method Exception handling in Julia Working with Date and Time in Julia Getting the absolute value of a number in Julia - abs() Method NamedTuple in Julia
[ { "code": null, "e": 24544, "s": 24516, "text": "\n12 Oct, 2020" }, { "code": null, "e": 24932, "s": 24544, "text": "Format Specifiers are used to format the Input and Output of a Programming language. It tell the compiler about the data type of the Input that is being passed to it. Julia contains a package Printf and using its macro @printf takes input string value to be formatted and accepts parameters as variables to apply to the string.@printf is a macro in Julia, which has the following syntax:" }, { "code": null, "e": 24975, "s": 24932, "text": "@printf([io::IOstream], \"%Fmt\", args...)\n\n" }, { "code": null, "e": 25127, "s": 24975, "text": "It is used to print a space before the variable value over which it is specified. The variable value can belong to any data type, numeric, or strings. " }, { "code": null, "e": 25133, "s": 25127, "text": "Julia" }, { "code": "# declaring a variable string val = \"Space\" # importing moduleusing Printf # adding space identifier after a string “Added” @printf(\"Added, % s \\n\", val)", "e": 25290, "s": 25133, "text": null }, { "code": null, "e": 25298, "s": 25290, "text": "Output:" }, { "code": null, "e": 25313, "s": 25298, "text": "Added, Space \n" }, { "code": null, "e": 25520, "s": 25313, "text": "On specifying a numeric value as argument with the %+d format, ‘+’ sign is added before it. On specifying floating-point number as argument only the part before decimal is returned as output with +ve sign. " }, { "code": null, "e": 25526, "s": 25520, "text": "Julia" }, { "code": "# declaring numeric value num1 = 111 # importing required moduleusing Printf # adding positive sign before numerical value@printf(\"Adding %+d\", num1) # declaring floating point numbernum2 = 10.1 # adding positive sign before floating number@printf(\"Adding positive sign %+d\", num2)", "e": 25812, "s": 25526, "text": null }, { "code": null, "e": 25820, "s": 25812, "text": "Output:" }, { "code": null, "e": 25831, "s": 25820, "text": "+111\n+11\n\n" }, { "code": null, "e": 25900, "s": 25831, "text": "The floating numbers are converted to integers with a positive sign." }, { "code": null, "e": 26124, "s": 25900, "text": "The output returned can be explicitly left-justified by applying a minus sign after the symbol %. The following code, for example, % 16.4f justifies the passed parameter in a field of 16 characters with two decimal places. " }, { "code": null, "e": 26130, "s": 26124, "text": "Julia" }, { "code": "# importing moduleusing Printf # declaring a floating point numbernum1 = 10.1234 # left justifying the number @printf(\"|%-16.4f|\", num1)", "e": 26269, "s": 26130, "text": null }, { "code": null, "e": 26277, "s": 26269, "text": "Output:" }, { "code": null, "e": 26297, "s": 26277, "text": "|10.1234 |\n" }, { "code": null, "e": 26442, "s": 26297, "text": "This format specifier can be used to insert a % sign. There are no parameters specified explicitly. It can be used for both strings or numbers. " }, { "code": null, "e": 26448, "s": 26442, "text": "Julia" }, { "code": "# importing moduleusing Printf # embedded in numerical values@printf(\"2 %% 8 = 0\") # embedding in strings @printf(\"hello %% gfg \")", "e": 26581, "s": 26448, "text": null }, { "code": null, "e": 26589, "s": 26581, "text": "Output:" }, { "code": null, "e": 26612, "s": 26589, "text": "2 % 8 = 0\nhello % gfg\n" }, { "code": null, "e": 26864, "s": 26612, "text": "This representation is used to donate a hexadecimal number of the specified numeric value in either lower case or upper case characters %x in lower case and %X in upper case. Only numerical values can be specified as parameters in this argument list. " }, { "code": null, "e": 26870, "s": 26864, "text": "Julia" }, { "code": "# importing moduleusing Printf # converting 100 to lower case hexadecimal@printf(\"% x\", 100) # converting 13 to lower case hexadecimal@printf(\"% x\", 13) # converting 234 to upper case hexadecimal@printf(\"% X\", 234)", "e": 27088, "s": 26870, "text": null }, { "code": null, "e": 27096, "s": 27088, "text": "Output:" }, { "code": null, "e": 27106, "s": 27096, "text": "64\nd\nEA\n\n" }, { "code": null, "e": 27265, "s": 27106, "text": "This representation is used to denote the number specified as the argument in the octal form. The variable to be converted cannot be a floating-point number. " }, { "code": null, "e": 27271, "s": 27265, "text": "Julia" }, { "code": "# importing moduleusing Printf # converting 372 from decimal # to octal representation@printf(\"% o\", 372) # converting 9 to octal@printf(\"% o\", 9)", "e": 27420, "s": 27271, "text": null }, { "code": null, "e": 27428, "s": 27420, "text": "Output:" }, { "code": null, "e": 27437, "s": 27428, "text": "564\n11\n\n" }, { "code": null, "e": 27597, "s": 27437, "text": "This format specifier is used to express the value in a scientific way with %E expressing the output in upper case characters and %e in lower case characters. " }, { "code": null, "e": 27603, "s": 27597, "text": "Julia" }, { "code": "using Printf # converting numerical and floating numbers# scientific notation in lower case@printf(\"% e\", 100)@printf(\"% e\", 12.56) # converting numerical and floating numbers# scientific notation in upper case@printf(\"% E\", 100)@printf(\"% E\", 99.78)", "e": 27857, "s": 27603, "text": null }, { "code": null, "e": 27865, "s": 27857, "text": "Output:" }, { "code": null, "e": 27919, "s": 27865, "text": "1.000000e+02\n1.256000e+01\n1.000000E+02\n9.978000E+01\n\n" }, { "code": null, "e": 28188, "s": 27919, "text": "Used to convert a number into floating-point integer values. Works both the numerical and decimal point numbers. It appends exactly 6 digits after the decimal, by default. We can specify the number of digits in %.xf parameter, where x indicates the number of digits. " }, { "code": null, "e": 28194, "s": 28188, "text": "Julia" }, { "code": "using Printf # converting numerical to decimal point@printf(\"% f\", 100) # converting floating to decimal point@printf(\"% f\", 12.56) # printing decimal number upto 4 places only@printf(\"%.4f\", 12.56)", "e": 28396, "s": 28194, "text": null }, { "code": null, "e": 28404, "s": 28396, "text": "Output:" }, { "code": null, "e": 28435, "s": 28404, "text": "100.000000\n12.560000\n12.5600\n\n" }, { "code": null, "e": 28454, "s": 28435, "text": "Julia Input/Output" }, { "code": null, "e": 28461, "s": 28454, "text": "Picked" }, { "code": null, "e": 28467, "s": 28461, "text": "Julia" }, { "code": null, "e": 28565, "s": 28467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28574, "s": 28565, "text": "Comments" }, { "code": null, "e": 28587, "s": 28574, "text": "Old Comments" }, { "code": null, "e": 28657, "s": 28587, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 28705, "s": 28657, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 28775, "s": 28705, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 28809, "s": 28775, "text": "Working with Excel Files in Julia" }, { "code": null, "e": 28871, "s": 28809, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 28930, "s": 28871, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 28958, "s": 28930, "text": "Exception handling in Julia" }, { "code": null, "e": 28994, "s": 28958, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 29057, "s": 28994, "text": "Getting the absolute value of a number in Julia - abs() Method" } ]
Reverse String II in Python
Suppose we have a string and an integer k, we have to reverse the first k characters for every 2k characters counting from the start of the string. If there is no sufficient character left, then reverse all of them. If there are less than 2k characters but greater than or equal to k characters, then reverse the first k characters and left the other as original. So, if the input is like "abcdefgh" and k = 3, then the output will be "cbadefhg" To solve this, we will follow these steps − l := make a list of characters of s l := make a list of characters of s i := k-1 i := k-1 while i < size of l + k −a := l[from index 0 to i-k+1]b := l[from index i-k+1 to i+1]c := l[from index i+1 to end]l := a concatenate b[from index 0 to end] concatenate ci := i + 2*k while i < size of l + k − a := l[from index 0 to i-k+1] a := l[from index 0 to i-k+1] b := l[from index i-k+1 to i+1] b := l[from index i-k+1 to i+1] c := l[from index i+1 to end] c := l[from index i+1 to end] l := a concatenate b[from index 0 to end] concatenate c l := a concatenate b[from index 0 to end] concatenate c i := i + 2*k i := i + 2*k return string by concatenating each character in l return string by concatenating each character in l Let us see the following implementation to get a better understanding − Live Demo class Solution: def reverseStr(self, s, k): l = list(s) i = k-1 while i < len(l)+k: a = l[:i-k+1] b = l[i-k+1:i+1] c = l[i+1:] l = a + b[::-1] + c i += 2*k return ''.join(l) ob = Solution() print(ob.reverseStr("abcdefg", 3)) "abcdefg", 3 cbadefg
[ { "code": null, "e": 1426, "s": 1062, "text": "Suppose we have a string and an integer k, we have to reverse the first k characters for every 2k characters counting from the start of the string. If there is no sufficient character left, then reverse all of them. If there are less than 2k characters but greater than or equal to k characters, then reverse the first k characters and left the other as original." }, { "code": null, "e": 1508, "s": 1426, "text": "So, if the input is like \"abcdefgh\" and k = 3, then the output will be \"cbadefhg\"" }, { "code": null, "e": 1552, "s": 1508, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1588, "s": 1552, "text": "l := make a list of characters of s" }, { "code": null, "e": 1624, "s": 1588, "text": "l := make a list of characters of s" }, { "code": null, "e": 1633, "s": 1624, "text": "i := k-1" }, { "code": null, "e": 1642, "s": 1633, "text": "i := k-1" }, { "code": null, "e": 1824, "s": 1642, "text": "while i < size of l + k −a := l[from index 0 to i-k+1]b := l[from index i-k+1 to i+1]c := l[from index i+1 to end]l := a concatenate b[from index 0 to end] concatenate ci := i + 2*k" }, { "code": null, "e": 1850, "s": 1824, "text": "while i < size of l + k −" }, { "code": null, "e": 1880, "s": 1850, "text": "a := l[from index 0 to i-k+1]" }, { "code": null, "e": 1910, "s": 1880, "text": "a := l[from index 0 to i-k+1]" }, { "code": null, "e": 1942, "s": 1910, "text": "b := l[from index i-k+1 to i+1]" }, { "code": null, "e": 1974, "s": 1942, "text": "b := l[from index i-k+1 to i+1]" }, { "code": null, "e": 2004, "s": 1974, "text": "c := l[from index i+1 to end]" }, { "code": null, "e": 2034, "s": 2004, "text": "c := l[from index i+1 to end]" }, { "code": null, "e": 2090, "s": 2034, "text": "l := a concatenate b[from index 0 to end] concatenate c" }, { "code": null, "e": 2146, "s": 2090, "text": "l := a concatenate b[from index 0 to end] concatenate c" }, { "code": null, "e": 2159, "s": 2146, "text": "i := i + 2*k" }, { "code": null, "e": 2172, "s": 2159, "text": "i := i + 2*k" }, { "code": null, "e": 2223, "s": 2172, "text": "return string by concatenating each character in l" }, { "code": null, "e": 2274, "s": 2223, "text": "return string by concatenating each character in l" }, { "code": null, "e": 2346, "s": 2274, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 2357, "s": 2346, "text": " Live Demo" }, { "code": null, "e": 2655, "s": 2357, "text": "class Solution:\n def reverseStr(self, s, k):\n l = list(s)\n i = k-1\n while i < len(l)+k:\n a = l[:i-k+1]\n b = l[i-k+1:i+1]\n c = l[i+1:]\n l = a + b[::-1] + c\n i += 2*k\n return ''.join(l)\n\nob = Solution()\nprint(ob.reverseStr(\"abcdefg\", 3))" }, { "code": null, "e": 2668, "s": 2655, "text": "\"abcdefg\", 3" }, { "code": null, "e": 2676, "s": 2668, "text": "cbadefg" } ]
UInt64.MaxValue Field in C# with Examples - GeeksforGeeks
01 May, 2019 The MaxValue field of UInt64 Struct is used to represent the maximum value of the 64-bit unsigned long integer. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 18446744073709551615. Its hexadecimal value is 0xFFFFFFFFFFFFFFFF. It is used to avoid the OverflowException at runtime. Syntax: public const ulong MaxValue = 18446744073709551615; Return Value: This field always returns 18446744073709551615. Example: // C# program to illustrate the// UInt64.MaxValue Fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum // value of UInt64 struct Console.WriteLine("Maximum Value is: " + UInt64.MaxValue); // taking a variable ulong var1 = 93422337368375807; if (var1.Equals(UInt64.MaxValue)) { Console.WriteLine("Equal..!!"); Console.WriteLine("Type of var1 is: {0}", var1.GetTypeCode()); } else { Console.WriteLine("Not equal..!!"); Console.WriteLine("Type of var1 is: {0}", var1.GetTypeCode()); } }} Output: Maximum Value is: 18446744073709551615 Not equal..!! Type of var1 is: UInt64 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.uint64.maxvalue?view=netstandard-2.1 CSharp-UInt64-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object C# | Constructors Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Abstract Classes C# | Delegates Extension Method in C# C# | Data Types HashSet in C# with Examples Common Language Runtime (CLR) in C#
[ { "code": null, "e": 24502, "s": 24474, "text": "\n01 May, 2019" }, { "code": null, "e": 24857, "s": 24502, "text": "The MaxValue field of UInt64 Struct is used to represent the maximum value of the 64-bit unsigned long integer. The value of this field is constant means that the user cannot change the value of this field. The value of this field is 18446744073709551615. Its hexadecimal value is 0xFFFFFFFFFFFFFFFF. It is used to avoid the OverflowException at runtime." }, { "code": null, "e": 24865, "s": 24857, "text": "Syntax:" }, { "code": null, "e": 24917, "s": 24865, "text": "public const ulong MaxValue = 18446744073709551615;" }, { "code": null, "e": 24979, "s": 24917, "text": "Return Value: This field always returns 18446744073709551615." }, { "code": null, "e": 24988, "s": 24979, "text": "Example:" }, { "code": "// C# program to illustrate the// UInt64.MaxValue Fieldusing System; class GFG { // Main Method static public void Main() { // display the Maximum // value of UInt64 struct Console.WriteLine(\"Maximum Value is: \" + UInt64.MaxValue); // taking a variable ulong var1 = 93422337368375807; if (var1.Equals(UInt64.MaxValue)) { Console.WriteLine(\"Equal..!!\"); Console.WriteLine(\"Type of var1 is: {0}\", var1.GetTypeCode()); } else { Console.WriteLine(\"Not equal..!!\"); Console.WriteLine(\"Type of var1 is: {0}\", var1.GetTypeCode()); } }}", "e": 25724, "s": 24988, "text": null }, { "code": null, "e": 25732, "s": 25724, "text": "Output:" }, { "code": null, "e": 25810, "s": 25732, "text": "Maximum Value is: 18446744073709551615\nNot equal..!!\nType of var1 is: UInt64\n" }, { "code": null, "e": 25821, "s": 25810, "text": "Reference:" }, { "code": null, "e": 25909, "s": 25821, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.uint64.maxvalue?view=netstandard-2.1" }, { "code": null, "e": 25930, "s": 25909, "text": "CSharp-UInt64-Struct" }, { "code": null, "e": 25933, "s": 25930, "text": "C#" }, { "code": null, "e": 26031, "s": 25933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26040, "s": 26031, "text": "Comments" }, { "code": null, "e": 26053, "s": 26040, "text": "Old Comments" }, { "code": null, "e": 26075, "s": 26053, "text": "C# | Class and Object" }, { "code": null, "e": 26093, "s": 26075, "text": "C# | Constructors" }, { "code": null, "e": 26124, "s": 26093, "text": "Introduction to .NET Framework" }, { "code": null, "e": 26170, "s": 26124, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 26192, "s": 26170, "text": "C# | Abstract Classes" }, { "code": null, "e": 26207, "s": 26192, "text": "C# | Delegates" }, { "code": null, "e": 26230, "s": 26207, "text": "Extension Method in C#" }, { "code": null, "e": 26246, "s": 26230, "text": "C# | Data Types" }, { "code": null, "e": 26274, "s": 26246, "text": "HashSet in C# with Examples" } ]
Draw any polygon in Turtle - Python - GeeksforGeeks
10 Feb, 2020 Prerequisite: Python Turtle Basics Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. turtle drawings are basically drawn using four methods defined in the turtle module. forward(x): moves the turtle(pen) in the forward direction by x unit. backward(x): moves the turtle(pen) in the backward direction by x unit. right(n): rotate the turtle(pen) by n degree in clockwise direction. left(n): rotate the turtle(pen) by n degree in anticlockwise direction. In this article, we will learn how to draw different shaped Polygons using Turtle module. Given the number of sides (n) and length of sides (l), one can easily draw any polygon shape. Let’s try to understand it better with the help of examples. # draw any polygon in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the no of the sides of the polygonn = int(input("Enter the no of the sides of the polygon : ")) # taking input for the length of the sides of the polygonl = int(input("Enter the length of the sides of the polygon : ")) for _ in range(n): turtle.forward(l) turtle.right(360 / n) Input : 10 100 Output : Input : 3 150 Output : Input : 4 150 Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24604, "s": 24576, "text": "\n10 Feb, 2020" }, { "code": null, "e": 24639, "s": 24604, "text": "Prerequisite: Python Turtle Basics" }, { "code": null, "e": 24883, "s": 24639, "text": "Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. turtle drawings are basically drawn using four methods defined in the turtle module." }, { "code": null, "e": 24953, "s": 24883, "text": "forward(x): moves the turtle(pen) in the forward direction by x unit." }, { "code": null, "e": 25025, "s": 24953, "text": "backward(x): moves the turtle(pen) in the backward direction by x unit." }, { "code": null, "e": 25094, "s": 25025, "text": "right(n): rotate the turtle(pen) by n degree in clockwise direction." }, { "code": null, "e": 25166, "s": 25094, "text": "left(n): rotate the turtle(pen) by n degree in anticlockwise direction." }, { "code": null, "e": 25411, "s": 25166, "text": "In this article, we will learn how to draw different shaped Polygons using Turtle module. Given the number of sides (n) and length of sides (l), one can easily draw any polygon shape. Let’s try to understand it better with the help of examples." }, { "code": "# draw any polygon in turtle import turtle # creating turtle pent = turtle.Turtle() # taking input for the no of the sides of the polygonn = int(input(\"Enter the no of the sides of the polygon : \")) # taking input for the length of the sides of the polygonl = int(input(\"Enter the length of the sides of the polygon : \")) for _ in range(n): turtle.forward(l) turtle.right(360 / n)", "e": 25805, "s": 25411, "text": null }, { "code": null, "e": 25813, "s": 25805, "text": "Input :" }, { "code": null, "e": 25820, "s": 25813, "text": "10\n100" }, { "code": null, "e": 25829, "s": 25820, "text": "Output :" }, { "code": null, "e": 25837, "s": 25829, "text": "Input :" }, { "code": null, "e": 25843, "s": 25837, "text": "3\n150" }, { "code": null, "e": 25852, "s": 25843, "text": "Output :" }, { "code": null, "e": 25860, "s": 25852, "text": "Input :" }, { "code": null, "e": 25866, "s": 25860, "text": "4\n150" }, { "code": null, "e": 25875, "s": 25866, "text": "Output :" }, { "code": null, "e": 25889, "s": 25875, "text": "Python-turtle" }, { "code": null, "e": 25896, "s": 25889, "text": "Python" }, { "code": null, "e": 25994, "s": 25896, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26012, "s": 25994, "text": "Python Dictionary" }, { "code": null, "e": 26047, "s": 26012, "text": "Read a file line by line in Python" }, { "code": null, "e": 26069, "s": 26047, "text": "Enumerate() in Python" }, { "code": null, "e": 26101, "s": 26069, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26131, "s": 26101, "text": "Iterate over a list in Python" }, { "code": null, "e": 26173, "s": 26131, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26199, "s": 26173, "text": "Python String | replace()" }, { "code": null, "e": 26242, "s": 26199, "text": "Python program to convert a list to string" }, { "code": null, "e": 26279, "s": 26242, "text": "Create a Pandas DataFrame from Lists" } ]
Sum of even elements of an Array using Recursion - GeeksforGeeks
27 Apr, 2021 Given an array arr[] of integers, the task is to find the sum of even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 Approach: Write a recursive function that takes the array as an argument with the sum variable to store the sum and the index of the element that is under consideration. If the current element at the required index is even then added to the sum else do not update the sum and again call the same method for the next index. The termination condition will be when there is no element left to consider i.e. the passed index is out of the bounds of the given array, print the sum, and return in that case. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <iostream>using namespace std; // Recursive function to find the sum of// even elements from the arrayvoid SumOfEven(int arr[], int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum cout << sum; return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 0; SumOfEven(arr, n - 1, sum); return 0;} // Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Recursive function to find the sum of// even elements from the arraystatic void SumOfEven(int arr[], int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum System.out.print(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = arr.length; int sum = 0; SumOfEven(arr, n - 1, sum);}} // This code is contributed by nidhiva # Python3 implementation of the approach # Recursive function to find the sum of# even elements from the arraydef SumOfEven(arr, i, sum): # If current index is invalid i.e. # all the elements of the array # have been traversed if (i < 0): # Print the sum print(sum); return; # If current element is even if ((arr[i]) % 2 == 0): # Add it to the sum sum += (arr[i]); # Recursive call for the next element SumOfEven(arr, i - 1, sum); # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; n = len(arr); sum = 0; SumOfEven(arr, n - 1, sum); # This code is contributed by PrinciRaj1992 // C# implementation of the approachusing System; class GFG{ // Recursive function to find the sum of// even elements from the arraystatic void SumOfEven(int []arr, int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum Console.Write(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = arr.Length; int sum = 0; SumOfEven(arr, n - 1, sum);}} // This code is contributed by Rajput-Ji <script>// Java script implementation of the approach // Recursive function to find the sum of// even elements from the arrayfunction SumOfEven(arr,i,sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum document.write(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; let n = arr.length; let sum = 0; SumOfEven(arr, n - 1, sum); //contributed by bobby </script> 20 nidhiva Rajput-Ji princiraj1992 gottumukkalabobby Arrays Recursion Arrays Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Trapping Rain Water Building Heap from Array Program to find sum of elements in a given array Reversal algorithm for array rotation Write a program to print all permutations of a given string Program for Tower of Hanoi Recursion Program for Sum of the digits of a given number Backtracking | Introduction
[ { "code": null, "e": 24796, "s": 24768, "text": "\n27 Apr, 2021" }, { "code": null, "e": 24892, "s": 24796, "text": "Given an array arr[] of integers, the task is to find the sum of even elements from the array. " }, { "code": null, "e": 24903, "s": 24892, "text": "Examples: " }, { "code": null, "e": 25023, "s": 24903, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 " }, { "code": null, "e": 25526, "s": 25023, "text": "Approach: Write a recursive function that takes the array as an argument with the sum variable to store the sum and the index of the element that is under consideration. If the current element at the required index is even then added to the sum else do not update the sum and again call the same method for the next index. The termination condition will be when there is no element left to consider i.e. the passed index is out of the bounds of the given array, print the sum, and return in that case. " }, { "code": null, "e": 25578, "s": 25526, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25582, "s": 25578, "text": "C++" }, { "code": null, "e": 25587, "s": 25582, "text": "Java" }, { "code": null, "e": 25595, "s": 25587, "text": "Python3" }, { "code": null, "e": 25598, "s": 25595, "text": "C#" }, { "code": null, "e": 25609, "s": 25598, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <iostream>using namespace std; // Recursive function to find the sum of// even elements from the arrayvoid SumOfEven(int arr[], int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum cout << sum; return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 0; SumOfEven(arr, n - 1, sum); return 0;}", "e": 26351, "s": 25609, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Recursive function to find the sum of// even elements from the arraystatic void SumOfEven(int arr[], int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum System.out.print(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codepublic static void main (String[] args) throws java.lang.Exception{ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = arr.length; int sum = 0; SumOfEven(arr, n - 1, sum);}} // This code is contributed by nidhiva", "e": 27245, "s": 26351, "text": null }, { "code": "# Python3 implementation of the approach # Recursive function to find the sum of# even elements from the arraydef SumOfEven(arr, i, sum): # If current index is invalid i.e. # all the elements of the array # have been traversed if (i < 0): # Print the sum print(sum); return; # If current element is even if ((arr[i]) % 2 == 0): # Add it to the sum sum += (arr[i]); # Recursive call for the next element SumOfEven(arr, i - 1, sum); # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; n = len(arr); sum = 0; SumOfEven(arr, n - 1, sum); # This code is contributed by PrinciRaj1992", "e": 27922, "s": 27245, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Recursive function to find the sum of// even elements from the arraystatic void SumOfEven(int []arr, int i, int sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum Console.Write(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver codepublic static void Main (String[] args){ int []arr = { 1, 2, 3, 4, 5, 6, 7, 8 }; int n = arr.Length; int sum = 0; SumOfEven(arr, n - 1, sum);}} // This code is contributed by Rajput-Ji", "e": 28732, "s": 27922, "text": null }, { "code": "<script>// Java script implementation of the approach // Recursive function to find the sum of// even elements from the arrayfunction SumOfEven(arr,i,sum){ // If current index is invalid i.e. all // the elements of the array // have been traversed if (i < 0) { // Print the sum document.write(sum); return; } // If current element is even if ((arr[i]) % 2 == 0) { // Add it to the sum sum += (arr[i]); } // Recursive call for the next element SumOfEven(arr, i - 1, sum);} // Driver code let arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ]; let n = arr.length; let sum = 0; SumOfEven(arr, n - 1, sum); //contributed by bobby </script>", "e": 29448, "s": 28732, "text": null }, { "code": null, "e": 29451, "s": 29448, "text": "20" }, { "code": null, "e": 29461, "s": 29453, "text": "nidhiva" }, { "code": null, "e": 29471, "s": 29461, "text": "Rajput-Ji" }, { "code": null, "e": 29485, "s": 29471, "text": "princiraj1992" }, { "code": null, "e": 29503, "s": 29485, "text": "gottumukkalabobby" }, { "code": null, "e": 29510, "s": 29503, "text": "Arrays" }, { "code": null, "e": 29520, "s": 29510, "text": "Recursion" }, { "code": null, "e": 29527, "s": 29520, "text": "Arrays" }, { "code": null, "e": 29537, "s": 29527, "text": "Recursion" }, { "code": null, "e": 29635, "s": 29537, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29644, "s": 29635, "text": "Comments" }, { "code": null, "e": 29657, "s": 29644, "text": "Old Comments" }, { "code": null, "e": 29682, "s": 29657, "text": "Window Sliding Technique" }, { "code": null, "e": 29702, "s": 29682, "text": "Trapping Rain Water" }, { "code": null, "e": 29727, "s": 29702, "text": "Building Heap from Array" }, { "code": null, "e": 29776, "s": 29727, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 29814, "s": 29776, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 29874, "s": 29814, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 29901, "s": 29874, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 29911, "s": 29901, "text": "Recursion" }, { "code": null, "e": 29959, "s": 29911, "text": "Program for Sum of the digits of a given number" } ]
Display <div> or <span> over image on :hover in HTML
In order to allow div or span element to appear over an image when mouse hover over the image, this can be done with the help of .image:hover overlay, To position .overlay element absolutely relative to the parent element we give height and width to 100% for all image sizes making parent element inline-block <div class="image"> <img src="..." /> <div class="overlay">Content to be displayed on hover</div> </div> By hiding the .overlay element by default, we use the selector .image:hover .overlay to change the styling on hover. Due to the HTML structure, this works well because .overlay is a descendant element. .image { position:relative; display:inline-block; } .overlay { display:none; } .image:hover .overlay { width:100%; height:100%; background:rgba(0,0,0,.5); position:absolute; top:0; left:0; display:inline-block; -webkit-box-sizing:border-box; -moz-box-sizing:border-box; box-sizing:border-box; /* All other styling - see example */ img { vertical-align:top; } }
[ { "code": null, "e": 1213, "s": 1062, "text": "In order to allow div or span element to appear over an image when mouse hover over the image, this can be done with the help of .image:hover overlay," }, { "code": null, "e": 1372, "s": 1213, "text": "To position .overlay element absolutely relative to the parent element we give height and width to 100% for all image sizes making parent element inline-block" }, { "code": null, "e": 1483, "s": 1372, "text": "<div class=\"image\">\n <img src=\"...\" />\n <div class=\"overlay\">Content to be displayed on hover</div>\n</div>" }, { "code": null, "e": 2101, "s": 1483, "text": "By hiding the .overlay element by default, we use the selector .image:hover .overlay to change the styling on hover. Due to the HTML structure, this works well because .overlay is a descendant element.\n.image {\n position:relative;\n display:inline-block;\n}\n.overlay {\n display:none;\n}\n.image:hover .overlay {\n width:100%;\n height:100%;\n background:rgba(0,0,0,.5);\n position:absolute;\n top:0;\n left:0;\n display:inline-block;\n -webkit-box-sizing:border-box;\n -moz-box-sizing:border-box;\n box-sizing:border-box;\n\n /* All other styling - see example */\n img {\n vertical-align:top;\n }\n}" } ]
Update the date and time values while inserting them in MySQL
Here, we will see an example wherein we are inserting datetime and updating them while using INSERT query. Let us first create a table − mysql> create table DemoTable816 (DueDate datetime); Query OK, 0 rows affected (0.45 sec) Insert some records in the table using insert command. Here is the query to add (minutes / hours / days / months / years) to date when performing INSERT − mysql> insert into DemoTable816 values(date_add(now(),interval 3 minute)); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable816 values(date_add('2018-01-21 00:00:00',interval 3 Hour)); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable816 values(date_add('2016-11-11 12:40:00',interval 3 Day)); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable816 values(date_add('2018-12-01 11:00:00',interval 3 Month)); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable816 values(date_add('2011-03-21 10:00:00',interval 3 Year)); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement − mysql> select *from DemoTable816; This will produce the following output - +---------------------+ | DueDate | +---------------------+ | 2019-08-03 13:08:43 | | 2018-01-21 03:00:00 | | 2016-11-14 12:40:00 | | 2019-03-01 11:00:00 | | 2014-03-21 10:00:00 | +---------------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1169, "s": 1062, "text": "Here, we will see an example wherein we are inserting datetime and updating them while using INSERT query." }, { "code": null, "e": 1199, "s": 1169, "text": "Let us first create a table −" }, { "code": null, "e": 1289, "s": 1199, "text": "mysql> create table DemoTable816 (DueDate datetime);\nQuery OK, 0 rows affected (0.45 sec)" }, { "code": null, "e": 1444, "s": 1289, "text": "Insert some records in the table using insert command. Here is the query to add (minutes / hours / days / months / years) to date when performing INSERT −" }, { "code": null, "e": 2055, "s": 1444, "text": "mysql> insert into DemoTable816 values(date_add(now(),interval 3 minute));\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable816 values(date_add('2018-01-21 00:00:00',interval 3 Hour));\nQuery OK, 1 row affected (0.52 sec)\nmysql> insert into DemoTable816 values(date_add('2016-11-11 12:40:00',interval 3 Day));\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable816 values(date_add('2018-12-01 11:00:00',interval 3 Month));\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable816 values(date_add('2011-03-21 10:00:00',interval 3 Year));\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2115, "s": 2055, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2149, "s": 2115, "text": "mysql> select *from DemoTable816;" }, { "code": null, "e": 2190, "s": 2149, "text": "This will produce the following output -" }, { "code": null, "e": 2431, "s": 2190, "text": "+---------------------+\n| DueDate |\n+---------------------+\n| 2019-08-03 13:08:43 |\n| 2018-01-21 03:00:00 |\n| 2016-11-14 12:40:00 |\n| 2019-03-01 11:00:00 |\n| 2014-03-21 10:00:00 |\n+---------------------+\n5 rows in set (0.00 sec)" } ]
C++ | Exception Handling | Question 11 - GeeksforGeeks
28 Jun, 2021 What happens in C++ when an exception is thrown and not caught anywhere like following program. #include <iostream>using namespace std; int fun() throw (int){ throw 10;} int main() { fun(); return 0;} (A) Compiler error(B) Abnormal program termination(C) Program doesn’t print anything and terminates normally(D) None of the aboveAnswer: (B)Explanation: When an exception is thrown and not caught, the program terminates abnormally.Quiz of this Question C++-Exception Handling Exception Handling C Language C++ Quiz Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Command line arguments in C/C++ Function Pointer in C Substring in C++ Structures in C C++ | Inheritance | Question 7 C++ | new and delete | Question 4 C++ | Operator Overloading | Question 10 C++ | Inheritance | Question 1 C++ | Virtual Functions | Question 2
[ { "code": null, "e": 24758, "s": 24730, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24854, "s": 24758, "text": "What happens in C++ when an exception is thrown and not caught anywhere like following program." }, { "code": "#include <iostream>using namespace std; int fun() throw (int){ throw 10;} int main() { fun(); return 0;} ", "e": 24972, "s": 24854, "text": null }, { "code": null, "e": 25225, "s": 24972, "text": "(A) Compiler error(B) Abnormal program termination(C) Program doesn’t print anything and terminates normally(D) None of the aboveAnswer: (B)Explanation: When an exception is thrown and not caught, the program terminates abnormally.Quiz of this Question" }, { "code": null, "e": 25248, "s": 25225, "text": "C++-Exception Handling" }, { "code": null, "e": 25267, "s": 25248, "text": "Exception Handling" }, { "code": null, "e": 25278, "s": 25267, "text": "C Language" }, { "code": null, "e": 25287, "s": 25278, "text": "C++ Quiz" }, { "code": null, "e": 25385, "s": 25287, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25397, "s": 25385, "text": "fork() in C" }, { "code": null, "e": 25429, "s": 25397, "text": "Command line arguments in C/C++" }, { "code": null, "e": 25451, "s": 25429, "text": "Function Pointer in C" }, { "code": null, "e": 25468, "s": 25451, "text": "Substring in C++" }, { "code": null, "e": 25484, "s": 25468, "text": "Structures in C" }, { "code": null, "e": 25515, "s": 25484, "text": "C++ | Inheritance | Question 7" }, { "code": null, "e": 25549, "s": 25515, "text": "C++ | new and delete | Question 4" }, { "code": null, "e": 25590, "s": 25549, "text": "C++ | Operator Overloading | Question 10" }, { "code": null, "e": 25621, "s": 25590, "text": "C++ | Inheritance | Question 1" } ]
Find the center of the circle using endpoints of diameter - GeeksforGeeks
24 Jan, 2022 Given two endpoint of diameter of a circle (x1, y1) and (x2, y2) find out the center of a circle. Examples : Input : x1 = -9, y1 = 3, and x2 = 5, y2 = –7 Output : -2, –2 Input : x1 = 5, y1 = 3 and x2 = –10 y2 = 4 Output : –2.5, 3.5 Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is : M = ((x 1 + x 2) / 2, (y 1 + y 2) / 2) The center of the circle is the mid point of its diameter so we calculate the mid point of its diameter by using midpoint formula. C++ Java Python3 C# PHP Javascript // C++ program to find the// center of the circle#include <iostream>using namespace std; // function to find the// center of the circlevoid center(int x1, int x2, int y1, int y2){ cout << (float)(x1 + x2) / 2 << ", " << (float)(y1 + y2) / 2;} // Driven Programint main(){ int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); return 0;} // Java program to find the// center of the circleclass GFG { // function to find the // center of the circle static void center(int x1, int x2, int y1, int y2) { System.out.print((float)(x1 + x2) / 2 + ", " + (float)(y1 + y2) / 2); } // Driver Program to test above function public static void main(String arg[]) { int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); }} // This code is contributed by Anant Agarwal. # Python3 program to find# the center of the circle # Function to find the# center of the circledef center(x1, x2, y1, y2) : print(int((x1 + x2) / 2), end= "") print(",", int((y1 + y2) / 2) ) # Driver Codex1 = -9; y1 = 3; x2 = 5; y2 = -7center(x1, x2, y1, y2) # This code is contributed by Smitha Dinesh Semwal // C# program to find the// center of the circleusing System; class GFG { // function to find the // center of the circle static void center(int x1, int x2, int y1, int y2) { Console.WriteLine((float)(x1 + x2) / 2 + ", " + (float)(y1 + y2) / 2); } // Driver Program to test above function public static void Main() { int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); }} // This code is contributed by vt_m. <?php// PHP program to find the// center of the circle // function to find the// center of the circlefunction center($x1, $x2, $y1, $y2){ echo((float)($x1 + $x2) / 2 . ", " . (float)($y1 + $y2) / 2);} // Driven Code$x1 = -9; $y1 = 3; $x2 = 5; $y2 = -7;center($x1, $x2, $y1, $y2); // This code is contributed by Ajit.?> <script> // javascript program to find the// center of the circle // function to find the // center of the circle function center(x1, x2, y1, y2) { document.write((x1 + x2) / 2 + ", " + (y1 + y2) / 2); } // Driver Function let x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); // This code is contributed by susmitakundugoaldanga.</script> Output : -2, -2 jit_t susmitakundugoaldanga ysachin2314 adnanirshad158 circle Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Closest Pair of Points | O(nlogn) Implementation Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24986, "s": 24958, "text": "\n24 Jan, 2022" }, { "code": null, "e": 25097, "s": 24986, "text": "Given two endpoint of diameter of a circle (x1, y1) and (x2, y2) find out the center of a circle. Examples : " }, { "code": null, "e": 25245, "s": 25097, "text": "Input : x1 = -9, y1 = 3, and \n x2 = 5, y2 = –7\nOutput : -2, –2\n\nInput : x1 = 5, y1 = 3 and \n x2 = –10 y2 = 4\nOutput : –2.5, 3.5" }, { "code": null, "e": 25492, "s": 25247, "text": "Midpoint Formula: The midpoint of two points, (x1, y2) and (x2, y2) is : M = ((x 1 + x 2) / 2, (y 1 + y 2) / 2) The center of the circle is the mid point of its diameter so we calculate the mid point of its diameter by using midpoint formula. " }, { "code": null, "e": 25498, "s": 25494, "text": "C++" }, { "code": null, "e": 25503, "s": 25498, "text": "Java" }, { "code": null, "e": 25511, "s": 25503, "text": "Python3" }, { "code": null, "e": 25514, "s": 25511, "text": "C#" }, { "code": null, "e": 25518, "s": 25514, "text": "PHP" }, { "code": null, "e": 25529, "s": 25518, "text": "Javascript" }, { "code": "// C++ program to find the// center of the circle#include <iostream>using namespace std; // function to find the// center of the circlevoid center(int x1, int x2, int y1, int y2){ cout << (float)(x1 + x2) / 2 << \", \" << (float)(y1 + y2) / 2;} // Driven Programint main(){ int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); return 0;}", "e": 25911, "s": 25529, "text": null }, { "code": "// Java program to find the// center of the circleclass GFG { // function to find the // center of the circle static void center(int x1, int x2, int y1, int y2) { System.out.print((float)(x1 + x2) / 2 + \", \" + (float)(y1 + y2) / 2); } // Driver Program to test above function public static void main(String arg[]) { int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); }} // This code is contributed by Anant Agarwal.", "e": 26449, "s": 25911, "text": null }, { "code": "# Python3 program to find# the center of the circle # Function to find the# center of the circledef center(x1, x2, y1, y2) : print(int((x1 + x2) / 2), end= \"\") print(\",\", int((y1 + y2) / 2) ) # Driver Codex1 = -9; y1 = 3; x2 = 5; y2 = -7center(x1, x2, y1, y2) # This code is contributed by Smitha Dinesh Semwal", "e": 26767, "s": 26449, "text": null }, { "code": "// C# program to find the// center of the circleusing System; class GFG { // function to find the // center of the circle static void center(int x1, int x2, int y1, int y2) { Console.WriteLine((float)(x1 + x2) / 2 + \", \" + (float)(y1 + y2) / 2); } // Driver Program to test above function public static void Main() { int x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); }} // This code is contributed by vt_m.", "e": 27301, "s": 26767, "text": null }, { "code": "<?php// PHP program to find the// center of the circle // function to find the// center of the circlefunction center($x1, $x2, $y1, $y2){ echo((float)($x1 + $x2) / 2 . \", \" . (float)($y1 + $y2) / 2);} // Driven Code$x1 = -9; $y1 = 3; $x2 = 5; $y2 = -7;center($x1, $x2, $y1, $y2); // This code is contributed by Ajit.?>", "e": 27643, "s": 27301, "text": null }, { "code": "<script> // javascript program to find the// center of the circle // function to find the // center of the circle function center(x1, x2, y1, y2) { document.write((x1 + x2) / 2 + \", \" + (y1 + y2) / 2); } // Driver Function let x1 = -9, y1 = 3, x2 = 5, y2 = -7; center(x1, x2, y1, y2); // This code is contributed by susmitakundugoaldanga.</script>", "e": 28076, "s": 27643, "text": null }, { "code": null, "e": 28087, "s": 28076, "text": "Output : " }, { "code": null, "e": 28094, "s": 28087, "text": "-2, -2" }, { "code": null, "e": 28102, "s": 28096, "text": "jit_t" }, { "code": null, "e": 28124, "s": 28102, "text": "susmitakundugoaldanga" }, { "code": null, "e": 28136, "s": 28124, "text": "ysachin2314" }, { "code": null, "e": 28151, "s": 28136, "text": "adnanirshad158" }, { "code": null, "e": 28158, "s": 28151, "text": "circle" }, { "code": null, "e": 28168, "s": 28158, "text": "Geometric" }, { "code": null, "e": 28187, "s": 28168, "text": "School Programming" }, { "code": null, "e": 28197, "s": 28187, "text": "Geometric" }, { "code": null, "e": 28295, "s": 28197, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28344, "s": 28295, "text": "Program for distance between two points on earth" }, { "code": null, "e": 28397, "s": 28344, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 28431, "s": 28397, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28489, "s": 28431, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28538, "s": 28489, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 28556, "s": 28538, "text": "Python Dictionary" }, { "code": null, "e": 28572, "s": 28556, "text": "Arrays in C/C++" }, { "code": null, "e": 28591, "s": 28572, "text": "Inheritance in C++" }, { "code": null, "e": 28616, "s": 28591, "text": "Reverse a string in Java" } ]
Explain the equals() method of the Object, String and, StringBuffer classes.
To compare two objects the object class provides a method with name equals(), this method accepts an object and compares it with the current object. If the references of these two objects are equal, then it returns true else this method returns false. In the following example we have a class Employee with two variables name, age and a parameterized constructor. From the main method we are creating two objects by passing same values and, comparing both values using the equals() method. Since the equals() method of the Object class returns true only if the references of the two objects are equal, this program returns false. Live Demo import java.util.Scanner; class Employee { private String name; private int age; Employee(String name, int age){ this.name = name; this.age = age; } } public class EqualsExample { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("Enter your name "); String name = sc.next(); System.out.println("Enter your age "); int age = sc.nextInt(); Employee emp1 = new Employee(name, age); Employee emp2 = new Employee(name, age); //Comparing the two objects boolean bool = emp1.equals(emp2); System.out.println(bool); } } Enter your name Krishna Enter your age 20 false The equals() method of the String class is not same as the equals() method of the Object class. It is overridden, this method accepts a String value and compares it with the current object and returns true only if the character sequences in the both String objects are exactly same. In the following example we are accepting values from the user, creating two String objects and comparing them using the equals() method and displaying the results. Since the equals method returns true only if you enter same character sequences. You need to enter same values to print true. Live Demo import java.util.Scanner; public class StringEquals { public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("Enter a name "); String name1 = sc.next(); System.out.println("Enter another name "); String name2 = sc.next(); //Comparing the two objects boolean bool = name1.equals(name2); System.out.println(bool); } } Enter a name Krishna Enter another name Krishna true But, unlike the Sting class the StringBuffer does not override the equals() method. Its functionality is same as in the Object class. Therefore, to get true you need to compare references pointing to the same value using the equal method. Live Demo import java.util.Scanner; public class StringEquals implements Cloneable{ public static void main(String[] args) { Scanner sc =new Scanner(System.in); System.out.println("Enter a name "); StringBuffer name1 = new StringBuffer(sc.next()); StringBuffer name2 = name1; //Comparing the two objects boolean bool = name1.equals(name2); System.out.println(bool); } } Enter a name krishna true
[ { "code": null, "e": 1314, "s": 1062, "text": "To compare two objects the object class provides a method with name equals(), this method accepts an object and compares it with the current object. If the references of these two objects are equal, then it returns true else this method returns false." }, { "code": null, "e": 1426, "s": 1314, "text": "In the following example we have a class Employee with two variables name, age and a parameterized constructor." }, { "code": null, "e": 1552, "s": 1426, "text": "From the main method we are creating two objects by passing same values and, comparing both values using the equals() method." }, { "code": null, "e": 1692, "s": 1552, "text": "Since the equals() method of the Object class returns true only if the references of the two objects are equal, this program returns false." }, { "code": null, "e": 1703, "s": 1692, "text": " Live Demo" }, { "code": null, "e": 2352, "s": 1703, "text": "import java.util.Scanner;\nclass Employee {\n private String name;\n private int age;\n Employee(String name, int age){\n this.name = name;\n this.age = age;\n }\n}\npublic class EqualsExample {\n public static void main(String[] args) {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter your name \");\n String name = sc.next();\n System.out.println(\"Enter your age \");\n int age = sc.nextInt();\n Employee emp1 = new Employee(name, age);\n Employee emp2 = new Employee(name, age);\n //Comparing the two objects\n boolean bool = emp1.equals(emp2);\n System.out.println(bool);\n }\n}" }, { "code": null, "e": 2400, "s": 2352, "text": "Enter your name\nKrishna\nEnter your age\n20\nfalse" }, { "code": null, "e": 2683, "s": 2400, "text": "The equals() method of the String class is not same as the equals() method of the Object class. It is overridden, this method accepts a String value and compares it with the current object and returns true only if the character sequences in the both String objects are exactly same." }, { "code": null, "e": 2848, "s": 2683, "text": "In the following example we are accepting values from the user, creating two String objects and comparing them using the equals() method and displaying the results." }, { "code": null, "e": 2974, "s": 2848, "text": "Since the equals method returns true only if you enter same character sequences. You need to enter same values to print true." }, { "code": null, "e": 2985, "s": 2974, "text": " Live Demo" }, { "code": null, "e": 3396, "s": 2985, "text": "import java.util.Scanner;\npublic class StringEquals {\n public static void main(String[] args) {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter a name \");\n String name1 = sc.next();\n System.out.println(\"Enter another name \");\n String name2 = sc.next();\n //Comparing the two objects\n boolean bool = name1.equals(name2);\n System.out.println(bool);\n }\n}" }, { "code": null, "e": 3449, "s": 3396, "text": "Enter a name\nKrishna\nEnter another name\nKrishna\ntrue" }, { "code": null, "e": 3583, "s": 3449, "text": "But, unlike the Sting class the StringBuffer does not override the equals() method. Its functionality is same as in the Object class." }, { "code": null, "e": 3688, "s": 3583, "text": "Therefore, to get true you need to compare references pointing to the same value using the equal method." }, { "code": null, "e": 3699, "s": 3688, "text": " Live Demo" }, { "code": null, "e": 4107, "s": 3699, "text": "import java.util.Scanner;\npublic class StringEquals implements Cloneable{\n public static void main(String[] args) {\n Scanner sc =new Scanner(System.in);\n System.out.println(\"Enter a name \");\n StringBuffer name1 = new StringBuffer(sc.next());\n StringBuffer name2 = name1;\n //Comparing the two objects\n boolean bool = name1.equals(name2);\n System.out.println(bool);\n }\n}" }, { "code": null, "e": 4133, "s": 4107, "text": "Enter a name\nkrishna\ntrue" } ]
How to horizontally center a widget using a grid() in Tkinter?
As the name suggests, a grid is nothing but a set of rows and columns. Tkinter grid manager works similarly; it places the widget in a 2-dimensional plane to align the device through its position vertically and horizontally. Let us consider an example where we want to make the widget centered in the window while resizing it. The grid(row, column) property will help to make the label widget centered horizontally, and the sticky property will avoid resizing the widget in the window. #Import tkinter library from tkinter import * #Create an instance of Tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x250") #Make the window sticky for every case win.grid_rowconfigure(0, weight=1) win.grid_columnconfigure(0, weight=1) #Create a Label label=Label(win, text="This is a Centered Text",font=('Aerial 15 bold')) label.grid(row=2, column=0) label.grid_rowconfigure(1, weight=1) label.grid_columnconfigure(1, weight=1) win.mainloop() The above code will display a window containing a text label widget centered horizontally. When we resize the window, it will not affect the widget’s position.
[ { "code": null, "e": 1287, "s": 1062, "text": "As the name suggests, a grid is nothing but a set of rows and columns. Tkinter grid manager works similarly; it places the widget in a 2-dimensional plane to align the device through its position vertically and horizontally." }, { "code": null, "e": 1548, "s": 1287, "text": "Let us consider an example where we want to make the widget centered in the window while resizing it. The grid(row, column) property will help to make the label widget centered horizontally, and the sticky property will avoid resizing the widget in the window." }, { "code": null, "e": 2031, "s": 1548, "text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of Tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x250\")\n#Make the window sticky for every case\nwin.grid_rowconfigure(0, weight=1)\nwin.grid_columnconfigure(0, weight=1)\n#Create a Label\nlabel=Label(win, text=\"This is a Centered Text\",font=('Aerial 15 bold'))\nlabel.grid(row=2, column=0)\nlabel.grid_rowconfigure(1, weight=1)\nlabel.grid_columnconfigure(1, weight=1)\nwin.mainloop()" }, { "code": null, "e": 2191, "s": 2031, "text": "The above code will display a window containing a text label widget centered horizontally. When we resize the window, it will not affect the widget’s position." } ]
Back-off Algorithm for CSMA/CD - GeeksforGeeks
18 Oct, 2021 Prerequisite – Basics of CSMA/ CD, Collision Detection in CSMA/CDBack-off algorithm is a collision resolution mechanism which is used in random access MAC protocols (CSMA/CD). This algorithm is generally used in Ethernet to schedule re-transmissions after collisions. If a collision takes place between 2 stations, they may restart transmission as soon as they can after the collision. This will always lead to another collision and form an infinite loop of collisions leading to a deadlock. To prevent such scenario back-off algorithm is used. Let us consider an scenario of 2 stations A and B transmitting some data: After a collision, time is divided into discrete slots (Tslot) whose length is equal to 2t, where t is the maximum propagation delay in the network. The stations involved in the collision randomly pick an integer from the set K i.e {0, 1}. This set is called the contention window. If the sources collide again because they picked the same integer, the contention window size is doubled and it becomes {0, 1, 2, 3}. Now the sources involved in the second collision randomly pick an integer from the set {0, 1, 2, 3} and wait for that number of time slots before trying again. Before they try to transmit, they listen to the channel and transmit only if the channel is idle. This causes the source which picked the smallest integer in the contention window to succeed in transmitting its frame. So, Back-off algorithm defines a waiting time for the stations involved in collision, i.e. for how much time the station should wait to re-transmit. Waiting time = back–off time Let n = collision number or re-transmission serial number. Then, Waiting time = K * Tslot where K = [0, 2n – 1 ] Example – Case-1 :Suppose 2 stations A and B start transmitting data (Packet 1) at the same time then, collision occurs. So, the collision number n for both their data (Packet 1) = 1. Now, both the station randomly pick an integer from the set K i.e. {0, 1}. When both A and B choose K = 0–> Waiting time for A = 0 * Tslot = 0Waiting time for B = 0 * Tslot = 0Therefore, both stations will transmit at the same time and hence collision occurs. Therefore, both stations will transmit at the same time and hence collision occurs. When A chooses K = 0 and B chooses K = 1–> Waiting time for A = 0 * Tslot = 0Waiting time for B = 1 * Tslot = TslotTherefore, A transmits the packet and B waits for time Tslot for transmitting and hence A wins. Therefore, A transmits the packet and B waits for time Tslot for transmitting and hence A wins. When A chooses K = 1 and B chooses K = 0–> Waiting time for A = 1 * Tslot = TslotWaiting time for B = 0 * Tslot = 0Therefore, B transmits the packet and A waits for time Tslot for transmitting and hence B wins. Therefore, B transmits the packet and A waits for time Tslot for transmitting and hence B wins. When both A and B choose K = 1–> Waiting time for A = 1 * Tslot = TslotWaiting time for B = 1 * Tslot = TslotTherefore, both will wait for the same time Tslot and then transmit. Hence, collision occurs. Therefore, both will wait for the same time Tslot and then transmit. Hence, collision occurs. Probability that A wins = 1/4 Probability that B wins = 1/4 Probability of collision = 2/4 Case-2 :Assume that A wins in Case 1 and transmitted its data(Packet 1). Now, as soon as B transmits its packet 1, A transmits its packet 2. Hence, collision occurs. Now collision no. n becomes 1 for packet 2 of A and becomes 2 for packet 1 of B.For packet 2 of A, K = {0, 1}For packet 1 of B, K = {0, 1, 2, 3} Probability that A wins = 5/8 Probability that B wins = 1/8 Probability of collision = 2/8 So, the probability of collision decreases as compared to Case 1. Advantage – Collision probability decreases exponentially. Disadvantages – Capture effect: Station who wins ones keeps on winning. Works only for 2 stations or hosts. GATE Practice Question – GATE-CS-2004 | Question 90GATE-CS-2016 (Set 2) | Question 34GATE-IT-2004 | Question 85 GATE-CS-2004 | Question 90 GATE-CS-2016 (Set 2) | Question 34 GATE-IT-2004 | Question 85 Pushpender007 Computer Networks GATE CS Technical Scripter Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Caesar Cipher in Cryptography Socket Programming in Python UDP Server-Client implementation in C Differences between IPv4 and IPv6 Socket Programming in Java ACID Properties in DBMS Page Replacement Algorithms in Operating Systems Types of Operating Systems Normal Forms in DBMS Semaphores in Process Synchronization
[ { "code": null, "e": 36592, "s": 36564, "text": "\n18 Oct, 2021" }, { "code": null, "e": 36860, "s": 36592, "text": "Prerequisite – Basics of CSMA/ CD, Collision Detection in CSMA/CDBack-off algorithm is a collision resolution mechanism which is used in random access MAC protocols (CSMA/CD). This algorithm is generally used in Ethernet to schedule re-transmissions after collisions." }, { "code": null, "e": 37137, "s": 36860, "text": "If a collision takes place between 2 stations, they may restart transmission as soon as they can after the collision. This will always lead to another collision and form an infinite loop of collisions leading to a deadlock. To prevent such scenario back-off algorithm is used." }, { "code": null, "e": 37211, "s": 37137, "text": "Let us consider an scenario of 2 stations A and B transmitting some data:" }, { "code": null, "e": 37360, "s": 37211, "text": "After a collision, time is divided into discrete slots (Tslot) whose length is equal to 2t, where t is the maximum propagation delay in the network." }, { "code": null, "e": 38005, "s": 37360, "text": "The stations involved in the collision randomly pick an integer from the set K i.e {0, 1}. This set is called the contention window. If the sources collide again because they picked the same integer, the contention window size is doubled and it becomes {0, 1, 2, 3}. Now the sources involved in the second collision randomly pick an integer from the set {0, 1, 2, 3} and wait for that number of time slots before trying again. Before they try to transmit, they listen to the channel and transmit only if the channel is idle. This causes the source which picked the smallest integer in the contention window to succeed in transmitting its frame." }, { "code": null, "e": 38154, "s": 38005, "text": "So, Back-off algorithm defines a waiting time for the stations involved in collision, i.e. for how much time the station should wait to re-transmit." }, { "code": null, "e": 38301, "s": 38154, "text": "Waiting time = back–off time\nLet n = collision number or re-transmission serial number. \nThen, \nWaiting time = K * Tslot\nwhere K = [0, 2n – 1 ] \n" }, { "code": null, "e": 38311, "s": 38301, "text": "Example –" }, { "code": null, "e": 38560, "s": 38311, "text": "Case-1 :Suppose 2 stations A and B start transmitting data (Packet 1) at the same time then, collision occurs. So, the collision number n for both their data (Packet 1) = 1. Now, both the station randomly pick an integer from the set K i.e. {0, 1}." }, { "code": null, "e": 38745, "s": 38560, "text": "When both A and B choose K = 0–> Waiting time for A = 0 * Tslot = 0Waiting time for B = 0 * Tslot = 0Therefore, both stations will transmit at the same time and hence collision occurs." }, { "code": null, "e": 38829, "s": 38745, "text": "Therefore, both stations will transmit at the same time and hence collision occurs." }, { "code": null, "e": 39040, "s": 38829, "text": "When A chooses K = 0 and B chooses K = 1–> Waiting time for A = 0 * Tslot = 0Waiting time for B = 1 * Tslot = TslotTherefore, A transmits the packet and B waits for time Tslot for transmitting and hence A wins." }, { "code": null, "e": 39136, "s": 39040, "text": "Therefore, A transmits the packet and B waits for time Tslot for transmitting and hence A wins." }, { "code": null, "e": 39347, "s": 39136, "text": "When A chooses K = 1 and B chooses K = 0–> Waiting time for A = 1 * Tslot = TslotWaiting time for B = 0 * Tslot = 0Therefore, B transmits the packet and A waits for time Tslot for transmitting and hence B wins." }, { "code": null, "e": 39443, "s": 39347, "text": "Therefore, B transmits the packet and A waits for time Tslot for transmitting and hence B wins." }, { "code": null, "e": 39646, "s": 39443, "text": "When both A and B choose K = 1–> Waiting time for A = 1 * Tslot = TslotWaiting time for B = 1 * Tslot = TslotTherefore, both will wait for the same time Tslot and then transmit. Hence, collision occurs." }, { "code": null, "e": 39740, "s": 39646, "text": "Therefore, both will wait for the same time Tslot and then transmit. Hence, collision occurs." }, { "code": null, "e": 39833, "s": 39740, "text": "Probability that A wins = 1/4\nProbability that B wins = 1/4\nProbability of collision = 2/4\n" }, { "code": null, "e": 40144, "s": 39833, "text": "Case-2 :Assume that A wins in Case 1 and transmitted its data(Packet 1). Now, as soon as B transmits its packet 1, A transmits its packet 2. Hence, collision occurs. Now collision no. n becomes 1 for packet 2 of A and becomes 2 for packet 1 of B.For packet 2 of A, K = {0, 1}For packet 1 of B, K = {0, 1, 2, 3}" }, { "code": null, "e": 40237, "s": 40144, "text": "Probability that A wins = 5/8\nProbability that B wins = 1/8\nProbability of collision = 2/8\n" }, { "code": null, "e": 40303, "s": 40237, "text": "So, the probability of collision decreases as compared to Case 1." }, { "code": null, "e": 40315, "s": 40303, "text": "Advantage –" }, { "code": null, "e": 40362, "s": 40315, "text": "Collision probability decreases exponentially." }, { "code": null, "e": 40378, "s": 40362, "text": "Disadvantages –" }, { "code": null, "e": 40434, "s": 40378, "text": "Capture effect: Station who wins ones keeps on winning." }, { "code": null, "e": 40470, "s": 40434, "text": "Works only for 2 stations or hosts." }, { "code": null, "e": 40495, "s": 40470, "text": "GATE Practice Question –" }, { "code": null, "e": 40582, "s": 40495, "text": "GATE-CS-2004 | Question 90GATE-CS-2016 (Set 2) | Question 34GATE-IT-2004 | Question 85" }, { "code": null, "e": 40609, "s": 40582, "text": "GATE-CS-2004 | Question 90" }, { "code": null, "e": 40644, "s": 40609, "text": "GATE-CS-2016 (Set 2) | Question 34" }, { "code": null, "e": 40671, "s": 40644, "text": "GATE-IT-2004 | Question 85" }, { "code": null, "e": 40685, "s": 40671, "text": "Pushpender007" }, { "code": null, "e": 40703, "s": 40685, "text": "Computer Networks" }, { "code": null, "e": 40711, "s": 40703, "text": "GATE CS" }, { "code": null, "e": 40730, "s": 40711, "text": "Technical Scripter" }, { "code": null, "e": 40748, "s": 40730, "text": "Computer Networks" }, { "code": null, "e": 40846, "s": 40748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40876, "s": 40846, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 40905, "s": 40876, "text": "Socket Programming in Python" }, { "code": null, "e": 40943, "s": 40905, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 40977, "s": 40943, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 41004, "s": 40977, "text": "Socket Programming in Java" }, { "code": null, "e": 41028, "s": 41004, "text": "ACID Properties in DBMS" }, { "code": null, "e": 41077, "s": 41028, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 41104, "s": 41077, "text": "Types of Operating Systems" }, { "code": null, "e": 41125, "s": 41104, "text": "Normal Forms in DBMS" } ]
How to set up your python development environment on AWS?
You need to have Python, pip, virtualenv, awswebcli and a SSH client installed to set up your Python Development Environment on AWS. You can follow instructions at http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html to install these. Once you have all those installed, you need to set up a virtual environment so that your global packages do not get polluted. Use the following command to set up a virtual environment: $ virtualenv -p python2.7 /tmp/hello-world Running virtualenv with interpreter /usr/bin/python2.7 New python executable in /tmp/hello-world/bin/python2.7 Also creating executable in /tmp/hello-world/bin/python Installing setuptools, pip...done. Once your virtual environment is ready, start it by running the activate script located in the environment's bin directory. For example, to start the hello-world environment created in the previous step, you would type: $ . /tmp/hello-world/bin/activate Once created, you can restart the virtual environment at any time by running its activate script again. To configure a Python application for deployment, from within your virtualenv, return to the top of your project's directory tree and create a requirements.txt file that contains your app's requirements(third party modules you are importing) with their version numbers(or without if you need latest one). For example, Flask==0.8 Jinja2==2.6 Werkzeug==0.8.3 certifi==0.0.8 chardet==1.0.1 : ... Alternatively you can use pip to get all installed packages from your machine to the requirements.txt file using: $ pip freeze >requirements.txt This allows AWS to replicate your application's Python environment using the same packages and same versions that you used to develop and test your application. Now configure AWS EB CLI repository with the 'eb init' command. $ eb init -p python2.7 hello-world Application hello-world has been created. This command creates a new application named hello-world and configures your local repository to create environments with the latest Python 2.7 platform configuration. Run eb init again to configure a default keypair so that you can connect to the EC2 instance running your application with SSH $ eb init Do you want to set up SSH for your instances? (y/n): y Select a keypair. 1) my-keypair 2) [ Create new KeyPair ] Select a key pair if you have one already, or follow the prompts to create a new one. If you don't see the prompt or need to change your settings later, run eb init -i. Create an environment and deploy you application to it with eb create: $ eb create hello-env This command creates a load balanced Elastic Beanstalk environment named hello-env. If you face any issues, you can check more detailed documentation here: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb
[ { "code": null, "e": 1319, "s": 1062, "text": "You need to have Python, pip, virtualenv, awswebcli and a SSH client installed to set up your Python Development Environment on AWS. You can follow instructions at http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html to install these." }, { "code": null, "e": 1504, "s": 1319, "text": "Once you have all those installed, you need to set up a virtual environment so that your global packages do not get polluted. Use the following command to set up a virtual environment:" }, { "code": null, "e": 1749, "s": 1504, "text": "$ virtualenv -p python2.7 /tmp/hello-world\nRunning virtualenv with interpreter /usr/bin/python2.7\nNew python executable in /tmp/hello-world/bin/python2.7\nAlso creating executable in /tmp/hello-world/bin/python\nInstalling setuptools, pip...done." }, { "code": null, "e": 1969, "s": 1749, "text": "Once your virtual environment is ready, start it by running the activate script located in the environment's bin directory. For example, to start the hello-world environment created in the previous step, you would type:" }, { "code": null, "e": 2003, "s": 1969, "text": "$ . /tmp/hello-world/bin/activate" }, { "code": null, "e": 2107, "s": 2003, "text": "Once created, you can restart the virtual environment at any time by running its activate script again." }, { "code": null, "e": 2425, "s": 2107, "text": "To configure a Python application for deployment, from within your virtualenv, return to the top of your project's directory tree and create a requirements.txt file that contains your app's requirements(third party modules you are importing) with their version numbers(or without if you need latest one). For example," }, { "code": null, "e": 2500, "s": 2425, "text": "Flask==0.8\nJinja2==2.6\nWerkzeug==0.8.3\ncertifi==0.0.8\nchardet==1.0.1 :\n..." }, { "code": null, "e": 2614, "s": 2500, "text": "Alternatively you can use pip to get all installed packages from your machine to the requirements.txt file using:" }, { "code": null, "e": 2645, "s": 2614, "text": "$ pip freeze >requirements.txt" }, { "code": null, "e": 2806, "s": 2645, "text": "This allows AWS to replicate your application's Python environment using the same packages and same versions that you used to develop and test your application." }, { "code": null, "e": 2870, "s": 2806, "text": "Now configure AWS EB CLI repository with the 'eb init' command." }, { "code": null, "e": 2905, "s": 2870, "text": "$ eb init -p python2.7 hello-world" }, { "code": null, "e": 2947, "s": 2905, "text": "Application hello-world has been created." }, { "code": null, "e": 3242, "s": 2947, "text": "This command creates a new application named hello-world and configures your local repository to create environments with the latest Python 2.7 platform configuration. Run eb init again to configure a default keypair so that you can connect to the EC2 instance running your application with SSH" }, { "code": null, "e": 3365, "s": 3242, "text": "$ eb init\nDo you want to set up SSH for your instances?\n(y/n): y\nSelect a keypair.\n1) my-keypair\n2) [ Create new KeyPair ]" }, { "code": null, "e": 3605, "s": 3365, "text": "Select a key pair if you have one already, or follow the prompts to create a new one. If you don't see the prompt or need to change your settings later, run eb init -i. Create an environment and deploy you application to it with eb create:" }, { "code": null, "e": 3627, "s": 3605, "text": "$ eb create hello-env" }, { "code": null, "e": 3711, "s": 3627, "text": "This command creates a load balanced Elastic Beanstalk environment named hello-env." }, { "code": null, "e": 3901, "s": 3711, "text": "If you face any issues, you can check more detailed documentation here: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb" } ]
How to fix "Exception in thread main" in java?
An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. import java.util.Scanner; public class ExceptionExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter first number: "); int a = sc.nextInt(); System.out.println("Enter second number: "); int b = sc.nextInt(); int c = a/b; System.out.println("The result is: "+c); } } Enter first number: 100 Enter second number: 0 Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionExample In Java There are two types of exceptions Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions. Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. The display pattern of the runtime exception/unchecked exception is "Exception in thread main" i.e. whenever a runtime exception occurs the message starts with this line. In following Java program, we have an array with size 5 and we are trying to access the 6th element, this generates ArrayIndexOutOfBoundsException. public class ExceptionExample { public static void main(String[] args) { //Creating an integer array with size 5 int inpuArray[] = new int[5]; //Populating the array inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //Accessing index greater than the size of the array System.out.println( inpuArray[6]); } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at MyPackage.ExceptionExample.main(ExceptionExample.java:14) In the following example we are trying to create an array by using a negative number for the size value, this generates a NegativeArraySizeException. public class Test { public static void main(String[] args) { int[] intArray = new int[-5]; } } On executing, this program generates a run time exception as shown below. Exception in thread "main" java.lang.NegativeArraySizeException at myPackage.Test.main(Test.java:6) You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code. For example, if you need to fix the ArrayIndexOutOfBoundsException in the first program listed above you need to remove/change the line that accesses index positon of the array beyond its size. public class ExceptionExample { public static void main(String[] args) { //Creating an integer array with size 5 int inpuArray[] = new int[5]; //Populating the array inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //Accessing index greater than the size of the array System.out.println( inpuArray[3]); } } 26
[ { "code": null, "e": 1290, "s": 1062, "text": "An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed." }, { "code": null, "e": 1665, "s": 1290, "text": "import java.util.Scanner;\npublic class ExceptionExample {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter first number: \");\n int a = sc.nextInt();\n System.out.println(\"Enter second number: \");\n int b = sc.nextInt();\n int c = a/b;\n System.out.println(\"The result is: \"+c);\n }\n}" }, { "code": null, "e": 1800, "s": 1665, "text": "Enter first number:\n100\nEnter second number:\n0\nException in thread \"main\" java.lang.ArithmeticException: / by zero\nat ExceptionExample" }, { "code": null, "e": 1842, "s": 1800, "text": "In Java There are two types of exceptions" }, { "code": null, "e": 2120, "s": 1842, "text": "Checked Exception − A checked exception is an exception that occurs at the time of compilation, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions." }, { "code": null, "e": 2399, "s": 2120, "text": "Unchecked Exception − An unchecked exception is the one which occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation." }, { "code": null, "e": 2570, "s": 2399, "text": "The display pattern of the runtime exception/unchecked exception is \"Exception in thread main\" i.e. whenever a runtime exception occurs the message starts with this line." }, { "code": null, "e": 2718, "s": 2570, "text": "In following Java program, we have an array with size 5 and we are trying to access the 6th element, this generates ArrayIndexOutOfBoundsException." }, { "code": null, "e": 3137, "s": 2718, "text": "public class ExceptionExample {\n public static void main(String[] args) {\n //Creating an integer array with size 5\n int inpuArray[] = new int[5];\n //Populating the array\n inpuArray[0] = 41;\n inpuArray[1] = 98;\n inpuArray[2] = 43;\n inpuArray[3] = 26;\n inpuArray[4] = 79;\n //Accessing index greater than the size of the array\n System.out.println( inpuArray[6]);\n }\n}" }, { "code": null, "e": 3269, "s": 3137, "text": "Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 6\nat MyPackage.ExceptionExample.main(ExceptionExample.java:14)" }, { "code": null, "e": 3419, "s": 3269, "text": "In the following example we are trying to create an array by using a negative number for the size value, this generates a NegativeArraySizeException." }, { "code": null, "e": 3526, "s": 3419, "text": "public class Test {\n public static void main(String[] args) {\n int[] intArray = new int[-5];\n }\n}" }, { "code": null, "e": 3600, "s": 3526, "text": "On executing, this program generates a run time exception as shown below." }, { "code": null, "e": 3700, "s": 3600, "text": "Exception in thread \"main\" java.lang.NegativeArraySizeException\nat myPackage.Test.main(Test.java:6)" }, { "code": null, "e": 3889, "s": 3700, "text": "You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code." }, { "code": null, "e": 4083, "s": 3889, "text": "For example, if you need to fix the ArrayIndexOutOfBoundsException in the first program listed above you need to remove/change the line that accesses index positon of the array beyond its size." }, { "code": null, "e": 4502, "s": 4083, "text": "public class ExceptionExample {\n public static void main(String[] args) {\n //Creating an integer array with size 5\n int inpuArray[] = new int[5];\n //Populating the array\n inpuArray[0] = 41;\n inpuArray[1] = 98;\n inpuArray[2] = 43;\n inpuArray[3] = 26;\n inpuArray[4] = 79;\n //Accessing index greater than the size of the array\n System.out.println( inpuArray[3]);\n }\n}" }, { "code": null, "e": 4505, "s": 4502, "text": "26" } ]