title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
How to solve too many re-renders error in ReactJS?
|
16 Feb, 2021
“Too many re-renderers” is a React error that happens after you have reached an infinite render loop, typically caused by code that in a useEffect hook or the main body of the component itself unconditionally calls state setters.
When does React decide to re-render a component?
The first rendering will be triggered after the componentWillMount lifecycle.
After the React ComponentWillUpdate lifecycle, it is then activated.
After mounting a React component, it will listen to any React props or state that has changed.
It will, by default, re-render the entire React component and its child components when it detects something has changed.
These are some tips to avoid too many re-renders errors in React:
Don’t change the state in the main body of the component.
Use the useEffect hook very cautiously. The second parameter of useEffect is an array of states based on the useEffect will call. So don’t update those states in useEffect otherwise, it will rerender the component again and again.
Use React shouldComponentUpdate: React shouldComponentUpdate is a method for optimizing performance, which tells React to stop re-rendering a component, even though it might have changed the state or prop values. Using this approach only if a part stays unchanged or pure while it is used. You are expected to return a Boolean value with the React shouldComponentUpdate method. Return true if it needs to re-render or false to avoid being re-render.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Filename- App.js: Below is an example of how to use React shouldComponentUpdate. I’ve built 2 components of React in this code. One is a part of the greeting, and the other is the app component. During the render lifecycle, each React component is a console logging a message.
Javascript
import React from "react";class Greeting extends React.Component { render() { console.log("Greeting - Render lifecycle"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { render() { console.log("App - Render lifecycle"); return <Greeting />; }} export default App;
Output:
Filename- App.js: Next, in the componentDidMount React lifecycle, I will add the React state, and update the state value.
Javascript
import React from "react"; class Greeting extends React.Component { render() { console.log("Greeting - Render lifecycle"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { state = { greeted: false, }; componentDidMount() { this.setState({ greeted: true }); } render() { console.log("App - Render lifecycle"); return <Greeting />; }} export default App;
Output: You can see in the output that the render lifecycle was triggered more than once on both the app and greeting components. This is because the React app component was re-rendered, after updating the state values, and its child components were also re-rendered. We should assume that the greeting portion is unchanged and that it won’t ever change.
Filename- App.js: Use the shouldComponentUpdate hook when it is clear that at all times a component we are creating will be static.
Javascript
import React from "react";class Greeting extends React.Component { shouldComponentUpdate() { console.log("Greeting - shouldComponentUpdate lifecycle"); return false; } render() { console.log("Greeting - Render lifecycle"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { state = { greeted: false, }; componentDidMount() { this.setState({ greeted: true }); } render() { console.log("App - Render lifecycle"); return <Greeting />; }} export default App;
Output: You can see that the app and greeting component went through a round of the rendering lifecycle. After the state values were changed, the App component went through the rendering lifecycle again. But the Greeting component did not console log the Lifecycle Render message.
Picked
React-Questions
JavaScript
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "“Too many re-renderers” is a React error that happens after you have reached an infinite render loop, typically caused by code that in a useEffect hook or the main body of the component itself unconditionally calls state setters. "
},
{
"code": null,
"e": 308,
"s": 259,
"text": "When does React decide to re-render a component?"
},
{
"code": null,
"e": 386,
"s": 308,
"text": "The first rendering will be triggered after the componentWillMount lifecycle."
},
{
"code": null,
"e": 455,
"s": 386,
"text": "After the React ComponentWillUpdate lifecycle, it is then activated."
},
{
"code": null,
"e": 550,
"s": 455,
"text": "After mounting a React component, it will listen to any React props or state that has changed."
},
{
"code": null,
"e": 672,
"s": 550,
"text": "It will, by default, re-render the entire React component and its child components when it detects something has changed."
},
{
"code": null,
"e": 738,
"s": 672,
"text": "These are some tips to avoid too many re-renders errors in React:"
},
{
"code": null,
"e": 796,
"s": 738,
"text": "Don’t change the state in the main body of the component."
},
{
"code": null,
"e": 1027,
"s": 796,
"text": "Use the useEffect hook very cautiously. The second parameter of useEffect is an array of states based on the useEffect will call. So don’t update those states in useEffect otherwise, it will rerender the component again and again."
},
{
"code": null,
"e": 1477,
"s": 1027,
"text": "Use React shouldComponentUpdate: React shouldComponentUpdate is a method for optimizing performance, which tells React to stop re-rendering a component, even though it might have changed the state or prop values. Using this approach only if a part stays unchanged or pure while it is used. You are expected to return a Boolean value with the React shouldComponentUpdate method. Return true if it needs to re-render or false to avoid being re-render."
},
{
"code": null,
"e": 1505,
"s": 1477,
"text": "Creating React Application:"
},
{
"code": null,
"e": 1569,
"s": 1505,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1601,
"s": 1569,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1701,
"s": 1601,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1715,
"s": 1701,
"text": "cd foldername"
},
{
"code": null,
"e": 1767,
"s": 1715,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2044,
"s": 1767,
"text": "Filename- App.js: Below is an example of how to use React shouldComponentUpdate. I’ve built 2 components of React in this code. One is a part of the greeting, and the other is the app component. During the render lifecycle, each React component is a console logging a message."
},
{
"code": null,
"e": 2055,
"s": 2044,
"text": "Javascript"
},
{
"code": "import React from \"react\";class Greeting extends React.Component { render() { console.log(\"Greeting - Render lifecycle\"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { render() { console.log(\"App - Render lifecycle\"); return <Greeting />; }} export default App;",
"e": 2363,
"s": 2055,
"text": null
},
{
"code": null,
"e": 2371,
"s": 2363,
"text": "Output:"
},
{
"code": null,
"e": 2493,
"s": 2371,
"text": "Filename- App.js: Next, in the componentDidMount React lifecycle, I will add the React state, and update the state value."
},
{
"code": null,
"e": 2504,
"s": 2493,
"text": "Javascript"
},
{
"code": "import React from \"react\"; class Greeting extends React.Component { render() { console.log(\"Greeting - Render lifecycle\"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { state = { greeted: false, }; componentDidMount() { this.setState({ greeted: true }); } render() { console.log(\"App - Render lifecycle\"); return <Greeting />; }} export default App;",
"e": 2915,
"s": 2504,
"text": null
},
{
"code": null,
"e": 3270,
"s": 2915,
"text": "Output: You can see in the output that the render lifecycle was triggered more than once on both the app and greeting components. This is because the React app component was re-rendered, after updating the state values, and its child components were also re-rendered. We should assume that the greeting portion is unchanged and that it won’t ever change."
},
{
"code": null,
"e": 3402,
"s": 3270,
"text": "Filename- App.js: Use the shouldComponentUpdate hook when it is clear that at all times a component we are creating will be static."
},
{
"code": null,
"e": 3413,
"s": 3402,
"text": "Javascript"
},
{
"code": "import React from \"react\";class Greeting extends React.Component { shouldComponentUpdate() { console.log(\"Greeting - shouldComponentUpdate lifecycle\"); return false; } render() { console.log(\"Greeting - Render lifecycle\"); return <h1>Geeksforgeeks</h1>; }} class App extends React.Component { state = { greeted: false, }; componentDidMount() { this.setState({ greeted: true }); } render() { console.log(\"App - Render lifecycle\"); return <Greeting />; }} export default App;",
"e": 3935,
"s": 3413,
"text": null
},
{
"code": null,
"e": 4216,
"s": 3935,
"text": "Output: You can see that the app and greeting component went through a round of the rendering lifecycle. After the state values were changed, the App component went through the rendering lifecycle again. But the Greeting component did not console log the Lifecycle Render message."
},
{
"code": null,
"e": 4223,
"s": 4216,
"text": "Picked"
},
{
"code": null,
"e": 4239,
"s": 4223,
"text": "React-Questions"
},
{
"code": null,
"e": 4250,
"s": 4239,
"text": "JavaScript"
},
{
"code": null,
"e": 4258,
"s": 4250,
"text": "ReactJS"
}
] |
Java long compareTo() with examples
|
05 Dec, 2018
The java.lang.Long.compareTo() is a built-in method in java that compares two Long objects numerically. This method returns 0 if this object is equal to the argument object, it returns less than 0 if this object is numerically less than the argument object and a value greater than 0 if this object is numerically greater than the argument object.
Syntax:
public int compareTo(Object obj)
Parameter:
obj - The object which is to be compared to.
Returns: The function returns three values:
equal to 0: Object is equal to the argument object
less than 0: Object is less than the argument object
greater than 0: Object is greater than the argument object
Program 1: The program below demonstrates the working of function.
// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when two objects are different Long obj1 = new Long(124); Long obj2 = new Long(167); int compareValue = obj1.compareTo(obj2); if (compareValue == 0) System.out.println("object1 and object2 are equal"); else if (compareValue < 0) System.out.println("object1 is less than object2"); else System.out.println("object1 is greater than object2"); }}
Output:
object1 is less than object2
Program 2: The program below demonstrates the working of function when no argument is passed
// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when no argument is passed Long obj1 = new Long(124); Long obj2 = new Long(167); int compareValue = obj1.compareTo(); if (compareValue == 0) System.out.println("object1 and object2 are equal"); else if (compareValue < 0) System.out.println("object1 is less than object2"); else System.out.println("object1 is greater than object2"); }}
Output:
prog.java:14: error: method compareTo in class Long cannot be applied to given types;
int compareValue = obj1.compareTo();
^
required: Long
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Program 3: The program below demonstrates the working of function when anything other than object is passed in an argument
// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when anything other than object // argument is passed Long obj1 = new Long(124); int compareValue = obj1.compareTo("gfg"); if (compareValue == 0) System.out.println("object1 and object2 are equal"); else if (compareValue < 0) System.out.println("object1 is less than object2"); else System.out.println("object1 is greater than object2"); }}
Output:
prog.java:14: error: incompatible types: String cannot be converted to Long
int compareValue = obj1.compareTo("gfg");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
Java-Functions
Java-lang package
java-Long
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Dec, 2018"
},
{
"code": null,
"e": 376,
"s": 28,
"text": "The java.lang.Long.compareTo() is a built-in method in java that compares two Long objects numerically. This method returns 0 if this object is equal to the argument object, it returns less than 0 if this object is numerically less than the argument object and a value greater than 0 if this object is numerically greater than the argument object."
},
{
"code": null,
"e": 384,
"s": 376,
"text": "Syntax:"
},
{
"code": null,
"e": 476,
"s": 384,
"text": "public int compareTo(Object obj)\n\nParameter: \nobj - The object which is to be compared to.\n"
},
{
"code": null,
"e": 520,
"s": 476,
"text": "Returns: The function returns three values:"
},
{
"code": null,
"e": 571,
"s": 520,
"text": "equal to 0: Object is equal to the argument object"
},
{
"code": null,
"e": 624,
"s": 571,
"text": "less than 0: Object is less than the argument object"
},
{
"code": null,
"e": 683,
"s": 624,
"text": "greater than 0: Object is greater than the argument object"
},
{
"code": null,
"e": 750,
"s": 683,
"text": "Program 1: The program below demonstrates the working of function."
},
{
"code": "// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when two objects are different Long obj1 = new Long(124); Long obj2 = new Long(167); int compareValue = obj1.compareTo(obj2); if (compareValue == 0) System.out.println(\"object1 and object2 are equal\"); else if (compareValue < 0) System.out.println(\"object1 is less than object2\"); else System.out.println(\"object1 is greater than object2\"); }}",
"e": 1359,
"s": 750,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1359,
"text": "Output:"
},
{
"code": null,
"e": 1397,
"s": 1367,
"text": "object1 is less than object2\n"
},
{
"code": null,
"e": 1490,
"s": 1397,
"text": "Program 2: The program below demonstrates the working of function when no argument is passed"
},
{
"code": "// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when no argument is passed Long obj1 = new Long(124); Long obj2 = new Long(167); int compareValue = obj1.compareTo(); if (compareValue == 0) System.out.println(\"object1 and object2 are equal\"); else if (compareValue < 0) System.out.println(\"object1 is less than object2\"); else System.out.println(\"object1 is greater than object2\"); }}",
"e": 2091,
"s": 1490,
"text": null
},
{
"code": null,
"e": 2099,
"s": 2091,
"text": "Output:"
},
{
"code": null,
"e": 2368,
"s": 2099,
"text": "prog.java:14: error: method compareTo in class Long cannot be applied to given types;\n int compareValue = obj1.compareTo(); \n ^\n required: Long\n found: no arguments\n reason: actual and formal argument lists differ in length\n1 error\n"
},
{
"code": null,
"e": 2491,
"s": 2368,
"text": "Program 3: The program below demonstrates the working of function when anything other than object is passed in an argument"
},
{
"code": "// Java program to demonstrate// of java.lang.Long.compareTo() methodimport java.lang.Math; class Gfg1 { // driver code public static void main(String args[]) { // when anything other than object // argument is passed Long obj1 = new Long(124); int compareValue = obj1.compareTo(\"gfg\"); if (compareValue == 0) System.out.println(\"object1 and object2 are equal\"); else if (compareValue < 0) System.out.println(\"object1 is less than object2\"); else System.out.println(\"object1 is greater than object2\"); }}",
"e": 3099,
"s": 2491,
"text": null
},
{
"code": null,
"e": 3107,
"s": 3099,
"text": "Output:"
},
{
"code": null,
"e": 3375,
"s": 3107,
"text": "prog.java:14: error: incompatible types: String cannot be converted to Long\n int compareValue = obj1.compareTo(\"gfg\"); \n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n1 error\n"
},
{
"code": null,
"e": 3390,
"s": 3375,
"text": "Java-Functions"
},
{
"code": null,
"e": 3408,
"s": 3390,
"text": "Java-lang package"
},
{
"code": null,
"e": 3418,
"s": 3408,
"text": "java-Long"
},
{
"code": null,
"e": 3428,
"s": 3418,
"text": "java-math"
},
{
"code": null,
"e": 3433,
"s": 3428,
"text": "Java"
},
{
"code": null,
"e": 3438,
"s": 3433,
"text": "Java"
},
{
"code": null,
"e": 3536,
"s": 3438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3555,
"s": 3536,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3573,
"s": 3555,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3588,
"s": 3573,
"text": "Stream In Java"
},
{
"code": null,
"e": 3608,
"s": 3588,
"text": "Collections in Java"
},
{
"code": null,
"e": 3640,
"s": 3608,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3664,
"s": 3640,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3676,
"s": 3664,
"text": "Set in Java"
},
{
"code": null,
"e": 3696,
"s": 3676,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3728,
"s": 3696,
"text": "Initialize an ArrayList in Java"
}
] |
Count of numbers from range [L, R] whose sum of digits is Y using Dynamic Programming
|
20 Apr, 2021
Pre-requisites: Recursion, Dynamic Programming, Digit DP
Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples:
Input: L = 0, R = 11, Y = 2 Output: 2 2 -> 2 11 -> 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3
Constraints:
0 <= L <= R <= 10^18
0 <= Y <= 162 (Which is the maximum possible sum a 18 digit number can have)
Approach: Firstly generalizing the question, [L, R] can be written as [0, R] – [0, L-1], i.e. first finding all the numbers in the range[0, R] whose digit sum = Y, and then for the range[0, L-1], then finally subtracting each values to get out desired result. So for the case of digit let’s store the digits of number L and R in 2 separate vectors so that accessing its digit would be easier. Then we need a function that will carry (current_index, flag, sum). This function is the main part of our logic. Initializing current_index = 0, flag = 0, sum = 0.
Let’s say R = 462, this number has 3 indexes i.e. 0, 1, 2. Now check in how many ways can you fill the 0th index. On observation we can say we can fill 0th index as 0, 1, 2, 3 and 4. If we exceed 4, then we would form a number greater than 462.
Now, if you have inserted 0 in 0th index then what can be the possibility for 1st index ? Answer – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Since you have a number 0 in the 0th index you can fill any number from 0-9 in the 1st index. Okay as you can fill any number in next index, you will turn flag = 1. flag = 1 tell us that we have the advantage to fill anything from 0-9. Similarly thinking up for the other indexes.
Now if we see the base condition
if(current_index == n) {if(sum == Y) return 1;else return 0;}
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>using namespace std; // function to convert digit to vectorvector<int> digitToVec(int n) { vector<int> a; while (n) { a.push_back(n % 10); n = n / 10; } reverse(a.begin(), a.end()); return a;} int Y; // setting Y as globalint dp[19][2][18 * 9 + 1]; // 3D dpint func(int ind, int flag, int sum, vector<int> a) { if (ind == a.size()) { if (sum == Y) return 1; else return 0; } if (dp[ind][flag][sum] != -1) return dp[ind][flag][sum]; // if flag = 0, I know I can only fill from 0 to a[ind] // if flag = 1, I have the advantage to fill from 0 to 9 int limit = 9; if (flag == 0) limit = a[ind]; int cnt = 0; for (int num = 0; num <= limit; num++) { // if flag = 0, which means no advantage // and I am still filling the same number as a[ind] means giving him no advantage // hence the next recursion call flag still stays as 0 if (flag == 0 && num == a[ind]) { cnt += func(ind + 1, 0, sum + num, a); } else { cnt += func(ind + 1, 1, sum + num, a); } } return dp[ind][flag][sum] = cnt;} // intermediate function helping to initialize all values of func()int ans(int n) { vector<int> a = digitToVec(n); memset(dp, -1, sizeof dp); // initializing dp as -1 return func(0, 0, 0, a);} // Driver codeint main() { int l, r; cin >> l >> r >> Y; cout << ans(r) - ans(l - 1); return 0;}
2
Now talking of the worst case Time Complexity: O(19 * 2 * (18 * 9) * 10)
prerna saini
29AjayKumar
mohit kumar 29
Code_Mech
ashishraut0910
Number Divisibility
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Product of Array except itself
Find Union and Intersection of two unsorted arrays
Median of two sorted arrays of same size
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Apr, 2021"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Pre-requisites: Recursion, Dynamic Programming, Digit DP"
},
{
"code": null,
"e": 262,
"s": 111,
"text": "Given an integer Y and a range [L, R], the task is to find the count of all numbers from the given range whose sum of digits is equal to Y.Examples: "
},
{
"code": null,
"e": 366,
"s": 262,
"text": "Input: L = 0, R = 11, Y = 2 Output: 2 2 -> 2 11 -> 1 + 1 = 2Input: L = 500, R = 1000, Y = 6 Output: 3 "
},
{
"code": null,
"e": 382,
"s": 368,
"text": "Constraints: "
},
{
"code": null,
"e": 403,
"s": 382,
"text": "0 <= L <= R <= 10^18"
},
{
"code": null,
"e": 480,
"s": 403,
"text": "0 <= Y <= 162 (Which is the maximum possible sum a 18 digit number can have)"
},
{
"code": null,
"e": 1037,
"s": 480,
"text": "Approach: Firstly generalizing the question, [L, R] can be written as [0, R] – [0, L-1], i.e. first finding all the numbers in the range[0, R] whose digit sum = Y, and then for the range[0, L-1], then finally subtracting each values to get out desired result. So for the case of digit let’s store the digits of number L and R in 2 separate vectors so that accessing its digit would be easier. Then we need a function that will carry (current_index, flag, sum). This function is the main part of our logic. Initializing current_index = 0, flag = 0, sum = 0."
},
{
"code": null,
"e": 1282,
"s": 1037,
"text": "Let’s say R = 462, this number has 3 indexes i.e. 0, 1, 2. Now check in how many ways can you fill the 0th index. On observation we can say we can fill 0th index as 0, 1, 2, 3 and 4. If we exceed 4, then we would form a number greater than 462."
},
{
"code": null,
"e": 1692,
"s": 1282,
"text": "Now, if you have inserted 0 in 0th index then what can be the possibility for 1st index ? Answer – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Since you have a number 0 in the 0th index you can fill any number from 0-9 in the 1st index. Okay as you can fill any number in next index, you will turn flag = 1. flag = 1 tell us that we have the advantage to fill anything from 0-9. Similarly thinking up for the other indexes."
},
{
"code": null,
"e": 1725,
"s": 1692,
"text": "Now if we see the base condition"
},
{
"code": null,
"e": 1787,
"s": 1725,
"text": "if(current_index == n) {if(sum == Y) return 1;else return 0;}"
},
{
"code": null,
"e": 1840,
"s": 1787,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1844,
"s": 1840,
"text": "C++"
},
{
"code": "#include<bits/stdc++.h>using namespace std; // function to convert digit to vectorvector<int> digitToVec(int n) { vector<int> a; while (n) { a.push_back(n % 10); n = n / 10; } reverse(a.begin(), a.end()); return a;} int Y; // setting Y as globalint dp[19][2][18 * 9 + 1]; // 3D dpint func(int ind, int flag, int sum, vector<int> a) { if (ind == a.size()) { if (sum == Y) return 1; else return 0; } if (dp[ind][flag][sum] != -1) return dp[ind][flag][sum]; // if flag = 0, I know I can only fill from 0 to a[ind] // if flag = 1, I have the advantage to fill from 0 to 9 int limit = 9; if (flag == 0) limit = a[ind]; int cnt = 0; for (int num = 0; num <= limit; num++) { // if flag = 0, which means no advantage // and I am still filling the same number as a[ind] means giving him no advantage // hence the next recursion call flag still stays as 0 if (flag == 0 && num == a[ind]) { cnt += func(ind + 1, 0, sum + num, a); } else { cnt += func(ind + 1, 1, sum + num, a); } } return dp[ind][flag][sum] = cnt;} // intermediate function helping to initialize all values of func()int ans(int n) { vector<int> a = digitToVec(n); memset(dp, -1, sizeof dp); // initializing dp as -1 return func(0, 0, 0, a);} // Driver codeint main() { int l, r; cin >> l >> r >> Y; cout << ans(r) - ans(l - 1); return 0;}",
"e": 3330,
"s": 1844,
"text": null
},
{
"code": null,
"e": 3332,
"s": 3330,
"text": "2"
},
{
"code": null,
"e": 3407,
"s": 3334,
"text": "Now talking of the worst case Time Complexity: O(19 * 2 * (18 * 9) * 10)"
},
{
"code": null,
"e": 3420,
"s": 3407,
"text": "prerna saini"
},
{
"code": null,
"e": 3432,
"s": 3420,
"text": "29AjayKumar"
},
{
"code": null,
"e": 3447,
"s": 3432,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 3457,
"s": 3447,
"text": "Code_Mech"
},
{
"code": null,
"e": 3472,
"s": 3457,
"text": "ashishraut0910"
},
{
"code": null,
"e": 3492,
"s": 3472,
"text": "Number Divisibility"
},
{
"code": null,
"e": 3506,
"s": 3492,
"text": "number-theory"
},
{
"code": null,
"e": 3519,
"s": 3506,
"text": "Mathematical"
},
{
"code": null,
"e": 3533,
"s": 3519,
"text": "number-theory"
},
{
"code": null,
"e": 3546,
"s": 3533,
"text": "Mathematical"
},
{
"code": null,
"e": 3644,
"s": 3546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3676,
"s": 3644,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 3720,
"s": 3676,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 3766,
"s": 3720,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 3808,
"s": 3766,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 3833,
"s": 3808,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 3865,
"s": 3833,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 3900,
"s": 3865,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 3931,
"s": 3900,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 3982,
"s": 3931,
"text": "Find Union and Intersection of two unsorted arrays"
}
] |
Python List VS Array VS Tuple
|
09 Feb, 2021
List: A list is of an ordered collection data type that is mutable which means it can be easily modified and we can change its data values and a list can be indexed, sliced, and changed and each element can be accessed using its index value in the list. The following are the main characteristics of a List:
The list is an ordered collection of data types.
The list is mutable.
List are dynamic and can contain objects of different data types.
List elements can be accessed by index number.
Example:
Python
# Python program to demonstrate List list = ["mango", "strawberry", "orange", "apple", "banana"]print(list) # we can specify the range of the# index by specifying where to start# and where to endprint(list[2:4]) # we can also change the item in the# list by using its index numberlist[1] = "grapes"print(list[1])
Output :
['mango', 'strawberry', 'orange', 'apple', 'banana']
['orange', 'apple']
grapes
Array: An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The following are the main characteristics of an Array:
An array is an ordered collection of the similar data types.
An array is mutable.
An array can be accessed by using its index number.
Examples:
Python
# Python program to demonstrate # Creation of Array # importing "array" for array creationsimport array as arr # creating an array with integer typea = arr.array('i', [1, 2, 3]) # printing original arrayprint ("The new created array is : ", end =" ")for i in range (0, 3): print (a[i], end =" ")print() # creating an array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # printing original arrayprint ("The new created array is : ", end =" ")for i in range (0, 3): print (b[i], end =" ")
Output:
The new created array is : 1 2 3
The new created array is : 2.5 3.2 3.3
Tuple: A tuple is an ordered and an immutable data type which means we cannot change its values and tuples are written in round brackets. We can access tuple by referring to the index number inside the square brackets. The following are the main characteristics of a Tuple:
Tuples are immutable and can store any type of data type.
it is defined using ().
it cannot be changed or replaced as it is an immutable data type.
Examples:
Python
tuple = ("orange","apple","banana")print(tuple) # we can access the items in# the tuple by its index numberprint(tuple[2]) #we can specify the range of the# index by specifying where to start# and where to endprint(tuple[0:2])
Output :
('orange', 'apple', 'banana')
banana
('orange', 'apple')
List
Array
Tuple
jinojossy93
Python-array
python-list
python-tuple
Difference Between
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Feb, 2021"
},
{
"code": null,
"e": 360,
"s": 52,
"text": "List: A list is of an ordered collection data type that is mutable which means it can be easily modified and we can change its data values and a list can be indexed, sliced, and changed and each element can be accessed using its index value in the list. The following are the main characteristics of a List:"
},
{
"code": null,
"e": 409,
"s": 360,
"text": "The list is an ordered collection of data types."
},
{
"code": null,
"e": 430,
"s": 409,
"text": "The list is mutable."
},
{
"code": null,
"e": 496,
"s": 430,
"text": "List are dynamic and can contain objects of different data types."
},
{
"code": null,
"e": 543,
"s": 496,
"text": "List elements can be accessed by index number."
},
{
"code": null,
"e": 553,
"s": 543,
"text": "Example: "
},
{
"code": null,
"e": 560,
"s": 553,
"text": "Python"
},
{
"code": "# Python program to demonstrate List list = [\"mango\", \"strawberry\", \"orange\", \"apple\", \"banana\"]print(list) # we can specify the range of the# index by specifying where to start# and where to endprint(list[2:4]) # we can also change the item in the# list by using its index numberlist[1] = \"grapes\"print(list[1])",
"e": 880,
"s": 560,
"text": null
},
{
"code": null,
"e": 889,
"s": 880,
"text": "Output :"
},
{
"code": null,
"e": 969,
"s": 889,
"text": "['mango', 'strawberry', 'orange', 'apple', 'banana']\n['orange', 'apple']\ngrapes"
},
{
"code": null,
"e": 1382,
"s": 969,
"text": "Array: An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The following are the main characteristics of an Array:"
},
{
"code": null,
"e": 1443,
"s": 1382,
"text": "An array is an ordered collection of the similar data types."
},
{
"code": null,
"e": 1464,
"s": 1443,
"text": "An array is mutable."
},
{
"code": null,
"e": 1516,
"s": 1464,
"text": "An array can be accessed by using its index number."
},
{
"code": null,
"e": 1527,
"s": 1516,
"text": "Examples: "
},
{
"code": null,
"e": 1534,
"s": 1527,
"text": "Python"
},
{
"code": "# Python program to demonstrate # Creation of Array # importing \"array\" for array creationsimport array as arr # creating an array with integer typea = arr.array('i', [1, 2, 3]) # printing original arrayprint (\"The new created array is : \", end =\" \")for i in range (0, 3): print (a[i], end =\" \")print() # creating an array with float typeb = arr.array('d', [2.5, 3.2, 3.3]) # printing original arrayprint (\"The new created array is : \", end =\" \")for i in range (0, 3): print (b[i], end =\" \")",
"e": 2043,
"s": 1534,
"text": null
},
{
"code": null,
"e": 2051,
"s": 2043,
"text": "Output:"
},
{
"code": null,
"e": 2128,
"s": 2053,
"text": "The new created array is : 1 2 3 \nThe new created array is : 2.5 3.2 3.3"
},
{
"code": null,
"e": 2404,
"s": 2128,
"text": "Tuple: A tuple is an ordered and an immutable data type which means we cannot change its values and tuples are written in round brackets. We can access tuple by referring to the index number inside the square brackets. The following are the main characteristics of a Tuple:"
},
{
"code": null,
"e": 2462,
"s": 2404,
"text": "Tuples are immutable and can store any type of data type."
},
{
"code": null,
"e": 2486,
"s": 2462,
"text": "it is defined using ()."
},
{
"code": null,
"e": 2552,
"s": 2486,
"text": "it cannot be changed or replaced as it is an immutable data type."
},
{
"code": null,
"e": 2563,
"s": 2552,
"text": "Examples: "
},
{
"code": null,
"e": 2570,
"s": 2563,
"text": "Python"
},
{
"code": "tuple = (\"orange\",\"apple\",\"banana\")print(tuple) # we can access the items in# the tuple by its index numberprint(tuple[2]) #we can specify the range of the# index by specifying where to start# and where to endprint(tuple[0:2])",
"e": 2797,
"s": 2570,
"text": null
},
{
"code": null,
"e": 2806,
"s": 2797,
"text": "Output :"
},
{
"code": null,
"e": 2863,
"s": 2806,
"text": "('orange', 'apple', 'banana')\nbanana\n('orange', 'apple')"
},
{
"code": null,
"e": 2868,
"s": 2863,
"text": "List"
},
{
"code": null,
"e": 2874,
"s": 2868,
"text": "Array"
},
{
"code": null,
"e": 2880,
"s": 2874,
"text": "Tuple"
},
{
"code": null,
"e": 2892,
"s": 2880,
"text": "jinojossy93"
},
{
"code": null,
"e": 2905,
"s": 2892,
"text": "Python-array"
},
{
"code": null,
"e": 2917,
"s": 2905,
"text": "python-list"
},
{
"code": null,
"e": 2930,
"s": 2917,
"text": "python-tuple"
},
{
"code": null,
"e": 2949,
"s": 2930,
"text": "Difference Between"
},
{
"code": null,
"e": 2956,
"s": 2949,
"text": "Python"
},
{
"code": null,
"e": 2968,
"s": 2956,
"text": "python-list"
}
] |
Prolog - Hello World
|
In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment.
After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows −
write('Hello World').
Note − After each line, you have to use one period (.) symbol to show that the line has ended.
The corresponding output will be as shown below −
Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console.
Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps −
Step 1 − From the prolog console, go to File > Change Dir, then click on that menu.
Step 2 − Select the proper folder and press OK.
Now we can see in the prolog console, it shows that we have successfully changed the directory.
Step 3 − Now create one file (extension is *.pl) and write the code as follows −
main :- write('This is sample Prolog program'),
write(' This program is written into hello_world.pl file').
Now let’s run the code. To run it, we have to write the file name as follows −
[hello_world]
The output is as follows −
|
[
{
"code": null,
"e": 2377,
"s": 2226,
"text": "In the previous section, we have seen how to install GNU Prolog. Now, we will see how to write a simple Hello World program in our Prolog environment."
},
{
"code": null,
"e": 2519,
"s": 2377,
"text": "After running the GNU prolog, we can write hello world program directly from the console. To do so, we have to write the command as follows −"
},
{
"code": null,
"e": 2542,
"s": 2519,
"text": "write('Hello World').\n"
},
{
"code": null,
"e": 2637,
"s": 2542,
"text": "Note − After each line, you have to use one period (.) symbol to show that the line has ended."
},
{
"code": null,
"e": 2687,
"s": 2637,
"text": "The corresponding output will be as shown below −"
},
{
"code": null,
"e": 2781,
"s": 2687,
"text": "Now let us see how to run the Prolog script file (extension is *.pl) into the Prolog console."
},
{
"code": null,
"e": 2952,
"s": 2781,
"text": "Before running *.pl file, we must store the file into the directory where the GNU prolog console is pointing, otherwise just change the directory by the following steps −"
},
{
"code": null,
"e": 3036,
"s": 2952,
"text": "Step 1 − From the prolog console, go to File > Change Dir, then click on that menu."
},
{
"code": null,
"e": 3084,
"s": 3036,
"text": "Step 2 − Select the proper folder and press OK."
},
{
"code": null,
"e": 3180,
"s": 3084,
"text": "Now we can see in the prolog console, it shows that we have successfully changed the directory."
},
{
"code": null,
"e": 3261,
"s": 3180,
"text": "Step 3 − Now create one file (extension is *.pl) and write the code as follows −"
},
{
"code": null,
"e": 3370,
"s": 3261,
"text": "main :- write('This is sample Prolog program'),\nwrite(' This program is written into hello_world.pl file').\n"
},
{
"code": null,
"e": 3449,
"s": 3370,
"text": "Now let’s run the code. To run it, we have to write the file name as follows −"
},
{
"code": null,
"e": 3464,
"s": 3449,
"text": "[hello_world]\n"
}
] |
Tag Object – Python Beautifulsoup
|
05 Sep, 2020
Tag object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Tag object corresponds to an XML or HTML tag in the original document. Further, this object is usually used to extract a tag from the whole HTML document. Further, Beautiful Soup is not an HTTP client which means to scrap online websites you first have to download them using requests module and then serve it to Beautiful Soup for scraping. Additionally, this object returns the first found tag if your document have multiple tags with the same name.
Prerequisite: Beautiful Soup Installation
Syntax:
Object.tag_name
Parameters: This function doesn’t accept any parameter.
Below given examples explain the concept of Tag object in Beautiful Soup.Example 1: In this example we are going to extract h1 tag element only.
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <h1>a web page</h1> </html> ''', "lxml") # Get the tagtag = soup.h1 # Print the outputprint(tag)
Output:
<h1>a web page</h1>
Example 2: In this example we are going to see the type of strong tag element only.
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <strong>a web page</strong> </html> ''', "lxml") # Get the tagtag = soup.strong # Print the outputprint(type(tag))
Output:
<class 'bs4.element.Tag'>
Example 3: In this example we are going to see the output from a HTML with multiple tags.
# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <strong>the first strong tag</strong> <h1> Heading </h1> <strong>the second strong tag</strong> </html> ''', "lxml") # Get the tagtag = soup.strong # Print the outputprint(tag)
Output:
<strong>the first strong tag</strong>
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 681,
"s": 28,
"text": "Tag object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. Tag object corresponds to an XML or HTML tag in the original document. Further, this object is usually used to extract a tag from the whole HTML document. Further, Beautiful Soup is not an HTTP client which means to scrap online websites you first have to download them using requests module and then serve it to Beautiful Soup for scraping. Additionally, this object returns the first found tag if your document have multiple tags with the same name."
},
{
"code": null,
"e": 723,
"s": 681,
"text": "Prerequisite: Beautiful Soup Installation"
},
{
"code": null,
"e": 731,
"s": 723,
"text": "Syntax:"
},
{
"code": null,
"e": 747,
"s": 731,
"text": "Object.tag_name"
},
{
"code": null,
"e": 803,
"s": 747,
"text": "Parameters: This function doesn’t accept any parameter."
},
{
"code": null,
"e": 948,
"s": 803,
"text": "Below given examples explain the concept of Tag object in Beautiful Soup.Example 1: In this example we are going to extract h1 tag element only."
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <h1>a web page</h1> </html> ''', \"lxml\") # Get the tagtag = soup.h1 # Print the outputprint(tag)",
"e": 1190,
"s": 948,
"text": null
},
{
"code": null,
"e": 1198,
"s": 1190,
"text": "Output:"
},
{
"code": null,
"e": 1218,
"s": 1198,
"text": "<h1>a web page</h1>"
},
{
"code": null,
"e": 1302,
"s": 1218,
"text": "Example 2: In this example we are going to see the type of strong tag element only."
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with an HTML pagesoup = BeautifulSoup(''' <html> <strong>a web page</strong> </html> ''', \"lxml\") # Get the tagtag = soup.strong # Print the outputprint(type(tag))",
"e": 1562,
"s": 1302,
"text": null
},
{
"code": null,
"e": 1570,
"s": 1562,
"text": "Output:"
},
{
"code": null,
"e": 1596,
"s": 1570,
"text": "<class 'bs4.element.Tag'>"
},
{
"code": null,
"e": 1686,
"s": 1596,
"text": "Example 3: In this example we are going to see the output from a HTML with multiple tags."
},
{
"code": "# Import Beautiful Soupfrom bs4 import BeautifulSoup # Initialize the object with a HTML pagesoup = BeautifulSoup(''' <html> <strong>the first strong tag</strong> <h1> Heading </h1> <strong>the second strong tag</strong> </html> ''', \"lxml\") # Get the tagtag = soup.strong # Print the outputprint(tag)",
"e": 2021,
"s": 1686,
"text": null
},
{
"code": null,
"e": 2029,
"s": 2021,
"text": "Output:"
},
{
"code": null,
"e": 2067,
"s": 2029,
"text": "<strong>the first strong tag</strong>"
},
{
"code": null,
"e": 2074,
"s": 2067,
"text": "Python"
},
{
"code": null,
"e": 2172,
"s": 2074,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2204,
"s": 2172,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2231,
"s": 2204,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2252,
"s": 2231,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2275,
"s": 2252,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2306,
"s": 2275,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2362,
"s": 2306,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2404,
"s": 2362,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2446,
"s": 2404,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2485,
"s": 2446,
"text": "Python | Get unique values from a list"
}
] |
Python Number randrange() Method
|
Python number method randrange() returns a randomly selected element from range(start, stop, step).
Following is the syntax for randrange() method −
randrange ([start,] stop [,step])
Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object.
start − Start point of the range. This would be included in the range.
start − Start point of the range. This would be included in the range.
stop − Stop point of the range. This would be excluded from the range.
stop − Stop point of the range. This would be excluded from the range.
step − Steps to be added in a number to decide a random number.
step − Steps to be added in a number to decide a random number.
This method returns a random item from the given range
The following example shows the usage of randrange() method.
#!/usr/bin/python
import random
# Select an even number in 100 <= number < 1000
print "randrange(100, 1000, 2) : ", random.randrange(100, 1000, 2)
# Select another number in 100 <= number < 1000
print "randrange(100, 1000, 3) : ", random.randrange(100, 1000, 3)
When we run above program, it produces following result −
randrange(100, 1000, 2) : 976
randrange(100, 1000, 3) : 520
|
[
{
"code": null,
"e": 2478,
"s": 2378,
"text": "Python number method randrange() returns a randomly selected element from range(start, stop, step)."
},
{
"code": null,
"e": 2527,
"s": 2478,
"text": "Following is the syntax for randrange() method −"
},
{
"code": null,
"e": 2562,
"s": 2527,
"text": "randrange ([start,] stop [,step])\n"
},
{
"code": null,
"e": 2713,
"s": 2562,
"text": "Note − This function is not accessible directly, so we need to import random module and then we need to call this function using random static object."
},
{
"code": null,
"e": 2784,
"s": 2713,
"text": "start − Start point of the range. This would be included in the range."
},
{
"code": null,
"e": 2855,
"s": 2784,
"text": "start − Start point of the range. This would be included in the range."
},
{
"code": null,
"e": 2926,
"s": 2855,
"text": "stop − Stop point of the range. This would be excluded from the range."
},
{
"code": null,
"e": 2997,
"s": 2926,
"text": "stop − Stop point of the range. This would be excluded from the range."
},
{
"code": null,
"e": 3061,
"s": 2997,
"text": "step − Steps to be added in a number to decide a random number."
},
{
"code": null,
"e": 3125,
"s": 3061,
"text": "step − Steps to be added in a number to decide a random number."
},
{
"code": null,
"e": 3180,
"s": 3125,
"text": "This method returns a random item from the given range"
},
{
"code": null,
"e": 3241,
"s": 3180,
"text": "The following example shows the usage of randrange() method."
},
{
"code": null,
"e": 3505,
"s": 3241,
"text": "#!/usr/bin/python\nimport random\n\n# Select an even number in 100 <= number < 1000\nprint \"randrange(100, 1000, 2) : \", random.randrange(100, 1000, 2)\n\n# Select another number in 100 <= number < 1000\nprint \"randrange(100, 1000, 3) : \", random.randrange(100, 1000, 3)"
},
{
"code": null,
"e": 3563,
"s": 3505,
"text": "When we run above program, it produces following result −"
}
] |
Removing Duplicate Rows (Based on Values from Multiple Columns) From SQL Table
|
28 Nov, 2021
In SQL, some rows contain duplicate entries in multiple columns(>1). For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table RESULT inside the database GeeksForGeeks. This table has 5 columns namely STUDENT_ID, PHYSICS_MARKS, CHEMISTRY_MARKS, MATHS_MARKS, and TOTAL_MARKS containing the id of the student, his/her marks in physics, chemistry, and mathematics, and finally his/her total marks.
Query:
CREATE TABLE RESULT(
STUDENT_ID INT,
PHYSICS_MARKS INT,
CHEMISTRY_MARKS INT,
MATHS_MARKS INT,
TOTAL_MARKS INT);
Output:
Step 4: Describe the structure of the table RESULT.
Query:
EXEC SP_COLUMNS RESULT;
Output:
Step 5: Insert 10 rows into the RESULT table.
Query:
INSERT INTO RESULT VALUES(1,90,88,75,253);
INSERT INTO RESULT VALUES(2,99,88,75,262);
INSERT INTO RESULT VALUES(3,96,88,75,256);
INSERT INTO RESULT VALUES(4,97,87,76,260);
INSERT INTO RESULT VALUES(5,91,86,77,254);
INSERT INTO RESULT VALUES(6,92,85,78,255);
INSERT INTO RESULT VALUES(7,93,84,79,256);
INSERT INTO RESULT VALUES(8,80,83,87,250);
INSERT INTO RESULT VALUES(9,80,82,88,250);
INSERT INTO RESULT VALUES(10,80,81,89,250);
Output:
Step 6: Display all the rows of the RESULT table.
Query:
SELECT * FROM RESULT;
Output:
Step 7: Delete rows from the table RESULT which have duplicate entries in the columns CHEMISTRY_MARKS and MATHS_MARKS. To achieve this, we use the DELETE function by self joining(use JOIN function on 2 aliases of the table i.e. R1 and R2) the table with itself and comparing the entries of the columns CHEMISTRY_MARKS and MATHS_MARKS for different entries of the column STUDENT_ID because ID is unique for each student.
Syntax:
DELETE T1 FROM TABLE_NAME T1
JOIN TABLE_NAME T2
ON T1.COLUMN_NAME2 = T2.COLUMN_NAME2 AND
T1.COLUMN_NAME3 = T2.COLUMN_NAME3 AND .......
AND T2.COLUMN_NAME1 < T1.COLUMN_NAME1;
Query:
DELETE R1 FROM RESULT R1
JOIN RESULT R2
ON R1.CHEMISTRY_MARKS = R2.CHEMISTRY_MARKS
AND R1.MATHS_MARKS = R2.MATHS_MARKS
AND R2.STUDENT_ID < R1.STUDENT_ID;
Output:
Step 8: Display all the rows of the updated RESULT table.
Query:
SELECT * FROM RESULT;
Note: No row has duplicate entries in the columns CHEMISTRY_MARKS and MATHS_MARKS.
Output:
Step 9: Delete rows from the table RESULT which have duplicate entries in the columns TOTAL_MARKS and PHYSICS_MARKS.
Query:
DELETE R1 FROM RESULT R1
JOIN RESULT R2
ON R1.TOTAL_MARKS = R2.TOTAL_MARKS AND R1.PHYSICS_MARKS = R2.PHYSICS_MARKS
AND R2.STUDENT_ID < R1.STUDENT_ID;
Output:
Step 10: Display all the rows of the updated RESULT table.
Query:
SELECT * FROM RESULT;
Note – No row has duplicate entries in the columns TOTAL_MARKS and PHYSICS_MARKS.
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Window functions in SQL
SQL | GROUP BY
Difference between DDL and DML in DBMS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2021"
},
{
"code": null,
"e": 310,
"s": 28,
"text": "In SQL, some rows contain duplicate entries in multiple columns(>1). For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database."
},
{
"code": null,
"e": 410,
"s": 310,
"text": "Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks."
},
{
"code": null,
"e": 417,
"s": 410,
"text": "Query:"
},
{
"code": null,
"e": 447,
"s": 417,
"text": "CREATE DATABASE GeeksForGeeks"
},
{
"code": null,
"e": 455,
"s": 447,
"text": "Output:"
},
{
"code": null,
"e": 527,
"s": 455,
"text": "Step 2: Use the GeeksForGeeks database. For this use the below command."
},
{
"code": null,
"e": 534,
"s": 527,
"text": "Query:"
},
{
"code": null,
"e": 552,
"s": 534,
"text": "USE GeeksForGeeks"
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Output:"
},
{
"code": null,
"e": 851,
"s": 560,
"text": "Step 3: Create a table RESULT inside the database GeeksForGeeks. This table has 5 columns namely STUDENT_ID, PHYSICS_MARKS, CHEMISTRY_MARKS, MATHS_MARKS, and TOTAL_MARKS containing the id of the student, his/her marks in physics, chemistry, and mathematics, and finally his/her total marks."
},
{
"code": null,
"e": 858,
"s": 851,
"text": "Query:"
},
{
"code": null,
"e": 971,
"s": 858,
"text": "CREATE TABLE RESULT(\nSTUDENT_ID INT,\nPHYSICS_MARKS INT,\nCHEMISTRY_MARKS INT,\nMATHS_MARKS INT,\nTOTAL_MARKS INT);"
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Output:"
},
{
"code": null,
"e": 1031,
"s": 979,
"text": "Step 4: Describe the structure of the table RESULT."
},
{
"code": null,
"e": 1038,
"s": 1031,
"text": "Query:"
},
{
"code": null,
"e": 1062,
"s": 1038,
"text": "EXEC SP_COLUMNS RESULT;"
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Output:"
},
{
"code": null,
"e": 1116,
"s": 1070,
"text": "Step 5: Insert 10 rows into the RESULT table."
},
{
"code": null,
"e": 1123,
"s": 1116,
"text": "Query:"
},
{
"code": null,
"e": 1554,
"s": 1123,
"text": "INSERT INTO RESULT VALUES(1,90,88,75,253);\nINSERT INTO RESULT VALUES(2,99,88,75,262);\nINSERT INTO RESULT VALUES(3,96,88,75,256);\nINSERT INTO RESULT VALUES(4,97,87,76,260);\nINSERT INTO RESULT VALUES(5,91,86,77,254);\nINSERT INTO RESULT VALUES(6,92,85,78,255);\nINSERT INTO RESULT VALUES(7,93,84,79,256);\nINSERT INTO RESULT VALUES(8,80,83,87,250);\nINSERT INTO RESULT VALUES(9,80,82,88,250);\nINSERT INTO RESULT VALUES(10,80,81,89,250);"
},
{
"code": null,
"e": 1562,
"s": 1554,
"text": "Output:"
},
{
"code": null,
"e": 1612,
"s": 1562,
"text": "Step 6: Display all the rows of the RESULT table."
},
{
"code": null,
"e": 1619,
"s": 1612,
"text": "Query:"
},
{
"code": null,
"e": 1641,
"s": 1619,
"text": "SELECT * FROM RESULT;"
},
{
"code": null,
"e": 1649,
"s": 1641,
"text": "Output:"
},
{
"code": null,
"e": 2069,
"s": 1649,
"text": "Step 7: Delete rows from the table RESULT which have duplicate entries in the columns CHEMISTRY_MARKS and MATHS_MARKS. To achieve this, we use the DELETE function by self joining(use JOIN function on 2 aliases of the table i.e. R1 and R2) the table with itself and comparing the entries of the columns CHEMISTRY_MARKS and MATHS_MARKS for different entries of the column STUDENT_ID because ID is unique for each student."
},
{
"code": null,
"e": 2077,
"s": 2069,
"text": "Syntax:"
},
{
"code": null,
"e": 2251,
"s": 2077,
"text": "DELETE T1 FROM TABLE_NAME T1\nJOIN TABLE_NAME T2\nON T1.COLUMN_NAME2 = T2.COLUMN_NAME2 AND\nT1.COLUMN_NAME3 = T2.COLUMN_NAME3 AND .......\nAND T2.COLUMN_NAME1 < T1.COLUMN_NAME1;"
},
{
"code": null,
"e": 2258,
"s": 2251,
"text": "Query:"
},
{
"code": null,
"e": 2412,
"s": 2258,
"text": "DELETE R1 FROM RESULT R1\nJOIN RESULT R2\nON R1.CHEMISTRY_MARKS = R2.CHEMISTRY_MARKS\nAND R1.MATHS_MARKS = R2.MATHS_MARKS\nAND R2.STUDENT_ID < R1.STUDENT_ID;"
},
{
"code": null,
"e": 2420,
"s": 2412,
"text": "Output:"
},
{
"code": null,
"e": 2478,
"s": 2420,
"text": "Step 8: Display all the rows of the updated RESULT table."
},
{
"code": null,
"e": 2485,
"s": 2478,
"text": "Query:"
},
{
"code": null,
"e": 2507,
"s": 2485,
"text": "SELECT * FROM RESULT;"
},
{
"code": null,
"e": 2590,
"s": 2507,
"text": "Note: No row has duplicate entries in the columns CHEMISTRY_MARKS and MATHS_MARKS."
},
{
"code": null,
"e": 2598,
"s": 2590,
"text": "Output:"
},
{
"code": null,
"e": 2715,
"s": 2598,
"text": "Step 9: Delete rows from the table RESULT which have duplicate entries in the columns TOTAL_MARKS and PHYSICS_MARKS."
},
{
"code": null,
"e": 2722,
"s": 2715,
"text": "Query:"
},
{
"code": null,
"e": 2872,
"s": 2722,
"text": "DELETE R1 FROM RESULT R1\nJOIN RESULT R2\nON R1.TOTAL_MARKS = R2.TOTAL_MARKS AND R1.PHYSICS_MARKS = R2.PHYSICS_MARKS\nAND R2.STUDENT_ID < R1.STUDENT_ID;"
},
{
"code": null,
"e": 2880,
"s": 2872,
"text": "Output:"
},
{
"code": null,
"e": 2939,
"s": 2880,
"text": "Step 10: Display all the rows of the updated RESULT table."
},
{
"code": null,
"e": 2946,
"s": 2939,
"text": "Query:"
},
{
"code": null,
"e": 2968,
"s": 2946,
"text": "SELECT * FROM RESULT;"
},
{
"code": null,
"e": 3050,
"s": 2968,
"text": "Note – No row has duplicate entries in the columns TOTAL_MARKS and PHYSICS_MARKS."
},
{
"code": null,
"e": 3058,
"s": 3050,
"text": "Output:"
},
{
"code": null,
"e": 3065,
"s": 3058,
"text": "Picked"
},
{
"code": null,
"e": 3075,
"s": 3065,
"text": "SQL-Query"
},
{
"code": null,
"e": 3086,
"s": 3075,
"text": "SQL-Server"
},
{
"code": null,
"e": 3090,
"s": 3086,
"text": "SQL"
},
{
"code": null,
"e": 3094,
"s": 3090,
"text": "SQL"
},
{
"code": null,
"e": 3192,
"s": 3094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3203,
"s": 3192,
"text": "CTE in SQL"
},
{
"code": null,
"e": 3269,
"s": 3203,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 3300,
"s": 3269,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 3324,
"s": 3300,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 3336,
"s": 3324,
"text": "SQL | Views"
},
{
"code": null,
"e": 3381,
"s": 3336,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 3413,
"s": 3381,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 3437,
"s": 3413,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 3452,
"s": 3437,
"text": "SQL | GROUP BY"
}
] |
Keyboard module in Python
|
24 Jan, 2019
Python provides a library named keyboard which is used to get full control of the keyboard. It’s a small Python library which can hook global events, register hotkeys, simulate key presses and much more.
It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys.
It captures all keys, even onscreen keyboard events are also captured.
Keyboard module supports complex hotkeys.
Using this module we can listen and send keyboard events.
It works on both windows and linux operating system.
Install using this command:
pip install keyboard
Example #1:
# Using Keyboard module in Pythonimport keyboard # It writes the content to outputkeyboard.write("GEEKS FOR GEEKS\n") # It writes the keys r, k and endofline keyboard.press_and_release('shift + r, shift + k, \n')keyboard.press_and_release('R, K') # it blocks until ctrl is pressedkeyboard.wait('Ctrl')
Output:
GEEKS FOR GEEKS
RK
rk
Example #2: Keyboard module to enter hotkeys.
# Keyboard module in Pythonimport keyboard # press a to print rkkeyboard.add_hotkey('a', lambda: keyboard.write('Geek'))keyboard.add_hotkey('ctrl + shift + a', print, args =('you entered', 'hotkey')) keyboard.wait('esc')
Output:
ark
you entered hotkey
Example #3: Keyboard module also used to record all the keyboard activities and replay them using play method.
# Keyboard module in Pythonimport keyboard # It records all the keys until escape is pressedrk = keyboard.record(until ='Esc') # It replay back the all keyskeyboard.play(rk, speed_factor = 1)
Output:
www.geeksforgeeks.org
Reference : https://pypi.org/project/keyboard/
Python-Library
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jan, 2019"
},
{
"code": null,
"e": 256,
"s": 52,
"text": "Python provides a library named keyboard which is used to get full control of the keyboard. It’s a small Python library which can hook global events, register hotkeys, simulate key presses and much more."
},
{
"code": null,
"e": 386,
"s": 256,
"text": "It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys."
},
{
"code": null,
"e": 457,
"s": 386,
"text": "It captures all keys, even onscreen keyboard events are also captured."
},
{
"code": null,
"e": 499,
"s": 457,
"text": "Keyboard module supports complex hotkeys."
},
{
"code": null,
"e": 557,
"s": 499,
"text": "Using this module we can listen and send keyboard events."
},
{
"code": null,
"e": 610,
"s": 557,
"text": "It works on both windows and linux operating system."
},
{
"code": null,
"e": 638,
"s": 610,
"text": "Install using this command:"
},
{
"code": null,
"e": 659,
"s": 638,
"text": "pip install keyboard"
},
{
"code": null,
"e": 671,
"s": 659,
"text": "Example #1:"
},
{
"code": "# Using Keyboard module in Pythonimport keyboard # It writes the content to outputkeyboard.write(\"GEEKS FOR GEEKS\\n\") # It writes the keys r, k and endofline keyboard.press_and_release('shift + r, shift + k, \\n')keyboard.press_and_release('R, K') # it blocks until ctrl is pressedkeyboard.wait('Ctrl')",
"e": 976,
"s": 671,
"text": null
},
{
"code": null,
"e": 984,
"s": 976,
"text": "Output:"
},
{
"code": null,
"e": 1008,
"s": 984,
"text": "GEEKS FOR GEEKS \nRK\nrk\n"
},
{
"code": null,
"e": 1055,
"s": 1008,
"text": " Example #2: Keyboard module to enter hotkeys."
},
{
"code": "# Keyboard module in Pythonimport keyboard # press a to print rkkeyboard.add_hotkey('a', lambda: keyboard.write('Geek'))keyboard.add_hotkey('ctrl + shift + a', print, args =('you entered', 'hotkey')) keyboard.wait('esc')",
"e": 1278,
"s": 1055,
"text": null
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Output:"
},
{
"code": null,
"e": 1310,
"s": 1286,
"text": "ark\nyou entered hotkey\n"
},
{
"code": null,
"e": 1422,
"s": 1310,
"text": " Example #3: Keyboard module also used to record all the keyboard activities and replay them using play method."
},
{
"code": "# Keyboard module in Pythonimport keyboard # It records all the keys until escape is pressedrk = keyboard.record(until ='Esc') # It replay back the all keyskeyboard.play(rk, speed_factor = 1)",
"e": 1616,
"s": 1422,
"text": null
},
{
"code": null,
"e": 1624,
"s": 1616,
"text": "Output:"
},
{
"code": null,
"e": 1648,
"s": 1624,
"text": "www.geeksforgeeks.org \n"
},
{
"code": null,
"e": 1696,
"s": 1648,
"text": " Reference : https://pypi.org/project/keyboard/"
},
{
"code": null,
"e": 1711,
"s": 1696,
"text": "Python-Library"
},
{
"code": null,
"e": 1735,
"s": 1711,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1742,
"s": 1735,
"text": "Python"
},
{
"code": null,
"e": 1761,
"s": 1742,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1859,
"s": 1761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1877,
"s": 1859,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1919,
"s": 1877,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1941,
"s": 1919,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1976,
"s": 1941,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2002,
"s": 1976,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2034,
"s": 2002,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2063,
"s": 2034,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2090,
"s": 2063,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2120,
"s": 2090,
"text": "Iterate over a list in Python"
}
] |
Kali Linux – File Management
|
22 Jun, 2020
In Kali Linux, most of the operations are performed on files. And to handle these files Kali Linux has directories also known as folders which are maintained in a tree-like structure. Though, these directories are also a type of file themselves. Kali Linux has 3 basic types of files:
Regular Files: It is the common file type in Linux. it includes files like – text files, images, binary files, etc. Such files can be created using the touch command. They consist of the majority of files in the Linux/UNIX system. The regular file contains ASCII or Human Readable text, executable program binaries, program data, and much more.Directories: Windows call these directories as folders. These are the files that store the list of file names and the related information. The root directory(/) is the base of the system, /home/ is the default location for user’s home directories, /bin for Essential User Binaries, /boot – Static Boot Files, etc. We could create new directories with mkdir command.Special Files: Represents a real physical device such as a printer which is used for IO operations. Device or special files are used for device Input/Output(I/O) on UNIX and Linux systems. You can see them in a file system as an ordinary directory or file.In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system.
Regular Files: It is the common file type in Linux. it includes files like – text files, images, binary files, etc. Such files can be created using the touch command. They consist of the majority of files in the Linux/UNIX system. The regular file contains ASCII or Human Readable text, executable program binaries, program data, and much more.
Directories: Windows call these directories as folders. These are the files that store the list of file names and the related information. The root directory(/) is the base of the system, /home/ is the default location for user’s home directories, /bin for Essential User Binaries, /boot – Static Boot Files, etc. We could create new directories with mkdir command.
Special Files: Represents a real physical device such as a printer which is used for IO operations. Device or special files are used for device Input/Output(I/O) on UNIX and Linux systems. You can see them in a file system as an ordinary directory or file.In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system.
In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system.
You can read more about the Linux File Management.
Kali Linux follows a specific File hierarchy structure which is just a way of organizing files, filesystems, directories, installed packages, and external devices connected to the system. It basically sets a standard or a base for defining the directory structure.
In Kali Linux File Hierarchy Structure the base or the main directory which contains all the directories is the root directory depicted by a “/”.
1. To List the Files. In Kali Linux, we use ls command to list files and directories. To use this enter the following command in the terminal.
ls
This command will print all the file and directories in the current directory.
2. To create a new file. In Kali Linux, we use touch command to create a new file. To use this enter the following command in the terminal.
touch filename.extension
This command will create a new file named filename.extension.
3. To display the content of a file. In Kali Linux, we use cat command to display the contents of a file. To use this enter the following command in the terminal.
cat filename.extension
This command will print the content of the filename.extension file.
4. To copy files. In Kali Linux, we use cp command to copy files and directories. To use this enter the following command in the terminal.
cp old/location/of/file /new/location/of/file
This command will copy file form old location to new location.
5. To move files. In Kali Linux, we use mv command to move files and directories. To use this enter the following command in the terminal.
mv old/location/of/file /new/location/of/file
This command will move the file form old location to new location.
6. To rename a file. In Kali Linux, we use mv command to rename files and directories. To use this enter the following command in the terminal.
mv filename.extension new_name.extension
This command will rename the file from filename.extension to new_name.extension.
7. To delete a file. In Kali Linux, we use rm command to delete files and directories. To use this enter the following command in the terminal.
rm filename.extension
This command will remove/delete the filename.extension from the current directory.
8. To edit a file. In Kali Linux, we use nano command to edit files. To use this enter the following command in the terminal.
nano filename.extension
This command will open an editor to write to file and after completing the same press ctrl+o to save the file.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
Introduction to Linux Operating System
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
chmod command in Linux with examples
screen command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 313,
"s": 28,
"text": "In Kali Linux, most of the operations are performed on files. And to handle these files Kali Linux has directories also known as folders which are maintained in a tree-like structure. Though, these directories are also a type of file themselves. Kali Linux has 3 basic types of files:"
},
{
"code": null,
"e": 1456,
"s": 313,
"text": "Regular Files: It is the common file type in Linux. it includes files like – text files, images, binary files, etc. Such files can be created using the touch command. They consist of the majority of files in the Linux/UNIX system. The regular file contains ASCII or Human Readable text, executable program binaries, program data, and much more.Directories: Windows call these directories as folders. These are the files that store the list of file names and the related information. The root directory(/) is the base of the system, /home/ is the default location for user’s home directories, /bin for Essential User Binaries, /boot – Static Boot Files, etc. We could create new directories with mkdir command.Special Files: Represents a real physical device such as a printer which is used for IO operations. Device or special files are used for device Input/Output(I/O) on UNIX and Linux systems. You can see them in a file system as an ordinary directory or file.In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system."
},
{
"code": null,
"e": 1801,
"s": 1456,
"text": "Regular Files: It is the common file type in Linux. it includes files like – text files, images, binary files, etc. Such files can be created using the touch command. They consist of the majority of files in the Linux/UNIX system. The regular file contains ASCII or Human Readable text, executable program binaries, program data, and much more."
},
{
"code": null,
"e": 2167,
"s": 1801,
"text": "Directories: Windows call these directories as folders. These are the files that store the list of file names and the related information. The root directory(/) is the base of the system, /home/ is the default location for user’s home directories, /bin for Essential User Binaries, /boot – Static Boot Files, etc. We could create new directories with mkdir command."
},
{
"code": null,
"e": 2601,
"s": 2167,
"text": "Special Files: Represents a real physical device such as a printer which is used for IO operations. Device or special files are used for device Input/Output(I/O) on UNIX and Linux systems. You can see them in a file system as an ordinary directory or file.In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system."
},
{
"code": null,
"e": 2779,
"s": 2601,
"text": "In Unix systems, there are two types of special files for each device, i.e. character special files and block special files. For more details, read the article Unix file system."
},
{
"code": null,
"e": 2830,
"s": 2779,
"text": "You can read more about the Linux File Management."
},
{
"code": null,
"e": 3095,
"s": 2830,
"text": "Kali Linux follows a specific File hierarchy structure which is just a way of organizing files, filesystems, directories, installed packages, and external devices connected to the system. It basically sets a standard or a base for defining the directory structure."
},
{
"code": null,
"e": 3241,
"s": 3095,
"text": "In Kali Linux File Hierarchy Structure the base or the main directory which contains all the directories is the root directory depicted by a “/”."
},
{
"code": null,
"e": 3384,
"s": 3241,
"text": "1. To List the Files. In Kali Linux, we use ls command to list files and directories. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 3388,
"s": 3384,
"text": "ls\n"
},
{
"code": null,
"e": 3467,
"s": 3388,
"text": "This command will print all the file and directories in the current directory."
},
{
"code": null,
"e": 3607,
"s": 3467,
"text": "2. To create a new file. In Kali Linux, we use touch command to create a new file. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 3633,
"s": 3607,
"text": "touch filename.extension\n"
},
{
"code": null,
"e": 3695,
"s": 3633,
"text": "This command will create a new file named filename.extension."
},
{
"code": null,
"e": 3858,
"s": 3695,
"text": "3. To display the content of a file. In Kali Linux, we use cat command to display the contents of a file. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 3882,
"s": 3858,
"text": "cat filename.extension\n"
},
{
"code": null,
"e": 3950,
"s": 3882,
"text": "This command will print the content of the filename.extension file."
},
{
"code": null,
"e": 4089,
"s": 3950,
"text": "4. To copy files. In Kali Linux, we use cp command to copy files and directories. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 4136,
"s": 4089,
"text": "cp old/location/of/file /new/location/of/file\n"
},
{
"code": null,
"e": 4199,
"s": 4136,
"text": "This command will copy file form old location to new location."
},
{
"code": null,
"e": 4338,
"s": 4199,
"text": "5. To move files. In Kali Linux, we use mv command to move files and directories. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 4385,
"s": 4338,
"text": "mv old/location/of/file /new/location/of/file\n"
},
{
"code": null,
"e": 4452,
"s": 4385,
"text": "This command will move the file form old location to new location."
},
{
"code": null,
"e": 4596,
"s": 4452,
"text": "6. To rename a file. In Kali Linux, we use mv command to rename files and directories. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 4638,
"s": 4596,
"text": "mv filename.extension new_name.extension\n"
},
{
"code": null,
"e": 4719,
"s": 4638,
"text": "This command will rename the file from filename.extension to new_name.extension."
},
{
"code": null,
"e": 4863,
"s": 4719,
"text": "7. To delete a file. In Kali Linux, we use rm command to delete files and directories. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 4886,
"s": 4863,
"text": "rm filename.extension\n"
},
{
"code": null,
"e": 4969,
"s": 4886,
"text": "This command will remove/delete the filename.extension from the current directory."
},
{
"code": null,
"e": 5095,
"s": 4969,
"text": "8. To edit a file. In Kali Linux, we use nano command to edit files. To use this enter the following command in the terminal."
},
{
"code": null,
"e": 5120,
"s": 5095,
"text": "nano filename.extension\n"
},
{
"code": null,
"e": 5231,
"s": 5120,
"text": "This command will open an editor to write to file and after completing the same press ctrl+o to save the file."
},
{
"code": null,
"e": 5242,
"s": 5231,
"text": "Linux-Unix"
},
{
"code": null,
"e": 5340,
"s": 5242,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5366,
"s": 5340,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 5401,
"s": 5366,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 5438,
"s": 5401,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 5467,
"s": 5438,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 5506,
"s": 5467,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 5543,
"s": 5506,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 5583,
"s": 5543,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 5617,
"s": 5583,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 5654,
"s": 5617,
"text": "chmod command in Linux with examples"
}
] |
Timing diagram of MVI instruction
|
18 Mar, 2020
Problem – Draw the timing diagram of the following code,
MVI B, 45
Explanation of the command – It stores the immediate 8 bit data to a register or memory location.
Example: MVI B, 45Opcode: MVIOperand: B is the destination register and 45 is the source data which needs to be transferred to the register.’45’ data will be stored in the B register.
Algorithm –
Decide what is the opcode and what is the data. Here, opcode is ‘MVI B’ and data is 45.
Assume the memory address of the opcode and the data. For example:MVI B, 452000: Opcode2001: 45
MVI B, 452000: Opcode2001: 45
The opcode fetch will be same in all the instructions.
Only the read instruction of the opcode needs to be added in the successive T states.
For the opcode fetch the IO/M (low active) = 0, S1 = 1 and S0 = 1. Also, 4 T states will be required to fetch the opcode from memory.
For the opcode read the IO/M (low active) = 0, S1 = 1 and S0 = 0. Also, only 3 T states will be required to read data from memory.
In Opcode fetch ( t1-t4 T states ) –
00 – lower bit of address where opcode is stored.
20 – higher bit of address where opcode is stored.
ALE – Provides signal for multiplexed address and data bus. Only in t1 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t1 & t4, no data is read by microprocessor. Signal is 0 in t2 & t3, data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 and S1 – Signal is 1 in t1 to t4 states, as to fetch the opcode from the memory.
In Opcode read ( t5-t7 T states ) –
01 – lower bit of address where data is stored.
20 – higher bit of address where data is stored.
ALE – Provides signal for multiplexed address and data bus. Only in t5 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t5 as no data is read by microprocessor. Signal is 0 in t6 & t7 as data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 – Signal is 0 in throughout, operation is performing on memory to read data 45.S1 – Signal is 1 throughout, operation is performing on memory to read data 45.
aggarwal19
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Mar, 2020"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Problem – Draw the timing diagram of the following code,"
},
{
"code": null,
"e": 122,
"s": 111,
"text": "MVI B, 45 "
},
{
"code": null,
"e": 220,
"s": 122,
"text": "Explanation of the command – It stores the immediate 8 bit data to a register or memory location."
},
{
"code": null,
"e": 404,
"s": 220,
"text": "Example: MVI B, 45Opcode: MVIOperand: B is the destination register and 45 is the source data which needs to be transferred to the register.’45’ data will be stored in the B register."
},
{
"code": null,
"e": 416,
"s": 404,
"text": "Algorithm –"
},
{
"code": null,
"e": 504,
"s": 416,
"text": "Decide what is the opcode and what is the data. Here, opcode is ‘MVI B’ and data is 45."
},
{
"code": null,
"e": 600,
"s": 504,
"text": "Assume the memory address of the opcode and the data. For example:MVI B, 452000: Opcode2001: 45"
},
{
"code": null,
"e": 630,
"s": 600,
"text": "MVI B, 452000: Opcode2001: 45"
},
{
"code": null,
"e": 685,
"s": 630,
"text": "The opcode fetch will be same in all the instructions."
},
{
"code": null,
"e": 771,
"s": 685,
"text": "Only the read instruction of the opcode needs to be added in the successive T states."
},
{
"code": null,
"e": 905,
"s": 771,
"text": "For the opcode fetch the IO/M (low active) = 0, S1 = 1 and S0 = 1. Also, 4 T states will be required to fetch the opcode from memory."
},
{
"code": null,
"e": 1036,
"s": 905,
"text": "For the opcode read the IO/M (low active) = 0, S1 = 1 and S0 = 0. Also, only 3 T states will be required to read data from memory."
},
{
"code": null,
"e": 1073,
"s": 1036,
"text": "In Opcode fetch ( t1-t4 T states ) –"
},
{
"code": null,
"e": 1123,
"s": 1073,
"text": "00 – lower bit of address where opcode is stored."
},
{
"code": null,
"e": 1174,
"s": 1123,
"text": "20 – higher bit of address where opcode is stored."
},
{
"code": null,
"e": 1712,
"s": 1174,
"text": "ALE – Provides signal for multiplexed address and data bus. Only in t1 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t1 & t4, no data is read by microprocessor. Signal is 0 in t2 & t3, data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 and S1 – Signal is 1 in t1 to t4 states, as to fetch the opcode from the memory."
},
{
"code": null,
"e": 1748,
"s": 1712,
"text": "In Opcode read ( t5-t7 T states ) –"
},
{
"code": null,
"e": 1796,
"s": 1748,
"text": "01 – lower bit of address where data is stored."
},
{
"code": null,
"e": 1845,
"s": 1796,
"text": "20 – higher bit of address where data is stored."
},
{
"code": null,
"e": 2460,
"s": 1845,
"text": "ALE – Provides signal for multiplexed address and data bus. Only in t5 it used as address bus to fetch lower bit of address otherwise it will be used as data bus.RD (low active) – Signal is 1 in t5 as no data is read by microprocessor. Signal is 0 in t6 & t7 as data is read by microprocessor.WR (low active) – Signal is 1 throughout, no data is written by microprocessor.IO/M (low active) – Signal is 0 in throughout, operation is performing on memory.S0 – Signal is 0 in throughout, operation is performing on memory to read data 45.S1 – Signal is 1 throughout, operation is performing on memory to read data 45."
},
{
"code": null,
"e": 2471,
"s": 2460,
"text": "aggarwal19"
},
{
"code": null,
"e": 2486,
"s": 2471,
"text": "microprocessor"
},
{
"code": null,
"e": 2505,
"s": 2486,
"text": "system-programming"
},
{
"code": null,
"e": 2542,
"s": 2505,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 2557,
"s": 2542,
"text": "microprocessor"
}
] |
Defer Keyword in Golang
|
09 Jun, 2021
In Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don’t execute until the nearby functions returns. You can create a deferred method, or function, or anonymous function by using the defer keyword.
Syntax:
// Function
defer func func_name(parameter_list Type)return_type{
// Code
}
// Method
defer func (receiver Type) method_name(parameter_list){
// Code
}
defer func (parameter_list)(return_type){
// code
}()
Important Points:
In Go language, multiple defer statements are allowed in the same program and they are executed in LIFO(Last-In, First-Out) order as shown in Example 2.
In the defer statements, the arguments are evaluated when the defer statement is executed, not when it is called.
Defer statements are generally used to ensure that the files are closed when their need is over, or to close the channel, or to catch the panics in the program.
Let us discuss this concept with the help of an example:
Example 1:
Go
// Go program to illustrate the// concept of the defer statementpackage main import "fmt" // Functionsfunc mul(a1, a2 int) int { res := a1 * a2 fmt.Println("Result: ", res) return 0} func show() { fmt.Println("Hello!, GeeksforGeeks")} // Main functionfunc main() { // Calling mul() function // Here mul function behaves // like a normal function mul(23, 45) // Calling mul()function // Using defer keyword // Here the mul() function // is defer function defer mul(23, 56) // Calling show() function show()}
Output:
Result: 1035
Hello!, GeeksforGeeks
Result: 1288
Explanation: In the above example we have two functions named mul() and show(). Where show() function is called normally in the main() function, mul() function is called in two different ways:
First, we call mul function normally(without the defer keyword), i.e, mul(23, 45) and it executes when the function is called(Output: Result : 1035 ).
Second, we call mul() function as a defer function using defer keyword, i.e, defer mul(23, 56) and it executes(Output: Result: 1288 ) when all the surrounding methods return.
Example 2:
Go
// Go program to illustrate// multiple defer statements, to illustrate LIFO policypackage main import "fmt" // Functionsfunc add(a1, a2 int) int { res := a1 + a2 fmt.Println("Result: ", res) return 0} // Main functionfunc main() { fmt.Println("Start") // Multiple defer statements // Executes in LIFO order defer fmt.Println("End") defer add(34, 56) defer add(10, 10)}
Output:
Start
Result: 20
Result: 90
End
competing23invain
Go-Keywords
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 422,
"s": 52,
"text": "In Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don’t execute until the nearby functions returns. You can create a deferred method, or function, or anonymous function by using the defer keyword."
},
{
"code": null,
"e": 430,
"s": 422,
"text": "Syntax:"
},
{
"code": null,
"e": 638,
"s": 430,
"text": "// Function\ndefer func func_name(parameter_list Type)return_type{\n// Code\n}\n\n// Method\ndefer func (receiver Type) method_name(parameter_list){\n// Code\n}\n\ndefer func (parameter_list)(return_type){\n// code\n}()"
},
{
"code": null,
"e": 656,
"s": 638,
"text": "Important Points:"
},
{
"code": null,
"e": 809,
"s": 656,
"text": "In Go language, multiple defer statements are allowed in the same program and they are executed in LIFO(Last-In, First-Out) order as shown in Example 2."
},
{
"code": null,
"e": 923,
"s": 809,
"text": "In the defer statements, the arguments are evaluated when the defer statement is executed, not when it is called."
},
{
"code": null,
"e": 1084,
"s": 923,
"text": "Defer statements are generally used to ensure that the files are closed when their need is over, or to close the channel, or to catch the panics in the program."
},
{
"code": null,
"e": 1141,
"s": 1084,
"text": "Let us discuss this concept with the help of an example:"
},
{
"code": null,
"e": 1153,
"s": 1141,
"text": "Example 1: "
},
{
"code": null,
"e": 1156,
"s": 1153,
"text": "Go"
},
{
"code": "// Go program to illustrate the// concept of the defer statementpackage main import \"fmt\" // Functionsfunc mul(a1, a2 int) int { res := a1 * a2 fmt.Println(\"Result: \", res) return 0} func show() { fmt.Println(\"Hello!, GeeksforGeeks\")} // Main functionfunc main() { // Calling mul() function // Here mul function behaves // like a normal function mul(23, 45) // Calling mul()function // Using defer keyword // Here the mul() function // is defer function defer mul(23, 56) // Calling show() function show()}",
"e": 1712,
"s": 1156,
"text": null
},
{
"code": null,
"e": 1721,
"s": 1712,
"text": "Output: "
},
{
"code": null,
"e": 1771,
"s": 1721,
"text": "Result: 1035\nHello!, GeeksforGeeks\nResult: 1288"
},
{
"code": null,
"e": 1964,
"s": 1771,
"text": "Explanation: In the above example we have two functions named mul() and show(). Where show() function is called normally in the main() function, mul() function is called in two different ways:"
},
{
"code": null,
"e": 2115,
"s": 1964,
"text": "First, we call mul function normally(without the defer keyword), i.e, mul(23, 45) and it executes when the function is called(Output: Result : 1035 )."
},
{
"code": null,
"e": 2290,
"s": 2115,
"text": "Second, we call mul() function as a defer function using defer keyword, i.e, defer mul(23, 56) and it executes(Output: Result: 1288 ) when all the surrounding methods return."
},
{
"code": null,
"e": 2301,
"s": 2290,
"text": "Example 2:"
},
{
"code": null,
"e": 2304,
"s": 2301,
"text": "Go"
},
{
"code": "// Go program to illustrate// multiple defer statements, to illustrate LIFO policypackage main import \"fmt\" // Functionsfunc add(a1, a2 int) int { res := a1 + a2 fmt.Println(\"Result: \", res) return 0} // Main functionfunc main() { fmt.Println(\"Start\") // Multiple defer statements // Executes in LIFO order defer fmt.Println(\"End\") defer add(34, 56) defer add(10, 10)}",
"e": 2702,
"s": 2304,
"text": null
},
{
"code": null,
"e": 2710,
"s": 2702,
"text": "Output:"
},
{
"code": null,
"e": 2744,
"s": 2710,
"text": "Start\nResult: 20\nResult: 90\nEnd"
},
{
"code": null,
"e": 2764,
"s": 2746,
"text": "competing23invain"
},
{
"code": null,
"e": 2776,
"s": 2764,
"text": "Go-Keywords"
},
{
"code": null,
"e": 2783,
"s": 2776,
"text": "Golang"
},
{
"code": null,
"e": 2795,
"s": 2783,
"text": "Go Language"
},
{
"code": null,
"e": 2893,
"s": 2795,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2945,
"s": 2893,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 2991,
"s": 2945,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 3041,
"s": 2991,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 3092,
"s": 3041,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 3139,
"s": 3092,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 3151,
"s": 3139,
"text": "Golang Maps"
},
{
"code": null,
"e": 3177,
"s": 3151,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 3198,
"s": 3177,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3252,
"s": 3198,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
What is the difference between __init__ and __call__?
|
21 Apr, 2020
Dunder or magic methods in Python are the methods having two prefixes and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. In this article, we are going to see the difference between two such methods.
Note: For more information, refer to Dunder or magic methods in Python
This Python method is similar to a constructor in any other programming language. A constructor is a definition with the same name as the class and is invoked automatically when the object of that class is defined. A constructor initializes all the required entities of the program to make it more reliable.Similar to this definition __init__() works as a Python constructor it is invoked automatically when an object of the class is defined. It initializes the required members with default values provided. It can also be invoked with the values provided during the time of declaration of the object of the class.
EXAMPLE:
class A: def __init__(self, x): print("inside __init__()") self.y = x def __str__(self): print("inside __str__()") print("value of y:", str(self.y)) # declaration of instance of class Aa = A(3) # calling __str__() for object aa.__str__() # declaration of another instance # of class Ab = A(10) # calling __str__() for bb.__str__()
OUTPUT:
inside __init__()
inside __str__()
('value of y:', '3')
inside __init__()
inside __str__()
('value of y:', '10')
Before getting into application of __call__() we need to understand what a callable object is.A callable object is one which can be called like a function.In Python, __call__() is used to resolve the code associated with a callable object. Any object can be converted to a callable object just by writing it in a function call format. An object of that kind invokes the __call__() method and executes the code associated with it. This doesn’t make the object not to work like a normal one. The object can be used as a normal is used.One thing to keep in mind is the object is itself used as a function, so syntax should be right.
EXAMPLE:
class A: def __init__(self, x): print("inside __init__()") self.y = x def __str__(self): print("inside __str__()") print("value of y:", str(self.y)) def __call__(self): res = 0 print("inside __call__()") print("adding 2 to the value of y") res = self.y + 2 return res # declaration of instance of class Aa = A(3) # calling __str__() for aa.__str__() # calling __call__() for a r = a()print(r) # declaration of another instance# of class Ab = A(10) # calling __str__() for bb.__str__() # calling __call__() for br = b()print(r)
OUTPUT:
inside __init__()
inside __str__()
('value of y:', '3')
inside __call__()
adding 2 to the value of y
5
inside __init__()
inside __str__()
('value of y:', '10')
inside __call__()
adding 2 to the value of y
12
python-oop-concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 395,
"s": 28,
"text": "Dunder or magic methods in Python are the methods having two prefixes and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading. Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc. In this article, we are going to see the difference between two such methods."
},
{
"code": null,
"e": 466,
"s": 395,
"text": "Note: For more information, refer to Dunder or magic methods in Python"
},
{
"code": null,
"e": 1082,
"s": 466,
"text": "This Python method is similar to a constructor in any other programming language. A constructor is a definition with the same name as the class and is invoked automatically when the object of that class is defined. A constructor initializes all the required entities of the program to make it more reliable.Similar to this definition __init__() works as a Python constructor it is invoked automatically when an object of the class is defined. It initializes the required members with default values provided. It can also be invoked with the values provided during the time of declaration of the object of the class."
},
{
"code": null,
"e": 1091,
"s": 1082,
"text": "EXAMPLE:"
},
{
"code": "class A: def __init__(self, x): print(\"inside __init__()\") self.y = x def __str__(self): print(\"inside __str__()\") print(\"value of y:\", str(self.y)) # declaration of instance of class Aa = A(3) # calling __str__() for object aa.__str__() # declaration of another instance # of class Ab = A(10) # calling __str__() for bb.__str__()",
"e": 1462,
"s": 1091,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "OUTPUT:"
},
{
"code": null,
"e": 1584,
"s": 1470,
"text": "inside __init__()\ninside __str__()\n('value of y:', '3')\ninside __init__()\ninside __str__()\n('value of y:', '10')\n"
},
{
"code": null,
"e": 2214,
"s": 1584,
"text": "Before getting into application of __call__() we need to understand what a callable object is.A callable object is one which can be called like a function.In Python, __call__() is used to resolve the code associated with a callable object. Any object can be converted to a callable object just by writing it in a function call format. An object of that kind invokes the __call__() method and executes the code associated with it. This doesn’t make the object not to work like a normal one. The object can be used as a normal is used.One thing to keep in mind is the object is itself used as a function, so syntax should be right."
},
{
"code": null,
"e": 2223,
"s": 2214,
"text": "EXAMPLE:"
},
{
"code": "class A: def __init__(self, x): print(\"inside __init__()\") self.y = x def __str__(self): print(\"inside __str__()\") print(\"value of y:\", str(self.y)) def __call__(self): res = 0 print(\"inside __call__()\") print(\"adding 2 to the value of y\") res = self.y + 2 return res # declaration of instance of class Aa = A(3) # calling __str__() for aa.__str__() # calling __call__() for a r = a()print(r) # declaration of another instance# of class Ab = A(10) # calling __str__() for bb.__str__() # calling __call__() for br = b()print(r)",
"e": 2848,
"s": 2223,
"text": null
},
{
"code": null,
"e": 2856,
"s": 2848,
"text": "OUTPUT:"
},
{
"code": null,
"e": 3064,
"s": 2856,
"text": "inside __init__()\ninside __str__()\n('value of y:', '3')\ninside __call__()\nadding 2 to the value of y\n5\ninside __init__()\ninside __str__()\n('value of y:', '10')\ninside __call__()\nadding 2 to the value of y\n12"
},
{
"code": null,
"e": 3084,
"s": 3064,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 3091,
"s": 3084,
"text": "Python"
},
{
"code": null,
"e": 3189,
"s": 3091,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3221,
"s": 3189,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3248,
"s": 3221,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3269,
"s": 3248,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3292,
"s": 3269,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3348,
"s": 3292,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3379,
"s": 3348,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3421,
"s": 3379,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3463,
"s": 3421,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3502,
"s": 3463,
"text": "Python | Get unique values from a list"
}
] |
Lodash _.split() Method
|
30 Sep, 2020
The Lodash _.split() method splits the given string by the given separator and up to the given limit length.
Syntax:
_.split( string, separator, limit )
Parameters: This method accepts three parameters as mentioned above and described below:
string: The string to split.
separator: The separator by which string is to be split.
limit: The length to truncate results.
Return Value: This method returns an array.
Example 1:
Javascript
// Defining Lodash variable const _ = require('lodash'); var str = "Geeks-for-Geeks"; // Using _.replace() methodconsole.log(_.split(str, '-' ))
Output:
[ 'Geeks', 'for', 'Geeks' ]
Example 2: The array limited to size of 1.
Javascript
// Defining Lodash variable const _ = require('lodash'); var str = "Geeks-for-Geeks"; // Using _.replace() methodconsole.log(_.split(str, '-', 1 ))
Output:
[ 'Geeks' ]
Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using npm install lodash.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Sep, 2020"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "The Lodash _.split() method splits the given string by the given separator and up to the given limit length."
},
{
"code": null,
"e": 145,
"s": 137,
"text": "Syntax:"
},
{
"code": null,
"e": 182,
"s": 145,
"text": "_.split( string, separator, limit )\n"
},
{
"code": null,
"e": 271,
"s": 182,
"text": "Parameters: This method accepts three parameters as mentioned above and described below:"
},
{
"code": null,
"e": 300,
"s": 271,
"text": "string: The string to split."
},
{
"code": null,
"e": 357,
"s": 300,
"text": "separator: The separator by which string is to be split."
},
{
"code": null,
"e": 396,
"s": 357,
"text": "limit: The length to truncate results."
},
{
"code": null,
"e": 440,
"s": 396,
"text": "Return Value: This method returns an array."
},
{
"code": null,
"e": 451,
"s": 440,
"text": "Example 1:"
},
{
"code": null,
"e": 462,
"s": 451,
"text": "Javascript"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var str = \"Geeks-for-Geeks\"; // Using _.replace() methodconsole.log(_.split(str, '-' ))",
"e": 610,
"s": 462,
"text": null
},
{
"code": null,
"e": 618,
"s": 610,
"text": "Output:"
},
{
"code": null,
"e": 647,
"s": 618,
"text": "[ 'Geeks', 'for', 'Geeks' ]\n"
},
{
"code": null,
"e": 690,
"s": 647,
"text": "Example 2: The array limited to size of 1."
},
{
"code": null,
"e": 701,
"s": 690,
"text": "Javascript"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var str = \"Geeks-for-Geeks\"; // Using _.replace() methodconsole.log(_.split(str, '-', 1 ))",
"e": 852,
"s": 701,
"text": null
},
{
"code": null,
"e": 860,
"s": 852,
"text": "Output:"
},
{
"code": null,
"e": 873,
"s": 860,
"text": "[ 'Geeks' ]\n"
},
{
"code": null,
"e": 1021,
"s": 873,
"text": "Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using npm install lodash."
},
{
"code": null,
"e": 1039,
"s": 1021,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1050,
"s": 1039,
"text": "JavaScript"
},
{
"code": null,
"e": 1067,
"s": 1050,
"text": "Web Technologies"
}
] |
XQuery - max Function
|
The max function is used to get the maximum valued item present in a sequence.
max($seq as item()*)
$seq − provided sequence. A sequence can contain 0 or more items.
$seq − provided sequence. A sequence can contain 0 or more items.
let $items := (1,2,3,4,5,6)
let $max := max($items)
return
<result>
<max>{$max}</max>
</result>
<result>
<max>6</max>
</result>
In order to test the above-mentioned functionality, replace the contents of books.xqy (mentioned in Environment Setup chapter) with the above XQuery expression and execute the XQueryTester java program to verify the result.
|
[
{
"code": null,
"e": 2085,
"s": 2006,
"text": "The max function is used to get the maximum valued item present in a sequence."
},
{
"code": null,
"e": 2106,
"s": 2085,
"text": "max($seq as item()*)"
},
{
"code": null,
"e": 2172,
"s": 2106,
"text": "$seq − provided sequence. A sequence can contain 0 or more items."
},
{
"code": null,
"e": 2238,
"s": 2172,
"text": "$seq − provided sequence. A sequence can contain 0 or more items."
},
{
"code": null,
"e": 2351,
"s": 2238,
"text": "let $items := (1,2,3,4,5,6)\nlet $max := max($items)\nreturn\n <result>\n <max>{$max}</max> \n </result>"
},
{
"code": null,
"e": 2389,
"s": 2351,
"text": "<result>\n <max>6</max> \n</result>\n"
}
] |
Python | Pandas df.size, df.shape and df.ndim
|
03 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas .size, .shape and .ndim are used to return size, shape and dimensions of data frames and series.
Syntax: dataframe.sizeReturn : Returns size of dataframe/series which is equivalent to total number of elements. That is rows x columns.Syntax: dataframe.shapeReturn : Returns tuple of shape (Rows, columns) of dataframe/seriesSyntax: dataframe.ndimReturn : Returns dimension of dataframe/series. 1 for one dimension (series), 2 for two dimension (dataframe)
To download the data set used in following example, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example:In this example, the output from size and shape is stored first. Since .size returns total number of elements, it is compared by multiplying rows and columns returned by the shape method. After that dimension of Dataframe and series is also checked using .ndim
# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dataframe.sizesize = data.size # dataframe.shapeshape = data.shape # dataframe.ndimdf_ndim = data.ndim # series.ndimseries_ndim = data["Salary"].ndim # printing size and shapeprint("Size = {}\nShape ={}\nShape[0] x Shape[1] = {}".format(size, shape, shape[0]*shape[1])) # printing ndimprint("ndim of dataframe = {}\nndim of series ={}".format(df_ndim, series_ndim))
Output:
Size = 4122
Shape=(458, 9)
Shape[0] x Shape[1] = 4122
ndim of dataframe = 2
ndim of series=1
As it can be seen, rows x columns from .shape is equal to the value returned by .sizeAlso, ndim for dataframe was 2 and series is 1 which is true for all kind of dataframes and series.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 346,
"s": 242,
"text": "Pandas .size, .shape and .ndim are used to return size, shape and dimensions of data frames and series."
},
{
"code": null,
"e": 704,
"s": 346,
"text": "Syntax: dataframe.sizeReturn : Returns size of dataframe/series which is equivalent to total number of elements. That is rows x columns.Syntax: dataframe.shapeReturn : Returns tuple of shape (Rows, columns) of dataframe/seriesSyntax: dataframe.ndimReturn : Returns dimension of dataframe/series. 1 for one dimension (series), 2 for two dimension (dataframe)"
},
{
"code": null,
"e": 768,
"s": 704,
"text": "To download the data set used in following example, click here."
},
{
"code": null,
"e": 915,
"s": 768,
"text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 1184,
"s": 915,
"text": "Example:In this example, the output from size and shape is stored first. Since .size returns total number of elements, it is compared by multiplying rows and columns returned by the shape method. After that dimension of Dataframe and series is also checked using .ndim"
},
{
"code": "# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dataframe.sizesize = data.size # dataframe.shapeshape = data.shape # dataframe.ndimdf_ndim = data.ndim # series.ndimseries_ndim = data[\"Salary\"].ndim # printing size and shapeprint(\"Size = {}\\nShape ={}\\nShape[0] x Shape[1] = {}\".format(size, shape, shape[0]*shape[1])) # printing ndimprint(\"ndim of dataframe = {}\\nndim of series ={}\".format(df_ndim, series_ndim))",
"e": 1704,
"s": 1184,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Output:"
},
{
"code": null,
"e": 1805,
"s": 1712,
"text": "Size = 4122\nShape=(458, 9)\nShape[0] x Shape[1] = 4122\nndim of dataframe = 2\nndim of series=1"
},
{
"code": null,
"e": 1990,
"s": 1805,
"text": "As it can be seen, rows x columns from .shape is equal to the value returned by .sizeAlso, ndim for dataframe was 2 and series is 1 which is true for all kind of dataframes and series."
},
{
"code": null,
"e": 2014,
"s": 1990,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2046,
"s": 2014,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2060,
"s": 2046,
"text": "Python-pandas"
},
{
"code": null,
"e": 2067,
"s": 2060,
"text": "Python"
},
{
"code": null,
"e": 2165,
"s": 2067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2183,
"s": 2165,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2225,
"s": 2183,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2247,
"s": 2225,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2282,
"s": 2247,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2308,
"s": 2282,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2340,
"s": 2308,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2369,
"s": 2340,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2396,
"s": 2369,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2426,
"s": 2396,
"text": "Iterate over a list in Python"
}
] |
Remove duplicate elements in Java with HashSet
|
Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements.
Let us declare a list and add elements −
List < Integer > list1 = new ArrayList < Integer > ();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(400);
list1.add(500);
list1.add(600);
list1.add(600);
list1.add(700);
list1.add(400);
list1.add(500);
Now, use the HashSet implementation and convert the list to HashSet to remove duplicates −
HashSet<Integer>set = new HashSet<Integer>(list1);
List<Integer>list2 = new ArrayList<Integer>(set);
Above, the list2 will now have only unique elements.
Live Demo
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Demo {
public static void main(String[] argv) {
List<Integer>list1 = new ArrayList<Integer>();
list1.add(100);
list1.add(200);
list1.add(300);
list1.add(400);
list1.add(400);
list1.add(500);
list1.add(600);
list1.add(600);
list1.add(700);
list1.add(400);
list1.add(500);
HashSet<Integer>set = new HashSet<Integer>(list1);
List<Integer>list2 = new ArrayList<Integer>(set);
System.out.println("List after removing duplicate elements:");
for (Object ob: list2)
System.out.println(ob);
}
}
List after removing duplicate elements:
400
100
500
200
600
300
700
|
[
{
"code": null,
"e": 1297,
"s": 1187,
"text": "Set implementations in Java has only unique elements. Therefore, it can be used to remove duplicate elements."
},
{
"code": null,
"e": 1338,
"s": 1297,
"text": "Let us declare a list and add elements −"
},
{
"code": null,
"e": 1569,
"s": 1338,
"text": "List < Integer > list1 = new ArrayList < Integer > ();\nlist1.add(100);\nlist1.add(200);\nlist1.add(300);\nlist1.add(400);\nlist1.add(400);\nlist1.add(500);\nlist1.add(600);\nlist1.add(600);\nlist1.add(700);\nlist1.add(400);\nlist1.add(500);"
},
{
"code": null,
"e": 1660,
"s": 1569,
"text": "Now, use the HashSet implementation and convert the list to HashSet to remove duplicates −"
},
{
"code": null,
"e": 1761,
"s": 1660,
"text": "HashSet<Integer>set = new HashSet<Integer>(list1);\nList<Integer>list2 = new ArrayList<Integer>(set);"
},
{
"code": null,
"e": 1814,
"s": 1761,
"text": "Above, the list2 will now have only unique elements."
},
{
"code": null,
"e": 1825,
"s": 1814,
"text": " Live Demo"
},
{
"code": null,
"e": 2512,
"s": 1825,
"text": "import java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] argv) {\n List<Integer>list1 = new ArrayList<Integer>();\n list1.add(100);\n list1.add(200);\n list1.add(300);\n list1.add(400);\n list1.add(400);\n list1.add(500);\n list1.add(600);\n list1.add(600);\n list1.add(700);\n list1.add(400);\n list1.add(500);\n HashSet<Integer>set = new HashSet<Integer>(list1);\n List<Integer>list2 = new ArrayList<Integer>(set);\n System.out.println(\"List after removing duplicate elements:\");\n for (Object ob: list2)\n System.out.println(ob);\n }\n}"
},
{
"code": null,
"e": 2580,
"s": 2512,
"text": "List after removing duplicate elements:\n400\n100\n500\n200\n600\n300\n700"
}
] |
push_back() vs emplace_back() in C++ STL Vectors
|
03 Jun, 2022
In C++, vectors are dynamic arrays, that can grow or shrink and their storage is handled by the container itself. There are two ways of inserting an element in a vector. They are push_back() and emplace_back(). In this article, we will discuss the difference between them.
This method is used to insert elements in a vector from the end of the container. As the flexibility in the size of the vector is dynamic, the size of the container also increased by 1 after inserting any new element.
Program 1:
C++
// C++ program to demonstrate the// push_back() method #include <iostream>#include <vector> using namespace std; // Classclass GFG { public: int x; // Parameterized Constructor GFG(int x) : x(x) { cout << "Constructor=>" << "x:" << x << endl; } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x) { cout << "Copied=>" << "x:" << x << endl; } ~GFG() { cout << "destructor=>" << "x:" << x << endl; }}; // Driver Codeint main(){ // Vector of object of GFG class // is created vector<GFG> vertices; cout << "length of vertices:" << vertices.size() << endl; // Inserting elements in the object // created using push_back() method cout << endl; // Custom input entries vertices.push_back(GFG(1)); cout << endl; vertices.push_back(GFG(11)); cout << endl; vertices.push_back(GFG(21)); cout << endl; return 0;}
length of vertices:0
Constructor=>x:1
Copied=>x:1
destructor=>x:1
Constructor=>x:11
Copied=>x:11
Copied=>x:1
destructor=>x:1
destructor=>x:11
Constructor=>x:21
Copied=>x:21
Copied=>x:1
Copied=>x:11
destructor=>x:1
destructor=>x:11
destructor=>x:21
destructor=>x:1
destructor=>x:11
destructor=>x:21
Explanation:
Everytime push_back a value to a vector , cpp will create a new vector which copied the new value from parameter and all values in the old vector
In the main function, a vector(vector1) of class GFG is created of size is 0. When using GFG(int) as parameter, it is created using a parameterized constructor, and since the vector is of type GFG, the object is passed to the “GFG” copy constructor, hence “Copied” is printed once.
When the second GFG value has been pushed_back, a new vector(vector2) will be created with greater size and Copied the GFG(11) into it. And then all the values in the old vector which refers to the vector1{1} Copied to the Vector2, so the “Copied” is printed twice when the second GFG has been pushed_back.
Similarly, when the third object is to be created, a new vector of greater size is allocated in memory, the first element is copied, then the second element is copied, and then the third element is copied. Hence, “Copied” is printed thrice as the copy constructor is called thrice, once for each element inserted.
However, if the size of the vector is fixed, then before inserting any element, the number of times “Copied” will be printed is one. This is because as the required size is declared, no re-copying of elements takes place upon each insertion.
Note: reserve() is used instead of using “vector<Point> vertices(3)”, as the below syntax sometimes doesn’t work because there is no default constructor defined in the class.
"vector<GFG> vertices(3);”
Program 2:The cost due to the copying of elements is high. Below is the program to optimize the usage of C++ Vectors to reduce the cost of copying elements:
C++
// C++ Program to optimize the usage// of C++ Vectors to reduce the cost// of copying elements with the// reserve() method #include <iostream>#include <vector>using namespace std; // Classclass GFG { public: float x, y; // Parameterized Constructor GFG(float x, float y) : x(x), y(y) { } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x), y(GFG.y) { cout << "Copied" << endl; }}; // Driver Codeint main(){ // Create object of vector in // the main() method vector<GFG> vertices; // Reserve three elements using // reserve() vertices.reserve(3); // Add elements to the vector // object vertices.push_back(GFG(1, 2)); cout << endl; vertices.push_back(GFG(4, 5)); cout << endl; vertices.push_back(GFG(7, 8)); cout << endl; return 0;}
Copied
Copied
Copied
This method is used instead of creating the object using parameterized constructor and allocating it into a different memory, then passing it to the copy constructor, which will insert it into the vector. This function can directly insert the object without calling the copy constructor. Below is the program to illustrate the same:
Program 3:
C++
// C++ Program to illustrate the high// cost of copying the elements in// vector in STL #include <iostream>#include <vector>using namespace std; // Classclass GFG { public: float x, y; // Parameterized Constructor GFG(float x, float y) : x(x), y(y) { } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x), y(GFG.y) { cout << "Copied" << endl; }}; // Driver Codeint main(){ // Create an object of vector // class object vector<GFG> vertices; // Reserve the elements in the // vector using reserve() method vertices.reserve(3); // Add element to vector object // using emplace_back() method vertices.emplace_back(1, 2); cout << endl; vertices.emplace_back(4, 5); cout << endl; vertices.emplace_back(7, 8); cout << endl; return 0;}
Explanation: In the above program nothing is printed as the copying of the constructor doesn’t take place while using the emplace_back() function.
Let us see the difference between in a tabular form -:
Its syntax is :
push_back(value_to_insert)
Its syntax is -:
emplace_back(value_to_insert)
anikaseth98
nilop
dingisooah
mayank007rawa
cpp-containers-library
cpp-vector
STL
C++
C++ Programs
Difference Between
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Writing First C++ Program - Hello World Example
Basic Input / Output in C++
Functions that cannot be overloaded in C++
Switch Statement in C/C++
Polymorphism in C++
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
Sorting a Map by value in C++ STL
C++ program for hashing with chaining
Passing a function as a parameter in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 327,
"s": 54,
"text": "In C++, vectors are dynamic arrays, that can grow or shrink and their storage is handled by the container itself. There are two ways of inserting an element in a vector. They are push_back() and emplace_back(). In this article, we will discuss the difference between them."
},
{
"code": null,
"e": 545,
"s": 327,
"text": "This method is used to insert elements in a vector from the end of the container. As the flexibility in the size of the vector is dynamic, the size of the container also increased by 1 after inserting any new element."
},
{
"code": null,
"e": 556,
"s": 545,
"text": "Program 1:"
},
{
"code": null,
"e": 560,
"s": 556,
"text": "C++"
},
{
"code": "// C++ program to demonstrate the// push_back() method #include <iostream>#include <vector> using namespace std; // Classclass GFG { public: int x; // Parameterized Constructor GFG(int x) : x(x) { cout << \"Constructor=>\" << \"x:\" << x << endl; } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x) { cout << \"Copied=>\" << \"x:\" << x << endl; } ~GFG() { cout << \"destructor=>\" << \"x:\" << x << endl; }}; // Driver Codeint main(){ // Vector of object of GFG class // is created vector<GFG> vertices; cout << \"length of vertices:\" << vertices.size() << endl; // Inserting elements in the object // created using push_back() method cout << endl; // Custom input entries vertices.push_back(GFG(1)); cout << endl; vertices.push_back(GFG(11)); cout << endl; vertices.push_back(GFG(21)); cout << endl; return 0;}",
"e": 1528,
"s": 560,
"text": null
},
{
"code": null,
"e": 1830,
"s": 1528,
"text": "length of vertices:0\n\nConstructor=>x:1\nCopied=>x:1\ndestructor=>x:1\n\nConstructor=>x:11\nCopied=>x:11\nCopied=>x:1\ndestructor=>x:1\ndestructor=>x:11\n\nConstructor=>x:21\nCopied=>x:21\nCopied=>x:1\nCopied=>x:11\ndestructor=>x:1\ndestructor=>x:11\ndestructor=>x:21\n\ndestructor=>x:1\ndestructor=>x:11\ndestructor=>x:21"
},
{
"code": null,
"e": 1843,
"s": 1830,
"text": "Explanation:"
},
{
"code": null,
"e": 1990,
"s": 1843,
"text": "Everytime push_back a value to a vector , cpp will create a new vector which copied the new value from parameter and all values in the old vector "
},
{
"code": null,
"e": 2273,
"s": 1990,
"text": "In the main function, a vector(vector1) of class GFG is created of size is 0. When using GFG(int) as parameter, it is created using a parameterized constructor, and since the vector is of type GFG, the object is passed to the “GFG” copy constructor, hence “Copied” is printed once. "
},
{
"code": null,
"e": 2580,
"s": 2273,
"text": "When the second GFG value has been pushed_back, a new vector(vector2) will be created with greater size and Copied the GFG(11) into it. And then all the values in the old vector which refers to the vector1{1} Copied to the Vector2, so the “Copied” is printed twice when the second GFG has been pushed_back."
},
{
"code": null,
"e": 2894,
"s": 2580,
"text": "Similarly, when the third object is to be created, a new vector of greater size is allocated in memory, the first element is copied, then the second element is copied, and then the third element is copied. Hence, “Copied” is printed thrice as the copy constructor is called thrice, once for each element inserted."
},
{
"code": null,
"e": 3136,
"s": 2894,
"text": "However, if the size of the vector is fixed, then before inserting any element, the number of times “Copied” will be printed is one. This is because as the required size is declared, no re-copying of elements takes place upon each insertion."
},
{
"code": null,
"e": 3311,
"s": 3136,
"text": "Note: reserve() is used instead of using “vector<Point> vertices(3)”, as the below syntax sometimes doesn’t work because there is no default constructor defined in the class."
},
{
"code": null,
"e": 3338,
"s": 3311,
"text": "\"vector<GFG> vertices(3);”"
},
{
"code": null,
"e": 3495,
"s": 3338,
"text": "Program 2:The cost due to the copying of elements is high. Below is the program to optimize the usage of C++ Vectors to reduce the cost of copying elements:"
},
{
"code": null,
"e": 3499,
"s": 3495,
"text": "C++"
},
{
"code": "// C++ Program to optimize the usage// of C++ Vectors to reduce the cost// of copying elements with the// reserve() method #include <iostream>#include <vector>using namespace std; // Classclass GFG { public: float x, y; // Parameterized Constructor GFG(float x, float y) : x(x), y(y) { } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x), y(GFG.y) { cout << \"Copied\" << endl; }}; // Driver Codeint main(){ // Create object of vector in // the main() method vector<GFG> vertices; // Reserve three elements using // reserve() vertices.reserve(3); // Add elements to the vector // object vertices.push_back(GFG(1, 2)); cout << endl; vertices.push_back(GFG(4, 5)); cout << endl; vertices.push_back(GFG(7, 8)); cout << endl; return 0;}",
"e": 4331,
"s": 3499,
"text": null
},
{
"code": null,
"e": 4354,
"s": 4331,
"text": "Copied\n\nCopied\n\nCopied"
},
{
"code": null,
"e": 4689,
"s": 4356,
"text": "This method is used instead of creating the object using parameterized constructor and allocating it into a different memory, then passing it to the copy constructor, which will insert it into the vector. This function can directly insert the object without calling the copy constructor. Below is the program to illustrate the same:"
},
{
"code": null,
"e": 4700,
"s": 4689,
"text": "Program 3:"
},
{
"code": null,
"e": 4704,
"s": 4700,
"text": "C++"
},
{
"code": "// C++ Program to illustrate the high// cost of copying the elements in// vector in STL #include <iostream>#include <vector>using namespace std; // Classclass GFG { public: float x, y; // Parameterized Constructor GFG(float x, float y) : x(x), y(y) { } // Copy Constructor GFG(const GFG& GFG) : x(GFG.x), y(GFG.y) { cout << \"Copied\" << endl; }}; // Driver Codeint main(){ // Create an object of vector // class object vector<GFG> vertices; // Reserve the elements in the // vector using reserve() method vertices.reserve(3); // Add element to vector object // using emplace_back() method vertices.emplace_back(1, 2); cout << endl; vertices.emplace_back(4, 5); cout << endl; vertices.emplace_back(7, 8); cout << endl; return 0;}",
"e": 5532,
"s": 4704,
"text": null
},
{
"code": null,
"e": 5684,
"s": 5536,
"text": "Explanation: In the above program nothing is printed as the copying of the constructor doesn’t take place while using the emplace_back() function. "
},
{
"code": null,
"e": 5739,
"s": 5684,
"text": "Let us see the difference between in a tabular form -:"
},
{
"code": null,
"e": 5755,
"s": 5739,
"text": "Its syntax is :"
},
{
"code": null,
"e": 5782,
"s": 5755,
"text": "push_back(value_to_insert)"
},
{
"code": null,
"e": 5799,
"s": 5782,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 5829,
"s": 5799,
"text": "emplace_back(value_to_insert)"
},
{
"code": null,
"e": 5841,
"s": 5829,
"text": "anikaseth98"
},
{
"code": null,
"e": 5847,
"s": 5841,
"text": "nilop"
},
{
"code": null,
"e": 5858,
"s": 5847,
"text": "dingisooah"
},
{
"code": null,
"e": 5872,
"s": 5858,
"text": "mayank007rawa"
},
{
"code": null,
"e": 5895,
"s": 5872,
"text": "cpp-containers-library"
},
{
"code": null,
"e": 5906,
"s": 5895,
"text": "cpp-vector"
},
{
"code": null,
"e": 5910,
"s": 5906,
"text": "STL"
},
{
"code": null,
"e": 5914,
"s": 5910,
"text": "C++"
},
{
"code": null,
"e": 5927,
"s": 5914,
"text": "C++ Programs"
},
{
"code": null,
"e": 5946,
"s": 5927,
"text": "Difference Between"
},
{
"code": null,
"e": 5950,
"s": 5946,
"text": "STL"
},
{
"code": null,
"e": 5954,
"s": 5950,
"text": "CPP"
},
{
"code": null,
"e": 6052,
"s": 5954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6100,
"s": 6052,
"text": "Writing First C++ Program - Hello World Example"
},
{
"code": null,
"e": 6128,
"s": 6100,
"text": "Basic Input / Output in C++"
},
{
"code": null,
"e": 6171,
"s": 6128,
"text": "Functions that cannot be overloaded in C++"
},
{
"code": null,
"e": 6197,
"s": 6171,
"text": "Switch Statement in C/C++"
},
{
"code": null,
"e": 6217,
"s": 6197,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 6252,
"s": 6217,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 6311,
"s": 6252,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 6345,
"s": 6311,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 6383,
"s": 6345,
"text": "C++ program for hashing with chaining"
}
] |
How to Save Pandas Dataframe as gzip/zip File? - GeeksforGeeks
|
26 Nov, 2020
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users.
The to_pickle() method in Pandas is used to pickle (serialize) the given object into the file. This method utilizes the syntax as given below :
Syntax:
DataFrame.to_pickle(self, path,
compression='infer',
protocol=4)
This method supports compressions like zip, gzip, bz2, and xz. In the given examples, you’ll see how to convert a DataFrame into zip, and gzip.
Example 1: Save Pandas Dataframe as zip File
Python3
# importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67}, 'Name': {0: 'Ajay', 1: 'Deep', 2: 'Deepanshi', 3: 'Mira', 4: 'Yash'}, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file# by default, compression type infers from the file extension in specified path.# file will be created in the given pathdata.to_pickle('file.zip')
Output:
Example 2: Save Pandas Dataframe as gzip File.
Python3
# importing packagesimport pandas as pd # dictionary of datadct = {"C1": range(5), "C2": range(5, 10)} # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file# we can also select compression type# file will be created in the given pathdata.to_pickle('file.gzip')
Output:
In order to read the created files, you’ll need to use read_pickle() method. This method utilizes the syntax as given below:
pandas.read_pickle(filepath_or_buffer,
compression='infer')
Example 1: Reading zip file
Python3
# reading from the zip filepd.read_pickle('file.zip')
Output:
Example 2: Reading gzip File.
Python3
# reading from gzip filepd.read_pickle('file.gzip')
Output:
From the above two examples, we can see both of the compressed files can be read by the read_pickle() method without any changes except for the file extension.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Python math function | sqrt()
Python | Output Formatting
Python - Pandas dataframe.append()
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 25869,
"s": 25537,
"text": "Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. "
},
{
"code": null,
"e": 26013,
"s": 25869,
"text": "The to_pickle() method in Pandas is used to pickle (serialize) the given object into the file. This method utilizes the syntax as given below :"
},
{
"code": null,
"e": 26021,
"s": 26013,
"text": "Syntax:"
},
{
"code": null,
"e": 26125,
"s": 26021,
"text": "DataFrame.to_pickle(self, path,\n compression='infer',\n protocol=4)\n"
},
{
"code": null,
"e": 26269,
"s": 26125,
"text": "This method supports compressions like zip, gzip, bz2, and xz. In the given examples, you’ll see how to convert a DataFrame into zip, and gzip."
},
{
"code": null,
"e": 26314,
"s": 26269,
"text": "Example 1: Save Pandas Dataframe as zip File"
},
{
"code": null,
"e": 26322,
"s": 26314,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas as pd # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12, 3: 13, 4: 67}, 'Name': {0: 'Ajay', 1: 'Deep', 2: 'Deepanshi', 3: 'Mira', 4: 'Yash'}, 'Marks': {0: 89, 1: 97, 2: 45, 3: 78, 4: 56}, 'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C', 4: 'E'} } # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file# by default, compression type infers from the file extension in specified path.# file will be created in the given pathdata.to_pickle('file.zip')",
"e": 26972,
"s": 26322,
"text": null
},
{
"code": null,
"e": 26980,
"s": 26972,
"text": "Output:"
},
{
"code": null,
"e": 27027,
"s": 26980,
"text": "Example 2: Save Pandas Dataframe as gzip File."
},
{
"code": null,
"e": 27035,
"s": 27027,
"text": "Python3"
},
{
"code": "# importing packagesimport pandas as pd # dictionary of datadct = {\"C1\": range(5), \"C2\": range(5, 10)} # forming dataframe and printingdata = pd.DataFrame(dct)print(data) # using to_pickle function to form file# we can also select compression type# file will be created in the given pathdata.to_pickle('file.gzip')",
"e": 27353,
"s": 27035,
"text": null
},
{
"code": null,
"e": 27361,
"s": 27353,
"text": "Output:"
},
{
"code": null,
"e": 27486,
"s": 27361,
"text": "In order to read the created files, you’ll need to use read_pickle() method. This method utilizes the syntax as given below:"
},
{
"code": null,
"e": 27564,
"s": 27486,
"text": "pandas.read_pickle(filepath_or_buffer, \n compression='infer')\n"
},
{
"code": null,
"e": 27592,
"s": 27564,
"text": "Example 1: Reading zip file"
},
{
"code": null,
"e": 27600,
"s": 27592,
"text": "Python3"
},
{
"code": "# reading from the zip filepd.read_pickle('file.zip')",
"e": 27654,
"s": 27600,
"text": null
},
{
"code": null,
"e": 27662,
"s": 27654,
"text": "Output:"
},
{
"code": null,
"e": 27692,
"s": 27662,
"text": "Example 2: Reading gzip File."
},
{
"code": null,
"e": 27700,
"s": 27692,
"text": "Python3"
},
{
"code": "# reading from gzip filepd.read_pickle('file.gzip')",
"e": 27752,
"s": 27700,
"text": null
},
{
"code": null,
"e": 27760,
"s": 27752,
"text": "Output:"
},
{
"code": null,
"e": 27920,
"s": 27760,
"text": "From the above two examples, we can see both of the compressed files can be read by the read_pickle() method without any changes except for the file extension."
},
{
"code": null,
"e": 27944,
"s": 27920,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27958,
"s": 27944,
"text": "Python-pandas"
},
{
"code": null,
"e": 27965,
"s": 27958,
"text": "Python"
},
{
"code": null,
"e": 28063,
"s": 27965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28085,
"s": 28063,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28117,
"s": 28085,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28133,
"s": 28117,
"text": "Deque in Python"
},
{
"code": null,
"e": 28156,
"s": 28133,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 28198,
"s": 28156,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28228,
"s": 28198,
"text": "Python math function | sqrt()"
},
{
"code": null,
"e": 28255,
"s": 28228,
"text": "Python | Output Formatting"
},
{
"code": null,
"e": 28290,
"s": 28255,
"text": "Python - Pandas dataframe.append()"
},
{
"code": null,
"e": 28346,
"s": 28290,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Longest common subsequence with permutations allowed - GeeksforGeeks
|
20 Jul, 2021
Given two strings in lowercase, find the longest string whose permutations are subsequences of given two strings. The output longest string must be sorted.Examples:
Input : str1 = "pink", str2 = "kite"
Output : "ik"
The string "ik" is the longest sorted string
whose one permutation "ik" is subsequence of
"pink" and another permutation "ki" is
subsequence of "kite".
Input : str1 = "working", str2 = "women"
Output : "now"
Input : str1 = "geeks" , str2 = "cake"
Output : "ek"
Input : str1 = "aaaa" , str2 = "baba"
Output : "aa"
The idea is to count characters in both strings.
calculate frequency of characters for each string and store them in their respective count arrays, say count1[] for str1 and count2[] for str2.Now we have count arrays for 26 characters. So traverse count1[] and for any index ‘i’ append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times.Since we traverse count array in ascending order, our final string characters will be in sorted order.
calculate frequency of characters for each string and store them in their respective count arrays, say count1[] for str1 and count2[] for str2.
Now we have count arrays for 26 characters. So traverse count1[] and for any index ‘i’ append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times.
Since we traverse count array in ascending order, our final string characters will be in sorted order.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find LCS with permutations allowed#include<bits/stdc++.h>using namespace std; // Function to calculate longest string// str1 --> first string// str2 --> second string// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest string whose// permutations are sub-sequence of given two stringsvoid longestString(string str1, string str2){ int count1[26] = {0}, count2[26]= {0}; // calculate frequency of characters for (int i=0; i<str1.length(); i++) count1[str1[i]-'a']++; for (int i=0; i<str2.length(); i++) count2[str2[i]-'a']++; // Now traverse hash array string result; for (int i=0; i<26; i++) // append character ('a'+i) in resultant // string 'result' by min(count1[i],count2i]) // times for (int j=1; j<=min(count1[i],count2[i]); j++) result.push_back('a' + i); cout << result;} // Driver program to run the caseint main(){ string str1 = "geeks", str2 = "cake"; longestString(str1, str2); return 0;}
//Java program to find LCS with permutations allowed class GFG { // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of given two strings static void longestString(String str1, String str2) { int count1[] = new int[26], count2[] = new int[26]; // calculate frequency of characters for (int i = 0; i < str1.length(); i++) { count1[str1.charAt(i) - 'a']++; } for (int i = 0; i < str2.length(); i++) { count2[str2.charAt(i) - 'a']++; } // Now traverse hash array String result = ""; for (int i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (int j = 1; j <= Math.min(count1[i], count2[i]); j++) { result += (char)('a' + i); } } System.out.println(result); } // Driver program to run the case public static void main(String[] args) { String str1 = "geeks", str2 = "cake"; longestString(str1, str2); }}/* This java code is contributed by 29AjayKumar*/
# Python 3 program to find LCS# with permutations allowed # Function to calculate longest string# str1 --> first string# str2 --> second string# count1[] --> hash array to calculate frequency# of characters in str1# count[2] --> hash array to calculate frequency# of characters in str2# result --> resultant longest string whose# permutations are sub-sequence# of given two stringsdef longestString(str1, str2): count1 = [0] * 26 count2 = [0] * 26 # calculate frequency of characters for i in range( len(str1)): count1[ord(str1[i]) - ord('a')] += 1 for i in range(len(str2)): count2[ord(str2[i]) - ord('a')] += 1 # Now traverse hash array result = "" for i in range(26): # append character ('a'+i) in # resultant string 'result' by # min(count1[i],count2i]) times for j in range(1, min(count1[i], count2[i]) + 1): result = result + chr(ord('a') + i) print(result) # Driver Codeif __name__ == "__main__": str1 = "geeks" str2 = "cake" longestString(str1, str2) # This code is contributed by ita_c
// C# program to find LCS with// permutations allowedusing System; class GFG{ // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate// frequency of characters in str1// count[2] --> hash array to calculate// frequency of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of// given two stringsstatic void longestString(String str1, String str2){ int []count1 = new int[26]; int []count2 = new int[26]; // calculate frequency of characters for (int i = 0; i < str1.Length; i++) { count1[str1[i] - 'a']++; } for (int i = 0; i < str2.Length; i++) { count2[str2[i] - 'a']++; } // Now traverse hash array String result = ""; for (int i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (int j = 1; j <= Math.Min(count1[i], count2[i]); j++) { result += (char)('a' + i); } } Console.Write(result);} // Driver Codepublic static void Main(){ String str1 = "geeks", str2 = "cake"; longestString(str1, str2);}} // This code is contributed// by PrinciRaj1992
<?php// PHP program to find LCS with// permutations allowed // Function to calculate longest string// str1 --> first string// str2 --> second string// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest string whose// permutations are sub-sequence of given two stringsfunction longestString($str1, $str2){ $count1 = array_fill(0, 26, NULL); $count2 = array_fill(0, 26, NULL); // calculate frequency of characters for ($i = 0; $i < strlen($str1); $i++) $count1[ord($str1[$i]) - ord('a')]++; for ($i = 0; $i < strlen($str2); $i++) $count2[ord($str2[$i]) - ord('a')]++; // Now traverse hash array $result = ""; for ($i = 0; $i < 26; $i++) // append character ('a'+i) in resultant // string 'result' by min(count1[$i], // count2[$i]) times for ($j = 1; $j <= min($count1[$i], $count2[$i]); $j++) $result = $result.chr(ord('a') + $i); echo $result;} // Driver Code$str1 = "geeks";$str2 = "cake";longestString($str1, $str2); // This code is contributed by ita_c?>
<script> // Javascript program to find LCS with permutations allowedfunction min(a, b){ if(a < b) return a; else return b;} // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of given two stringsfunction longestString( str1, str2){ var count1 = new Array(26); var count2 = new Array(26); count1.fill(0); count2.fill(0); // calculate frequency of characters for (var i = 0; i < str1.length; i++) { count1[str1.charCodeAt(i) -97]++; } for (var i = 0; i < str2.length; i++) { count2[str2.charCodeAt(i) - 97]++; } // Now traverse hash array var result = ""; for (var i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (var j = 1; j <= min(count1[i], count2[i]); j++) { result += String.fromCharCode(97 + i); } } document.write(result); } var str1 = "geeks"; var str2 = "cake"; longestString(str1, str2); // This code is contributed by akshitsaxenaa09.</script>
ek
Time Complexity: O(m + n) where m and n are lengths of input strings.
Auxiliary Space: O(1)
If you have another approach to solve this problem then please share.
This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
29AjayKumar
princiraj1992
ukasp
akshitsaxenaa09
LCS
permutation
subsequence
Combinatorial
Strings
Strings
permutation
Combinatorial
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 26721,
"s": 26693,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 26888,
"s": 26721,
"text": "Given two strings in lowercase, find the longest string whose permutations are subsequences of given two strings. The output longest string must be sorted.Examples: "
},
{
"code": null,
"e": 27264,
"s": 26888,
"text": "Input : str1 = \"pink\", str2 = \"kite\"\nOutput : \"ik\" \nThe string \"ik\" is the longest sorted string \nwhose one permutation \"ik\" is subsequence of\n\"pink\" and another permutation \"ki\" is \nsubsequence of \"kite\". \n\nInput : str1 = \"working\", str2 = \"women\"\nOutput : \"now\"\n\nInput : str1 = \"geeks\" , str2 = \"cake\"\nOutput : \"ek\"\n\nInput : str1 = \"aaaa\" , str2 = \"baba\"\nOutput : \"aa\""
},
{
"code": null,
"e": 27317,
"s": 27266,
"text": "The idea is to count characters in both strings. "
},
{
"code": null,
"e": 27739,
"s": 27317,
"text": "calculate frequency of characters for each string and store them in their respective count arrays, say count1[] for str1 and count2[] for str2.Now we have count arrays for 26 characters. So traverse count1[] and for any index ‘i’ append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times.Since we traverse count array in ascending order, our final string characters will be in sorted order."
},
{
"code": null,
"e": 27883,
"s": 27739,
"text": "calculate frequency of characters for each string and store them in their respective count arrays, say count1[] for str1 and count2[] for str2."
},
{
"code": null,
"e": 28060,
"s": 27883,
"text": "Now we have count arrays for 26 characters. So traverse count1[] and for any index ‘i’ append character (‘a’+i) in resultant string ‘result’ by min(count1[i], count2[i]) times."
},
{
"code": null,
"e": 28163,
"s": 28060,
"text": "Since we traverse count array in ascending order, our final string characters will be in sorted order."
},
{
"code": null,
"e": 28167,
"s": 28163,
"text": "C++"
},
{
"code": null,
"e": 28172,
"s": 28167,
"text": "Java"
},
{
"code": null,
"e": 28180,
"s": 28172,
"text": "Python3"
},
{
"code": null,
"e": 28183,
"s": 28180,
"text": "C#"
},
{
"code": null,
"e": 28187,
"s": 28183,
"text": "PHP"
},
{
"code": null,
"e": 28198,
"s": 28187,
"text": "Javascript"
},
{
"code": "// C++ program to find LCS with permutations allowed#include<bits/stdc++.h>using namespace std; // Function to calculate longest string// str1 --> first string// str2 --> second string// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest string whose// permutations are sub-sequence of given two stringsvoid longestString(string str1, string str2){ int count1[26] = {0}, count2[26]= {0}; // calculate frequency of characters for (int i=0; i<str1.length(); i++) count1[str1[i]-'a']++; for (int i=0; i<str2.length(); i++) count2[str2[i]-'a']++; // Now traverse hash array string result; for (int i=0; i<26; i++) // append character ('a'+i) in resultant // string 'result' by min(count1[i],count2i]) // times for (int j=1; j<=min(count1[i],count2[i]); j++) result.push_back('a' + i); cout << result;} // Driver program to run the caseint main(){ string str1 = \"geeks\", str2 = \"cake\"; longestString(str1, str2); return 0;}",
"e": 29363,
"s": 28198,
"text": null
},
{
"code": "//Java program to find LCS with permutations allowed class GFG { // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of given two strings static void longestString(String str1, String str2) { int count1[] = new int[26], count2[] = new int[26]; // calculate frequency of characters for (int i = 0; i < str1.length(); i++) { count1[str1.charAt(i) - 'a']++; } for (int i = 0; i < str2.length(); i++) { count2[str2.charAt(i) - 'a']++; } // Now traverse hash array String result = \"\"; for (int i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (int j = 1; j <= Math.min(count1[i], count2[i]); j++) { result += (char)('a' + i); } } System.out.println(result); } // Driver program to run the case public static void main(String[] args) { String str1 = \"geeks\", str2 = \"cake\"; longestString(str1, str2); }}/* This java code is contributed by 29AjayKumar*/",
"e": 30761,
"s": 29363,
"text": null
},
{
"code": "# Python 3 program to find LCS# with permutations allowed # Function to calculate longest string# str1 --> first string# str2 --> second string# count1[] --> hash array to calculate frequency# of characters in str1# count[2] --> hash array to calculate frequency# of characters in str2# result --> resultant longest string whose# permutations are sub-sequence# of given two stringsdef longestString(str1, str2): count1 = [0] * 26 count2 = [0] * 26 # calculate frequency of characters for i in range( len(str1)): count1[ord(str1[i]) - ord('a')] += 1 for i in range(len(str2)): count2[ord(str2[i]) - ord('a')] += 1 # Now traverse hash array result = \"\" for i in range(26): # append character ('a'+i) in # resultant string 'result' by # min(count1[i],count2i]) times for j in range(1, min(count1[i], count2[i]) + 1): result = result + chr(ord('a') + i) print(result) # Driver Codeif __name__ == \"__main__\": str1 = \"geeks\" str2 = \"cake\" longestString(str1, str2) # This code is contributed by ita_c",
"e": 31914,
"s": 30761,
"text": null
},
{
"code": "// C# program to find LCS with// permutations allowedusing System; class GFG{ // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate// frequency of characters in str1// count[2] --> hash array to calculate// frequency of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of// given two stringsstatic void longestString(String str1, String str2){ int []count1 = new int[26]; int []count2 = new int[26]; // calculate frequency of characters for (int i = 0; i < str1.Length; i++) { count1[str1[i] - 'a']++; } for (int i = 0; i < str2.Length; i++) { count2[str2[i] - 'a']++; } // Now traverse hash array String result = \"\"; for (int i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (int j = 1; j <= Math.Min(count1[i], count2[i]); j++) { result += (char)('a' + i); } } Console.Write(result);} // Driver Codepublic static void Main(){ String str1 = \"geeks\", str2 = \"cake\"; longestString(str1, str2);}} // This code is contributed// by PrinciRaj1992",
"e": 33236,
"s": 31914,
"text": null
},
{
"code": "<?php// PHP program to find LCS with// permutations allowed // Function to calculate longest string// str1 --> first string// str2 --> second string// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest string whose// permutations are sub-sequence of given two stringsfunction longestString($str1, $str2){ $count1 = array_fill(0, 26, NULL); $count2 = array_fill(0, 26, NULL); // calculate frequency of characters for ($i = 0; $i < strlen($str1); $i++) $count1[ord($str1[$i]) - ord('a')]++; for ($i = 0; $i < strlen($str2); $i++) $count2[ord($str2[$i]) - ord('a')]++; // Now traverse hash array $result = \"\"; for ($i = 0; $i < 26; $i++) // append character ('a'+i) in resultant // string 'result' by min(count1[$i], // count2[$i]) times for ($j = 1; $j <= min($count1[$i], $count2[$i]); $j++) $result = $result.chr(ord('a') + $i); echo $result;} // Driver Code$str1 = \"geeks\";$str2 = \"cake\";longestString($str1, $str2); // This code is contributed by ita_c?>",
"e": 34460,
"s": 33236,
"text": null
},
{
"code": "<script> // Javascript program to find LCS with permutations allowedfunction min(a, b){ if(a < b) return a; else return b;} // Function to calculate longest String// str1 --> first String// str2 --> second String// count1[] --> hash array to calculate frequency// of characters in str1// count[2] --> hash array to calculate frequency// of characters in str2// result --> resultant longest String whose// permutations are sub-sequence of given two stringsfunction longestString( str1, str2){ var count1 = new Array(26); var count2 = new Array(26); count1.fill(0); count2.fill(0); // calculate frequency of characters for (var i = 0; i < str1.length; i++) { count1[str1.charCodeAt(i) -97]++; } for (var i = 0; i < str2.length; i++) { count2[str2.charCodeAt(i) - 97]++; } // Now traverse hash array var result = \"\"; for (var i = 0; i < 26; i++) // append character ('a'+i) in resultant // String 'result' by min(count1[i],count2i]) // times { for (var j = 1; j <= min(count1[i], count2[i]); j++) { result += String.fromCharCode(97 + i); } } document.write(result); } var str1 = \"geeks\"; var str2 = \"cake\"; longestString(str1, str2); // This code is contributed by akshitsaxenaa09.</script>",
"e": 35925,
"s": 34460,
"text": null
},
{
"code": null,
"e": 35928,
"s": 35925,
"text": "ek"
},
{
"code": null,
"e": 35998,
"s": 35928,
"text": "Time Complexity: O(m + n) where m and n are lengths of input strings."
},
{
"code": null,
"e": 36020,
"s": 35998,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 36090,
"s": 36020,
"text": "If you have another approach to solve this problem then please share."
},
{
"code": null,
"e": 36403,
"s": 36090,
"text": "This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 36528,
"s": 36403,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36834,
"s": 36528,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course."
},
{
"code": null,
"e": 36991,
"s": 36834,
"text": "In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students."
},
{
"code": null,
"e": 37003,
"s": 36991,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37017,
"s": 37003,
"text": "princiraj1992"
},
{
"code": null,
"e": 37023,
"s": 37017,
"text": "ukasp"
},
{
"code": null,
"e": 37039,
"s": 37023,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 37043,
"s": 37039,
"text": "LCS"
},
{
"code": null,
"e": 37055,
"s": 37043,
"text": "permutation"
},
{
"code": null,
"e": 37067,
"s": 37055,
"text": "subsequence"
},
{
"code": null,
"e": 37081,
"s": 37067,
"text": "Combinatorial"
},
{
"code": null,
"e": 37089,
"s": 37081,
"text": "Strings"
},
{
"code": null,
"e": 37097,
"s": 37089,
"text": "Strings"
},
{
"code": null,
"e": 37109,
"s": 37097,
"text": "permutation"
},
{
"code": null,
"e": 37123,
"s": 37109,
"text": "Combinatorial"
},
{
"code": null,
"e": 37127,
"s": 37123,
"text": "LCS"
},
{
"code": null,
"e": 37225,
"s": 37127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37297,
"s": 37225,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 37360,
"s": 37297,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 37390,
"s": 37360,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 37429,
"s": 37390,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 37507,
"s": 37429,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 37553,
"s": 37507,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 37578,
"s": 37553,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 37593,
"s": 37578,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37627,
"s": 37593,
"text": "Longest Common Subsequence | DP-4"
}
] |
How To Do Math in Python 3 with Operators? - GeeksforGeeks
|
18 Apr, 2022
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence specifies the order in which operators are evaluated when two or more operators with different precedence are adjacent in an expression. Below is a quick reference table for Unary Operators and Arithmetic Operator.
Divide left operand with right operand using ‘//’ operator
and provide the only quotient as an output
Divide left operand with right operand using ‘%’ operator
and provide the only remainder as an output
Example 1: Unary Operators.
Python3
a = 2.202b = -2.202 # This inverts the sign# for both integer as# well as float typec = -aprint("Minus operator value 1:", c)c = -bprint("Minus operator value 2:", c) # This does not inverts the sign# for both integer as well# as float typec = +aprint("Plus operator value 1:", c)c = +bprint("Plus operator value 2:", c) a = 2b = -2 # This inverts the sign only# for integer type as perform# operation as per this '-(x + 1)'.c = ~a # -(2 + 1)print("Invert operator value 1:", c)c = ~b # -(-2 + 1)print("Invert operator value 2:", c)
Output:
Minus operator value 1: -2.202
Minus operator value 2: 2.202
Plus operator value 1: 2.202
Plus operator value 2: -2.202
Invert operator value 1: -3
Invert operator value 2: 1
Example 2: Addition Operator.
Python3
a = 4b = -5 # This + operator performs# addition of two operands# or numbersd = a + bprint("Addition value 1:", d) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9, 10]d = []for j in range(len(a)): d.append(a[j] + b[j]) print("Addition value 2:", d)
Output:
Addition value 1: -1
Addition value 2: [7, 9, 11, 13, 15]
Example 3: Subtraction Operator.
Python3
a = 4b = -5 # This - operator performs# subtraction of two operands# or numbersd = a - bprint("Subtraction value 1:",d) a = [ 1 ,4,5]b = [1, 2, 3]print("Subtraction values:")for i in range(len(a)) : print(a[i] - b[i])
Output:
Subtraction value 1: 9
Subtraction values:
0
2
2
Example 4: Multiplication Operator.
Python3
a = 4b = -5c = 5.02 # This * operator performs# Multiplication of two# operands or numbersd = a * bprint("Multiplication value 1:", d) d = a * cprint("Multiplication value 2:", d)
Multiplication value 1: -20
Multiplication value 2: 20.08
Example 5: Division Operator.
Python3
a = 20b = -5c = 5.02 # This '/' operator performs# Division of two operands# or numbersd = a / bprint("Division value 1:", d) d = a / cprint("Division value 2:", d)
Output:
Division value 1: -4.0
Division value 2: 3.9840637450199208
Example 6: Floor Division Operator.
Python3
a = 20b = -5c = 5.02 # This // operator performs# Floor Division of two# operands or numbersd = a // bprint("Floor Division value 1:", d) d = a // cprint("Floor Division value 2:", d)
Output:
Floor Division value 1: -4
Floor Division value 2: 3.0
Example 7: Exponential Operator.
Python3
a = 5b = 3c = -3 # This ** operator performs# Exponential operation of two# operands or numbersd = a ** bprint("Exponent value 1:", d) d = a ** cprint("Exponent value 2:", d)
Output:
Exponent value 1: 125
Exponent value 2: 0.008
Example 8: Modulo Operator.
Python3
a = 12 b = 5c = 3 # This % operator performs Modulus# of two operands or numbers and# return the remainderd = a % b print("Modulus value 1:", d) d = c % bprint("Modulus value 2:", d)
Modulus value 1: 2
Modulus value 2: 3
varshagumber28
ruhelaa48
sumitgumber28
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 26104,
"s": 25537,
"text": "Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence specifies the order in which operators are evaluated when two or more operators with different precedence are adjacent in an expression. Below is a quick reference table for Unary Operators and Arithmetic Operator."
},
{
"code": null,
"e": 26163,
"s": 26104,
"text": "Divide left operand with right operand using ‘//’ operator"
},
{
"code": null,
"e": 26206,
"s": 26163,
"text": "and provide the only quotient as an output"
},
{
"code": null,
"e": 26264,
"s": 26206,
"text": "Divide left operand with right operand using ‘%’ operator"
},
{
"code": null,
"e": 26308,
"s": 26264,
"text": "and provide the only remainder as an output"
},
{
"code": null,
"e": 26336,
"s": 26308,
"text": "Example 1: Unary Operators."
},
{
"code": null,
"e": 26344,
"s": 26336,
"text": "Python3"
},
{
"code": "a = 2.202b = -2.202 # This inverts the sign# for both integer as# well as float typec = -aprint(\"Minus operator value 1:\", c)c = -bprint(\"Minus operator value 2:\", c) # This does not inverts the sign# for both integer as well# as float typec = +aprint(\"Plus operator value 1:\", c)c = +bprint(\"Plus operator value 2:\", c) a = 2b = -2 # This inverts the sign only# for integer type as perform# operation as per this '-(x + 1)'.c = ~a # -(2 + 1)print(\"Invert operator value 1:\", c)c = ~b # -(-2 + 1)print(\"Invert operator value 2:\", c)",
"e": 26882,
"s": 26344,
"text": null
},
{
"code": null,
"e": 26891,
"s": 26882,
"text": "Output: "
},
{
"code": null,
"e": 27066,
"s": 26891,
"text": "Minus operator value 1: -2.202\nMinus operator value 2: 2.202\nPlus operator value 1: 2.202\nPlus operator value 2: -2.202\nInvert operator value 1: -3\nInvert operator value 2: 1"
},
{
"code": null,
"e": 27096,
"s": 27066,
"text": "Example 2: Addition Operator."
},
{
"code": null,
"e": 27104,
"s": 27096,
"text": "Python3"
},
{
"code": "a = 4b = -5 # This + operator performs# addition of two operands# or numbersd = a + bprint(\"Addition value 1:\", d) a = [1, 2, 3, 4, 5]b = [6, 7, 8, 9, 10]d = []for j in range(len(a)): d.append(a[j] + b[j]) print(\"Addition value 2:\", d)",
"e": 27343,
"s": 27104,
"text": null
},
{
"code": null,
"e": 27352,
"s": 27343,
"text": "Output: "
},
{
"code": null,
"e": 27410,
"s": 27352,
"text": "Addition value 1: -1\nAddition value 2: [7, 9, 11, 13, 15]"
},
{
"code": null,
"e": 27443,
"s": 27410,
"text": "Example 3: Subtraction Operator."
},
{
"code": null,
"e": 27451,
"s": 27443,
"text": "Python3"
},
{
"code": "a = 4b = -5 # This - operator performs# subtraction of two operands# or numbersd = a - bprint(\"Subtraction value 1:\",d) a = [ 1 ,4,5]b = [1, 2, 3]print(\"Subtraction values:\")for i in range(len(a)) : print(a[i] - b[i])",
"e": 27670,
"s": 27451,
"text": null
},
{
"code": null,
"e": 27679,
"s": 27670,
"text": "Output: "
},
{
"code": null,
"e": 27728,
"s": 27679,
"text": "Subtraction value 1: 9\nSubtraction values:\n0\n2\n2"
},
{
"code": null,
"e": 27764,
"s": 27728,
"text": "Example 4: Multiplication Operator."
},
{
"code": null,
"e": 27772,
"s": 27764,
"text": "Python3"
},
{
"code": "a = 4b = -5c = 5.02 # This * operator performs# Multiplication of two# operands or numbersd = a * bprint(\"Multiplication value 1:\", d) d = a * cprint(\"Multiplication value 2:\", d)",
"e": 27952,
"s": 27772,
"text": null
},
{
"code": null,
"e": 28010,
"s": 27952,
"text": "Multiplication value 1: -20\nMultiplication value 2: 20.08"
},
{
"code": null,
"e": 28040,
"s": 28010,
"text": "Example 5: Division Operator."
},
{
"code": null,
"e": 28048,
"s": 28040,
"text": "Python3"
},
{
"code": "a = 20b = -5c = 5.02 # This '/' operator performs# Division of two operands# or numbersd = a / bprint(\"Division value 1:\", d) d = a / cprint(\"Division value 2:\", d)",
"e": 28213,
"s": 28048,
"text": null
},
{
"code": null,
"e": 28221,
"s": 28213,
"text": "Output:"
},
{
"code": null,
"e": 28281,
"s": 28221,
"text": "Division value 1: -4.0\nDivision value 2: 3.9840637450199208"
},
{
"code": null,
"e": 28317,
"s": 28281,
"text": "Example 6: Floor Division Operator."
},
{
"code": null,
"e": 28325,
"s": 28317,
"text": "Python3"
},
{
"code": "a = 20b = -5c = 5.02 # This // operator performs# Floor Division of two# operands or numbersd = a // bprint(\"Floor Division value 1:\", d) d = a // cprint(\"Floor Division value 2:\", d)",
"e": 28509,
"s": 28325,
"text": null
},
{
"code": null,
"e": 28517,
"s": 28509,
"text": "Output:"
},
{
"code": null,
"e": 28572,
"s": 28517,
"text": "Floor Division value 1: -4\nFloor Division value 2: 3.0"
},
{
"code": null,
"e": 28605,
"s": 28572,
"text": "Example 7: Exponential Operator."
},
{
"code": null,
"e": 28613,
"s": 28605,
"text": "Python3"
},
{
"code": "a = 5b = 3c = -3 # This ** operator performs# Exponential operation of two# operands or numbersd = a ** bprint(\"Exponent value 1:\", d) d = a ** cprint(\"Exponent value 2:\", d)",
"e": 28788,
"s": 28613,
"text": null
},
{
"code": null,
"e": 28796,
"s": 28788,
"text": "Output:"
},
{
"code": null,
"e": 28842,
"s": 28796,
"text": "Exponent value 1: 125\nExponent value 2: 0.008"
},
{
"code": null,
"e": 28870,
"s": 28842,
"text": "Example 8: Modulo Operator."
},
{
"code": null,
"e": 28878,
"s": 28870,
"text": "Python3"
},
{
"code": "a = 12 b = 5c = 3 # This % operator performs Modulus# of two operands or numbers and# return the remainderd = a % b print(\"Modulus value 1:\", d) d = c % bprint(\"Modulus value 2:\", d)",
"e": 29062,
"s": 28878,
"text": null
},
{
"code": null,
"e": 29101,
"s": 29062,
"text": "Modulus value 1: 2\nModulus value 2: 3\n"
},
{
"code": null,
"e": 29116,
"s": 29101,
"text": "varshagumber28"
},
{
"code": null,
"e": 29126,
"s": 29116,
"text": "ruhelaa48"
},
{
"code": null,
"e": 29140,
"s": 29126,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29157,
"s": 29140,
"text": "Python-Operators"
},
{
"code": null,
"e": 29164,
"s": 29157,
"text": "Python"
},
{
"code": null,
"e": 29262,
"s": 29164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29294,
"s": 29262,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29336,
"s": 29294,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29378,
"s": 29336,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29434,
"s": 29378,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29461,
"s": 29434,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29500,
"s": 29461,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29531,
"s": 29500,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29560,
"s": 29531,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29582,
"s": 29560,
"text": "Defaultdict in Python"
}
] |
TimeSpan.Subtract() Method in C# - GeeksforGeeks
|
30 Sep, 2019
This method is used to a get new TimeSpan object whose value is the difference of the specified TimeSpan object and this instance.
Syntax: public TimeSpan Subtract (TimeSpan t);
Parameter:t: This parameter specifies the time interval to be subtracted.
Return Value: It returns a new TimeSpan object whose value is the difference current instance and the value of t.
Exception: This method will give OverflowException when the resulting TimeSpan is smaller than smallest possible value or greater than the largest possible value.
Below programs illustrate the use of TimeSpan.Subtract(TimeSpan) Method:
Example 1:
// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating the TimeSpan object TimeSpan t1 = new TimeSpan(3, 22, 35, 33); TimeSpan t2 = new TimeSpan(1, 11, 15, 16); TimeSpan variable = t1.Subtract(t2); Console.WriteLine("The Timespan is : {0}", variable); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
The Timespan is : 2.11:20:17
Example 2: For Overflow Exception
// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System; class GFG { // Main Method public static void Main() { try { // the TimeSpan object TimeSpan t1 = TimeSpan.MinValue; TimeSpan t2 = new TimeSpan(3, 22, 35, 33); TimeSpan variable = t1.Subtract(t2); Console.WriteLine("The Timespan is : {0}", variable); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
Exception Thrown: System.OverflowException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.subtract?view=netframework-4.7.2
shubham_singh
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 25678,
"s": 25547,
"text": "This method is used to a get new TimeSpan object whose value is the difference of the specified TimeSpan object and this instance."
},
{
"code": null,
"e": 25725,
"s": 25678,
"text": "Syntax: public TimeSpan Subtract (TimeSpan t);"
},
{
"code": null,
"e": 25799,
"s": 25725,
"text": "Parameter:t: This parameter specifies the time interval to be subtracted."
},
{
"code": null,
"e": 25913,
"s": 25799,
"text": "Return Value: It returns a new TimeSpan object whose value is the difference current instance and the value of t."
},
{
"code": null,
"e": 26076,
"s": 25913,
"text": "Exception: This method will give OverflowException when the resulting TimeSpan is smaller than smallest possible value or greater than the largest possible value."
},
{
"code": null,
"e": 26149,
"s": 26076,
"text": "Below programs illustrate the use of TimeSpan.Subtract(TimeSpan) Method:"
},
{
"code": null,
"e": 26160,
"s": 26149,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System; class GFG { // Main Method public static void Main() { try { // creating the TimeSpan object TimeSpan t1 = new TimeSpan(3, 22, 35, 33); TimeSpan t2 = new TimeSpan(1, 11, 15, 16); TimeSpan variable = t1.Subtract(t2); Console.WriteLine(\"The Timespan is : {0}\", variable); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26810,
"s": 26160,
"text": null
},
{
"code": null,
"e": 26840,
"s": 26810,
"text": "The Timespan is : 2.11:20:17\n"
},
{
"code": null,
"e": 26874,
"s": 26840,
"text": "Example 2: For Overflow Exception"
},
{
"code": "// C# program to demonstrate the// TimeSpan.Subtract(TimeSpan) Methodusing System; class GFG { // Main Method public static void Main() { try { // the TimeSpan object TimeSpan t1 = TimeSpan.MinValue; TimeSpan t2 = new TimeSpan(3, 22, 35, 33); TimeSpan variable = t1.Subtract(t2); Console.WriteLine(\"The Timespan is : {0}\", variable); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 27505,
"s": 26874,
"text": null
},
{
"code": null,
"e": 27549,
"s": 27505,
"text": "Exception Thrown: System.OverflowException\n"
},
{
"code": null,
"e": 27560,
"s": 27549,
"text": "Reference:"
},
{
"code": null,
"e": 27653,
"s": 27560,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.timespan.subtract?view=netframework-4.7.2"
},
{
"code": null,
"e": 27667,
"s": 27653,
"text": "shubham_singh"
},
{
"code": null,
"e": 27681,
"s": 27667,
"text": "CSharp-method"
},
{
"code": null,
"e": 27704,
"s": 27681,
"text": "CSharp-TimeSpan-Struct"
},
{
"code": null,
"e": 27707,
"s": 27704,
"text": "C#"
},
{
"code": null,
"e": 27805,
"s": 27707,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27828,
"s": 27805,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27856,
"s": 27828,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27873,
"s": 27856,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 27895,
"s": 27873,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 27924,
"s": 27895,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 27964,
"s": 27924,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 27987,
"s": 27964,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28030,
"s": 27987,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28070,
"s": 28030,
"text": "Convert String to Character Array in C#"
}
] |
How to skip only first element of List in Scala - GeeksforGeeks
|
17 Apr, 2019
In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let’s see how to print the element of given List, by skipping the first item in Scala.
List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, tail() method is used to skip the first element of the list.below are examples to skip only first element of List.Example :
// Scala program to skip only first element of Listimport scala.collection.immutable._ // Creating object object GFGobject{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "a", "fabulous", "portal") println(mylist.tail) }}
List(For, geeks, is, a, fabulous, portal)
Example :
// Scala program to skip only first element of Listimport scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // range from 10 to 19 val myList = List.range(10, 19) println(myList) println("Using tail() method: " + myList.tail) } }
List(10, 11, 12, 13, 14, 15, 16, 17, 18)
Using tail() method: List(11, 12, 13, 14, 15, 16, 17, 18)
Scala
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Scala List map() method with example
Comments In Scala
Scala | Try-Catch Exceptions
|
[
{
"code": null,
"e": 25301,
"s": 25273,
"text": "\n17 Apr, 2019"
},
{
"code": null,
"e": 25532,
"s": 25301,
"text": "In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let’s see how to print the element of given List, by skipping the first item in Scala."
},
{
"code": null,
"e": 25778,
"s": 25532,
"text": "List in Scala contains many suitable methods to perform simple operations like head(), tail(), isEmpty(). Coming to list, tail() method is used to skip the first element of the list.below are examples to skip only first element of List.Example :"
},
{
"code": "// Scala program to skip only first element of Listimport scala.collection.immutable._ // Creating object object GFGobject{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"a\", \"fabulous\", \"portal\") println(mylist.tail) }}",
"e": 26193,
"s": 25778,
"text": null
},
{
"code": null,
"e": 26236,
"s": 26193,
"text": "List(For, geeks, is, a, fabulous, portal)\n"
},
{
"code": null,
"e": 26246,
"s": 26236,
"text": "Example :"
},
{
"code": "// Scala program to skip only first element of Listimport scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // range from 10 to 19 val myList = List.range(10, 19) println(myList) println(\"Using tail() method: \" + myList.tail) } } ",
"e": 26586,
"s": 26246,
"text": null
},
{
"code": null,
"e": 26686,
"s": 26586,
"text": "List(10, 11, 12, 13, 14, 15, 16, 17, 18)\nUsing tail() method: List(11, 12, 13, 14, 15, 16, 17, 18)\n"
},
{
"code": null,
"e": 26692,
"s": 26686,
"text": "Scala"
},
{
"code": null,
"e": 26698,
"s": 26692,
"text": "Scala"
},
{
"code": null,
"e": 26796,
"s": 26698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26817,
"s": 26796,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 26832,
"s": 26817,
"text": "Scala | Traits"
},
{
"code": null,
"e": 26849,
"s": 26832,
"text": "Scala ListBuffer"
},
{
"code": null,
"e": 26884,
"s": 26849,
"text": "Scala | Case Class and Case Object"
},
{
"code": null,
"e": 26905,
"s": 26884,
"text": "Hello World in Scala"
},
{
"code": null,
"e": 26932,
"s": 26905,
"text": "Scala | Functions - Basics"
},
{
"code": null,
"e": 26998,
"s": 26932,
"text": "Scala | Decision Making (if, if-else, Nested if-else, if-else if)"
},
{
"code": null,
"e": 27035,
"s": 26998,
"text": "Scala List map() method with example"
},
{
"code": null,
"e": 27053,
"s": 27035,
"text": "Comments In Scala"
}
] |
Python | Get first element with maximum value in list of tuples - GeeksforGeeks
|
30 Dec, 2018
In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let’s discuss certain ways in which this can be achieved.
Method #1 : Using max() + operator.itemgetter()We can get the maximum of corresponding tuple index from a list using the key itemgetter index provided and then mention the index information required using index specification at the end.
# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using max() + itemgetter()from operator import itemgetter # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print ("Original list : " + str(test_list)) # using max() + itemgetter()# to get tuple info. of maximum value tupleres = max(test_list, key = itemgetter(1))[0] # printing resultprint ("The name with maximum score is : " + res)
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Method #2 : Using max() + lambdaThis method is almost similar to the method discussed above, just the difference is the specification and processing of target tuple index for maximum is done by lambda function. This improved readability of code.
# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using max() + lambda # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print ("Original list : " + str(test_list)) # using max() + lambda# to get tuple info. of maximum value tupleres = max(test_list, key = lambda i : i[1])[0] # printing resultprint ("The name with maximum score is : " + res)
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Method #3 : Using sorted() + lambdaThe task performed by the max() in the above two methods can be done using reverse sorting and printing the first element. lambda function performs the task similar to above said methods.
# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using sorted() + lambda # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print ("Original list : " + str(test_list)) # using sorted() + lambda# to get tuple info. of maximum value tupleres = sorted(test_list, key = lambda i: i[1], reverse = True)[0][0] # printing resultprint ("The name with maximum score is : " + res)
Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]
The name with maximum score is : Manjeet
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 25759,
"s": 25731,
"text": "\n30 Dec, 2018"
},
{
"code": null,
"e": 26076,
"s": 25759,
"text": "In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let’s discuss certain ways in which this can be achieved."
},
{
"code": null,
"e": 26313,
"s": 26076,
"text": "Method #1 : Using max() + operator.itemgetter()We can get the maximum of corresponding tuple index from a list using the key itemgetter index provided and then mention the index information required using index specification at the end."
},
{
"code": "# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using max() + itemgetter()from operator import itemgetter # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print (\"Original list : \" + str(test_list)) # using max() + itemgetter()# to get tuple info. of maximum value tupleres = max(test_list, key = itemgetter(1))[0] # printing resultprint (\"The name with maximum score is : \" + res)",
"e": 26785,
"s": 26313,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26785,
"text": "Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]\nThe name with maximum score is : Manjeet\n"
},
{
"code": null,
"e": 27141,
"s": 26894,
"text": " Method #2 : Using max() + lambdaThis method is almost similar to the method discussed above, just the difference is the specification and processing of target tuple index for maximum is done by lambda function. This improved readability of code."
},
{
"code": "# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using max() + lambda # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print (\"Original list : \" + str(test_list)) # using max() + lambda# to get tuple info. of maximum value tupleres = max(test_list, key = lambda i : i[1])[0] # printing resultprint (\"The name with maximum score is : \" + res)",
"e": 27572,
"s": 27141,
"text": null
},
{
"code": null,
"e": 27681,
"s": 27572,
"text": "Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]\nThe name with maximum score is : Manjeet\n"
},
{
"code": null,
"e": 27905,
"s": 27681,
"text": " Method #3 : Using sorted() + lambdaThe task performed by the max() in the above two methods can be done using reverse sorting and printing the first element. lambda function performs the task similar to above said methods."
},
{
"code": "# Python3 code to demonstrate # to get tuple info. of maximum value tuple# using sorted() + lambda # initializing list test_list = [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)] # printing original list print (\"Original list : \" + str(test_list)) # using sorted() + lambda# to get tuple info. of maximum value tupleres = sorted(test_list, key = lambda i: i[1], reverse = True)[0][0] # printing resultprint (\"The name with maximum score is : \" + res)",
"e": 28363,
"s": 27905,
"text": null
},
{
"code": null,
"e": 28472,
"s": 28363,
"text": "Original list : [('Rash', 143), ('Manjeet', 200), ('Varsha', 100)]\nThe name with maximum score is : Manjeet\n"
},
{
"code": null,
"e": 28493,
"s": 28472,
"text": "Python list-programs"
},
{
"code": null,
"e": 28515,
"s": 28493,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 28522,
"s": 28515,
"text": "Python"
},
{
"code": null,
"e": 28538,
"s": 28522,
"text": "Python Programs"
},
{
"code": null,
"e": 28636,
"s": 28538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28654,
"s": 28636,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28686,
"s": 28654,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28728,
"s": 28686,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28754,
"s": 28728,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28798,
"s": 28754,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28841,
"s": 28798,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28863,
"s": 28841,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28902,
"s": 28863,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28948,
"s": 28902,
"text": "Python | Split string into list of characters"
}
] |
Node.js CRUD Operations Using Mongoose and MongoDB Atlas - GeeksforGeeks
|
07 Oct, 2021
Before we dive into the major operations and functionality of Mongoose, let us get a brief idea about what it actually is and how it makes our Node.js project more flexible and user friendly.
MongooseJs: Mongoose is basically a package that serves as a mediator between the NodeJS application and MongoDB server. It is an Object Document Mapper(ODM) that allows us to define objects with strongly-typed-schema that is mapped to a MongoDB document. Mongoose supports all the CRUD operations – Creating, Retrieving, Updating, and Deleting.
Prerequisites: Since we will be using Express to set up our basic server, We would recommend going through some articles on express and official express documents. Other requirements include MongoDB Atlas and Postman.
Installation: Install the mongoose and the express module through npm using the below command:
npm install express mongoose --save
MongoDB Atlas Setup:
Setup an account.
Build a new cluster.
Go to Database Access and hit “Add New User”. Add a username and password, if you autogenerate a password make sure you copy it, we’ll need it later.
Whitelist your IP Address.Hit “Add Current IP address” and Confirm.
Go to Clusters, if your cluster building is done then hit Connect, “Connect Your Application”, and copy the URL it gives you.
Postman Setup: We will be using Postman to manage our requests. Once it is downloaded, hit “Create a request” option. Every time we make a new API endpoint we’ll be setting up another request for it. This will help you manage everything so you don’t have to copy/paste HTTP requests everywhere.
Server Setup: Here, we’ll set up our server on port 3000 and call the express function that returns a server object in a variable named app. Then we start the listener saying app.listen with the port address. Finally, we create the /api route which will be triggered once request localhost:3000/api is received from the browser.
File Name : Server.js
Javascript
const express=require('express');const bodyParser=require('body-parser');const api = require('./api'); const port=3000;const app=express(); app.listen(port, function() { console.log("Server is listening at port:" + port);}); // Parses the text as url encoded dataapp.use(bodyParser.urlencoded({extended: true})); // Parses the text as jsonapp.use(bodyParser.json()); app.use('/api', api);
Server running on desired port
Sample output to check working of api route
Schema: Schema is a representation of the structure of the data. It allows us to decide exactly what data we want, and what options we want the data to have as an object.
Filename : studentschema.js
Javascript
var mongoose=require('mongoose'); var StudentSchema = new mongoose.Schema({ StudentId:Number, Name:String, Roll:Number, Birthday:Date, Address:String}); module.exports = mongoose.model( 'student', StudentSchema, 'Students');
A schema named “StuentSchema” is created that accepts the fields Id, Name, Roll, Birthday, Address.
Models basically provide a list of predefined methods that are used to manipulate the data for inserting, updating, deleting and retrieving from the database collection.
With that basic pattern, we’ll use the mongoose.model method to make it usable with actual data and export it so that we can use in api.js.
Advanced Routing and MongoDB Connections:
Filename : api.js When you make a request to localhost:3000/api, express will search for api route and execute the api.js file.
Javascript
var mongoose = require('mongoose');var express = require('express'); var router = express.Router();var StudentModel = require('./studentschema'); // Connecting to databasevar query = 'mongodb+srv://Username:<password>' + '@student.tuufn.mongodb.net/College?' + 'retryWrites=true&w=majority' const db = (query);mongoose.Promise = global.Promise; mongoose.connect(db, { useNewUrlParser : true, useUnifiedTopology: true }, function(error) { if (error) { console.log("Error!" + error); }}); module.exports = router;
The database is College and the collection inside the database in Students.
A Glimpse of the Mongo Database
CRUD OPERATIONS
Create: We’ll be setting up a post request to ‘/save’ and we’ll create a new student object with our model and pass with it the request data from Postman.
Once this is done, we will use .save() to save it to the database.
router.get('/save', function(req, res) {
var newStudent = new StudentModel({StudentId:101,
Name:"Sam", Roll:1, Birthday:2001-09-08});
newStudent.save(function(err, data) {
if(err) {
console.log(error);
}
else {
res.send("Data inserted");
}
});
});
A new instance of the student is created using StudentModel and the reference is stored in the variable newStudent. Using the newStudent variable we save the document of the new student to the database collection.
For achieving this, in Postman we will make a GET request localhost:3000/api/save
Note: We can even insert new documents without hardcoding the fields as done above. For that we need to change the request from GET to POST and use the body-parser middleware to accept the new student’s data. This ensures that we can insert details of as many students as we need.
router.post('/save', function(req, res) {
var newStudent = new StudentModel();
newStudent.StudentId = req.body.StudentId;
newStudent.Name = req.body.Name;
newStudent.Roll = req.body.Roll;
newStudent.Birthday = req.body.Birthday;
newStudent.save(function(err, data){
if(err){
console.log(error);
}
else{
res.send("Data inserted");
}
});
});
Retrieve: To retrieve records from a database collection we make use of the .find() function.
router.get('/findall', function(req, res) {
StudentModel.find(function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});
In Postman, we make a new GET request with the URL localhost:3000/api/findall and hit send. It makes our HTTP GET request and returns documents of all the students from our database collection.
To retrieve a single record or the first matched document we make use of the function findOne().
router.get('/findfirst', function(req, res) {
StudentModel.findOne({StudentId:{$gt:185}},
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});
In Postman, we make a new GET request with the URL localhost:3000/api/findfirst and hit send.It makes our HTTP GET request and returns the first document that match the condition StudentId:$gt:185 ($gt means greater than).
Delete: To delete a record from database, we make use of the function .remove(). It accepts a condition that is the parameter according to which it performs deletion. Here the condition is Id:188.
router.get('/delete', function(req, res) {
StudentModel.remove({StudentId:188},
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
}
});
});
We can also use the .findByIdAndDelete() method to easily remove a record from the database. Every object created with Mongoose is given its own _id, and we can use this to target specific items with a DELETE request.
router.post('/delete', function(req, res) {
StudentModel.findByIdAndDelete((req.body.id),
function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
console.log("Data Deleted!");
}
});
});
Update: Just like with the delete request, we’ll be using the _id to target the correct item. .findByIdAndUpdate() takes the target’s id, and the request data you want to replace it with.
router.post('/update', function(req, res) {
StudentModel.findByIdAndUpdate(req.body.id,
{Name:req.body.Name}, function(err, data) {
if(err){
console.log(err);
}
else{
res.send(data);
console.log("Data updated!");
}
});
});
How to retrieve the latest record from database collection: To retrieve the latest record we need two basic functions:
.sort() – It accepts a parameter according to which it sorts the data in descending (-1) or ascending(1) order.
.limit() – It decides the number of documents needed to be retrieved.
Example: Suppose I want to fetch the record of the student who has most recently taken admission to the College. The following code snippet does this job for us..
Code Snippet that retrieves the latest data
NOTE: limit() should not be used without .sort() as it may cause bugs later that are difficult to track down. This is because we can’t otherwise guarantee the order of the result. We would get different records at the top of the results which isn’t desirable. To make a query deterministic, they must give the same results every time they are executed.
anikakapoor
khushboogoyal499
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Express.js res.redirect() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26537,
"s": 26509,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 26729,
"s": 26537,
"text": "Before we dive into the major operations and functionality of Mongoose, let us get a brief idea about what it actually is and how it makes our Node.js project more flexible and user friendly."
},
{
"code": null,
"e": 27075,
"s": 26729,
"text": "MongooseJs: Mongoose is basically a package that serves as a mediator between the NodeJS application and MongoDB server. It is an Object Document Mapper(ODM) that allows us to define objects with strongly-typed-schema that is mapped to a MongoDB document. Mongoose supports all the CRUD operations – Creating, Retrieving, Updating, and Deleting."
},
{
"code": null,
"e": 27293,
"s": 27075,
"text": "Prerequisites: Since we will be using Express to set up our basic server, We would recommend going through some articles on express and official express documents. Other requirements include MongoDB Atlas and Postman."
},
{
"code": null,
"e": 27388,
"s": 27293,
"text": "Installation: Install the mongoose and the express module through npm using the below command:"
},
{
"code": null,
"e": 27424,
"s": 27388,
"text": "npm install express mongoose --save"
},
{
"code": null,
"e": 27446,
"s": 27424,
"text": "MongoDB Atlas Setup: "
},
{
"code": null,
"e": 27464,
"s": 27446,
"text": "Setup an account."
},
{
"code": null,
"e": 27485,
"s": 27464,
"text": "Build a new cluster."
},
{
"code": null,
"e": 27635,
"s": 27485,
"text": "Go to Database Access and hit “Add New User”. Add a username and password, if you autogenerate a password make sure you copy it, we’ll need it later."
},
{
"code": null,
"e": 27703,
"s": 27635,
"text": "Whitelist your IP Address.Hit “Add Current IP address” and Confirm."
},
{
"code": null,
"e": 27829,
"s": 27703,
"text": "Go to Clusters, if your cluster building is done then hit Connect, “Connect Your Application”, and copy the URL it gives you."
},
{
"code": null,
"e": 28124,
"s": 27829,
"text": "Postman Setup: We will be using Postman to manage our requests. Once it is downloaded, hit “Create a request” option. Every time we make a new API endpoint we’ll be setting up another request for it. This will help you manage everything so you don’t have to copy/paste HTTP requests everywhere."
},
{
"code": null,
"e": 28454,
"s": 28124,
"text": "Server Setup: Here, we’ll set up our server on port 3000 and call the express function that returns a server object in a variable named app. Then we start the listener saying app.listen with the port address. Finally, we create the /api route which will be triggered once request localhost:3000/api is received from the browser. "
},
{
"code": null,
"e": 28476,
"s": 28454,
"text": "File Name : Server.js"
},
{
"code": null,
"e": 28487,
"s": 28476,
"text": "Javascript"
},
{
"code": "const express=require('express');const bodyParser=require('body-parser');const api = require('./api'); const port=3000;const app=express(); app.listen(port, function() { console.log(\"Server is listening at port:\" + port);}); // Parses the text as url encoded dataapp.use(bodyParser.urlencoded({extended: true})); // Parses the text as jsonapp.use(bodyParser.json()); app.use('/api', api);",
"e": 28888,
"s": 28487,
"text": null
},
{
"code": null,
"e": 28919,
"s": 28888,
"text": "Server running on desired port"
},
{
"code": null,
"e": 28963,
"s": 28919,
"text": "Sample output to check working of api route"
},
{
"code": null,
"e": 29134,
"s": 28963,
"text": "Schema: Schema is a representation of the structure of the data. It allows us to decide exactly what data we want, and what options we want the data to have as an object."
},
{
"code": null,
"e": 29163,
"s": 29134,
"text": "Filename : studentschema.js "
},
{
"code": null,
"e": 29174,
"s": 29163,
"text": "Javascript"
},
{
"code": "var mongoose=require('mongoose'); var StudentSchema = new mongoose.Schema({ StudentId:Number, Name:String, Roll:Number, Birthday:Date, Address:String}); module.exports = mongoose.model( 'student', StudentSchema, 'Students');",
"e": 29419,
"s": 29174,
"text": null
},
{
"code": null,
"e": 29519,
"s": 29419,
"text": "A schema named “StuentSchema” is created that accepts the fields Id, Name, Roll, Birthday, Address."
},
{
"code": null,
"e": 29689,
"s": 29519,
"text": "Models basically provide a list of predefined methods that are used to manipulate the data for inserting, updating, deleting and retrieving from the database collection."
},
{
"code": null,
"e": 29829,
"s": 29689,
"text": "With that basic pattern, we’ll use the mongoose.model method to make it usable with actual data and export it so that we can use in api.js."
},
{
"code": null,
"e": 29872,
"s": 29829,
"text": "Advanced Routing and MongoDB Connections: "
},
{
"code": null,
"e": 30000,
"s": 29872,
"text": "Filename : api.js When you make a request to localhost:3000/api, express will search for api route and execute the api.js file."
},
{
"code": null,
"e": 30011,
"s": 30000,
"text": "Javascript"
},
{
"code": "var mongoose = require('mongoose');var express = require('express'); var router = express.Router();var StudentModel = require('./studentschema'); // Connecting to databasevar query = 'mongodb+srv://Username:<password>' + '@student.tuufn.mongodb.net/College?' + 'retryWrites=true&w=majority' const db = (query);mongoose.Promise = global.Promise; mongoose.connect(db, { useNewUrlParser : true, useUnifiedTopology: true }, function(error) { if (error) { console.log(\"Error!\" + error); }}); module.exports = router;",
"e": 30546,
"s": 30011,
"text": null
},
{
"code": null,
"e": 30622,
"s": 30546,
"text": "The database is College and the collection inside the database in Students."
},
{
"code": null,
"e": 30654,
"s": 30622,
"text": "A Glimpse of the Mongo Database"
},
{
"code": null,
"e": 30671,
"s": 30654,
"text": "CRUD OPERATIONS "
},
{
"code": null,
"e": 30826,
"s": 30671,
"text": "Create: We’ll be setting up a post request to ‘/save’ and we’ll create a new student object with our model and pass with it the request data from Postman."
},
{
"code": null,
"e": 30893,
"s": 30826,
"text": "Once this is done, we will use .save() to save it to the database."
},
{
"code": null,
"e": 31219,
"s": 30893,
"text": "router.get('/save', function(req, res) {\n var newStudent = new StudentModel({StudentId:101, \n Name:\"Sam\", Roll:1, Birthday:2001-09-08});\n\n newStudent.save(function(err, data) {\n if(err) {\n console.log(error);\n }\n else {\n res.send(\"Data inserted\");\n }\n });\n});"
},
{
"code": null,
"e": 31433,
"s": 31219,
"text": "A new instance of the student is created using StudentModel and the reference is stored in the variable newStudent. Using the newStudent variable we save the document of the new student to the database collection."
},
{
"code": null,
"e": 31515,
"s": 31433,
"text": "For achieving this, in Postman we will make a GET request localhost:3000/api/save"
},
{
"code": null,
"e": 31796,
"s": 31515,
"text": "Note: We can even insert new documents without hardcoding the fields as done above. For that we need to change the request from GET to POST and use the body-parser middleware to accept the new student’s data. This ensures that we can insert details of as many students as we need."
},
{
"code": null,
"e": 32208,
"s": 31796,
"text": "router.post('/save', function(req, res) {\nvar newStudent = new StudentModel();\n newStudent.StudentId = req.body.StudentId;\n newStudent.Name = req.body.Name;\n newStudent.Roll = req.body.Roll;\n newStudent.Birthday = req.body.Birthday;\n \n newStudent.save(function(err, data){\n if(err){\n console.log(error);\n }\n else{\n res.send(\"Data inserted\");\n }\n });\n});"
},
{
"code": null,
"e": 32302,
"s": 32208,
"text": "Retrieve: To retrieve records from a database collection we make use of the .find() function."
},
{
"code": null,
"e": 32505,
"s": 32302,
"text": "router.get('/findall', function(req, res) {\n StudentModel.find(function(err, data) {\n if(err){\n console.log(err);\n }\n else{\n res.send(data);\n }\n }); \n});"
},
{
"code": null,
"e": 32699,
"s": 32505,
"text": "In Postman, we make a new GET request with the URL localhost:3000/api/findall and hit send. It makes our HTTP GET request and returns documents of all the students from our database collection."
},
{
"code": null,
"e": 32797,
"s": 32699,
"text": "To retrieve a single record or the first matched document we make use of the function findOne(). "
},
{
"code": null,
"e": 33041,
"s": 32797,
"text": "router.get('/findfirst', function(req, res) {\n StudentModel.findOne({StudentId:{$gt:185}}, \n function(err, data) {\n if(err){\n console.log(err);\n }\n else{\n res.send(data);\n }\n }); \n});"
},
{
"code": null,
"e": 33264,
"s": 33041,
"text": "In Postman, we make a new GET request with the URL localhost:3000/api/findfirst and hit send.It makes our HTTP GET request and returns the first document that match the condition StudentId:$gt:185 ($gt means greater than)."
},
{
"code": null,
"e": 33461,
"s": 33264,
"text": "Delete: To delete a record from database, we make use of the function .remove(). It accepts a condition that is the parameter according to which it performs deletion. Here the condition is Id:188."
},
{
"code": null,
"e": 33695,
"s": 33461,
"text": "router.get('/delete', function(req, res) {\n StudentModel.remove({StudentId:188}, \n function(err, data) {\n if(err){\n console.log(err);\n }\n else{\n res.send(data);\n }\n }); \n});"
},
{
"code": null,
"e": 33914,
"s": 33695,
"text": "We can also use the .findByIdAndDelete() method to easily remove a record from the database. Every object created with Mongoose is given its own _id, and we can use this to target specific items with a DELETE request. "
},
{
"code": null,
"e": 34200,
"s": 33914,
"text": "router.post('/delete', function(req, res) {\n StudentModel.findByIdAndDelete((req.body.id), \n function(err, data) {\n if(err){\n console.log(err);\n }\n else{\n res.send(data);\n console.log(\"Data Deleted!\");\n }\n }); \n});"
},
{
"code": null,
"e": 34388,
"s": 34200,
"text": "Update: Just like with the delete request, we’ll be using the _id to target the correct item. .findByIdAndUpdate() takes the target’s id, and the request data you want to replace it with."
},
{
"code": null,
"e": 34694,
"s": 34388,
"text": "router.post('/update', function(req, res) {\n StudentModel.findByIdAndUpdate(req.body.id, \n {Name:req.body.Name}, function(err, data) {\n if(err){\n console.log(err);\n }\n else{\n res.send(data);\n console.log(\"Data updated!\");\n }\n }); \n});"
},
{
"code": null,
"e": 34814,
"s": 34694,
"text": "How to retrieve the latest record from database collection: To retrieve the latest record we need two basic functions: "
},
{
"code": null,
"e": 34926,
"s": 34814,
"text": ".sort() – It accepts a parameter according to which it sorts the data in descending (-1) or ascending(1) order."
},
{
"code": null,
"e": 34996,
"s": 34926,
"text": ".limit() – It decides the number of documents needed to be retrieved."
},
{
"code": null,
"e": 35159,
"s": 34996,
"text": "Example: Suppose I want to fetch the record of the student who has most recently taken admission to the College. The following code snippet does this job for us.."
},
{
"code": null,
"e": 35203,
"s": 35159,
"text": "Code Snippet that retrieves the latest data"
},
{
"code": null,
"e": 35556,
"s": 35203,
"text": "NOTE: limit() should not be used without .sort() as it may cause bugs later that are difficult to track down. This is because we can’t otherwise guarantee the order of the result. We would get different records at the top of the results which isn’t desirable. To make a query deterministic, they must give the same results every time they are executed."
},
{
"code": null,
"e": 35568,
"s": 35556,
"text": "anikakapoor"
},
{
"code": null,
"e": 35585,
"s": 35568,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 35598,
"s": 35585,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 35606,
"s": 35598,
"text": "Node.js"
},
{
"code": null,
"e": 35623,
"s": 35606,
"text": "Web Technologies"
},
{
"code": null,
"e": 35721,
"s": 35623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35775,
"s": 35721,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 35812,
"s": 35775,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 35852,
"s": 35812,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 35885,
"s": 35852,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 35920,
"s": 35885,
"text": "Express.js res.redirect() Function"
},
{
"code": null,
"e": 35960,
"s": 35920,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36005,
"s": 35960,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36048,
"s": 36005,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 36098,
"s": 36048,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Check if count of divisors is even or odd - GeeksforGeeks
|
20 Jan, 2022
Given a number “n”, find its total number of divisors are even or odd.Examples :
Input : n = 10
Output : Even
Input: n = 100
Output: Odd
Input: n = 125
Output: Even
A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd.Time complexity for such a solution would be O(sqrt(n))
C++
C
Java
Python3
C#
PHP
Javascript
// Naive Solution to find// if count of divisors// is even or odd#include <bits/stdc++.h>using namespace std; // Function to count// the divisorsvoid countDivisors(int n){ // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) cout << "Even" << endl; else cout << "Odd" << endl;} // Driver Codeint main(){ cout << "The count of divisor: "; countDivisors(10); return 0;} // This code is Contributed by SHUBHAMSINGH10
// Naive Solution to find// if count of divisors// is even or odd #include <math.h>#include <stdio.h> // Function to count// the divisorsvoid countDivisors(int n){ // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) printf("Even\n"); else printf("Odd\n");} // Driver Codeint main(){ printf("The count of divisor: "); countDivisors(10); return 0;}
// Naive Solution to find if count// of divisors is even or odd import java.io.*;import java.math.*; class GFG{ // Function to count // the divisors static void countDivisors(int n) { // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) System.out.println("Even"); else System.out.println("Odd"); } // Driver Code public static void main(String args[]) { System.out.print("The count of divisor: "); countDivisors(10); }}// This code is contributed by Nikita Tiwari
# Naive Solution to find if count # of divisors is even or oddimport math # Function to count# the divisorsdef countDivisors(n) : # Initialize count # of divisors count = 0 # Note that this loop # runs till square # root for i in range(1, (int)(math.sqrt(n)) + 2) : if (n % i == 0) : # If divisors are # equal, increment # count by one # Otherwise increment # count by 2 if( n // i == i) : count = count + 1 else : count = count + 2 if (count % 2 == 0) : print("Even") else : print("Odd") # Driver Codeprint("The count of divisor: ")countDivisors(10) # This code is contributed by Nikita Tiwari
// C# program using Naive// Solution to find if// count of divisors// is even or oddusing System; class GFG { // Function to count // the divisors static void countDivisors(int n) { // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= Math.Sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) Console.Write("Even"); else Console.Write("Odd"); } // Driver code public static void Main() { Console.Write("The count of divisor: "); countDivisors(10); }} // This code is contributed by Sam007.
<?php// Naive Solution to// find if count of// divisors is even// or odd // Function to count// the divisorsfunction countDivisors($n){ // Initialize count // of divisors $count = 0; // Note that this // loop runs till // square root for ($i = 1; $i <= sqrt($n) + 1; $i++) { if ($n % $i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 $count += ($n / $i == $i)? 1 : 2; } if ($count % 2 == 0) echo "Even\n"; else echo "Odd\n";} // Driver Code echo "The count of divisor: "; countDivisors(10); // This code is contributed by ajit.?>
<script> // Naive Solution to find// if count of divisors// is even or odd // Function to count// the divisorsfunction countDivisors(n){ // Initialize count // of divisors let count = 0; // Note that this // loop runs till // square root for (let i = 1; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (Math.floor(n / i) == i) ? 1 : 2; } if (count % 2 == 0) document.write("Even" + "<br>"); else document.write("Odd" + "<br>");} // Driver Code document.write("The count of divisor: "); countDivisors(10); // This code is contributed by Surbhi Tyagi. </script>
Output :
The count of divisor: Even
Efficient Solution: We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it’s a perfect square, then the number of divisors would be odd, else it’d be even.Below is the implementation of above idea :
C++
Java
Python3
C#
PHP
Javascript
// C++ program for// Efficient Solution to find// if count of divisors is// even or odd#include <bits/stdc++.h>using namespace std; // Function to find if count// of divisors is even or// oddvoid countDivisors(int n){ int root_n = sqrt(n); // If n is a perfect square, // then it has odd divisors if (root_n * root_n == n) printf("Odd\n"); else printf("Even\n");} // Driver Codeint main(){ cout << "The count of divisors" << " of 10 is: "; countDivisors(14); return 0;}
// Java program for Efficient// Solution to find if count of// divisors is even or oddimport java.io.*;import java.math.*; class GFG{ // Function to find if count // of divisors is even or // odd static void countDivisors(int n) { int root_n = (int)(Math.sqrt(n)); // If n is a perfect square, // then, it has odd divisors if (root_n * root_n == n) System.out.println("Odd"); else System.out.println("Even"); } // Driver code public static void main(String args[]) throws IOException { System.out.print("The count of" + "divisors of 10 is: "); countDivisors(10); }} // This code is contributed by Nikita Tiwari
# Python program for# Efficient Solution to find# find if count of divisors# is even or oddimport math def NumOfDivisor(n): if n < 1: return root_n = int(math.sqrt(n)) # If n is a perfect square, # then it has odd divisors if root_n**2 == n: print('Odd') else: print('Even') # Driver code if __name__ == '__main__': print("The count of divisor is:") NumOfDivisor(14) # This code is contributed by Yt R
// C# program for efficient// solution to find of// count of divisors is// even or oddusing System; class GFG { // Function to find if // count of divisors // is even or odd static void countDivisors(int n) { int root_n = (int)(Math.Sqrt(n)); // If n is a perfect square, // then, it has odd divisors if (root_n * root_n == n) Console.WriteLine("Odd"); else Console.WriteLine("Even"); } // Driver code public static void Main() { Console.Write("The count of divisors : "); countDivisors(10); }} // This code is contributed by Sam007.
<?php// Php program for Efficient// Solution to find if count of// divisors is even or odd // Function to find if count// of divisors is even or// odd function countDivisors($n){ $root_n = sqrt($n); // If n is a perfect square, // then it has odd divisors if ($root_n * $root_n == $n) echo "Odd\n"; else echo "Even\n";} // Driver Codeecho "The count of divisors of 10 is: "; countDivisors(10); // This code is contributed by ajit?>
<script> // JavaScript program for// Efficient Solution to find// if count of divisors// is even or odd // Function to count// the divisorsfunction countDivisors(n){ // Store square root of n let root_n = Math.sqrt(n); // If n is a perfect square, // then it has odd divisors if (root_n * root_n == n) document.write("Odd" + "<br>"); else document.write("Even" + "<br>"); } // Driver Code document.write("The count of divisor: "); countDivisors(10); // This code is contributed by Surbhi Tyagi. </script>
Output :
The count of divisor: Even
This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sam007
jit_t
SHUBHAMSINGH10
surbhityagi15
sudhanshugupta2019a
hridyakrishnar127
amartyaghoshgfg
divisors
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
Program for factorial of a number
The Knight's tour problem | Backtracking-1
Find minimum number of coins that make a given value
Program for Decimal to Binary Conversion
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 26137,
"s": 26109,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 26220,
"s": 26137,
"text": "Given a number “n”, find its total number of divisors are even or odd.Examples : "
},
{
"code": null,
"e": 26315,
"s": 26220,
"text": "Input : n = 10 \nOutput : Even\n\nInput: n = 100\nOutput: Odd\n\nInput: n = 125\nOutput: Even"
},
{
"code": null,
"e": 26486,
"s": 26317,
"text": "A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd.Time complexity for such a solution would be O(sqrt(n)) "
},
{
"code": null,
"e": 26490,
"s": 26486,
"text": "C++"
},
{
"code": null,
"e": 26492,
"s": 26490,
"text": "C"
},
{
"code": null,
"e": 26497,
"s": 26492,
"text": "Java"
},
{
"code": null,
"e": 26505,
"s": 26497,
"text": "Python3"
},
{
"code": null,
"e": 26508,
"s": 26505,
"text": "C#"
},
{
"code": null,
"e": 26512,
"s": 26508,
"text": "PHP"
},
{
"code": null,
"e": 26523,
"s": 26512,
"text": "Javascript"
},
{
"code": "// Naive Solution to find// if count of divisors// is even or odd#include <bits/stdc++.h>using namespace std; // Function to count// the divisorsvoid countDivisors(int n){ // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) cout << \"Even\" << endl; else cout << \"Odd\" << endl;} // Driver Codeint main(){ cout << \"The count of divisor: \"; countDivisors(10); return 0;} // This code is Contributed by SHUBHAMSINGH10",
"e": 27318,
"s": 26523,
"text": null
},
{
"code": "// Naive Solution to find// if count of divisors// is even or odd #include <math.h>#include <stdio.h> // Function to count// the divisorsvoid countDivisors(int n){ // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) printf(\"Even\\n\"); else printf(\"Odd\\n\");} // Driver Codeint main(){ printf(\"The count of divisor: \"); countDivisors(10); return 0;}",
"e": 28048,
"s": 27318,
"text": null
},
{
"code": "// Naive Solution to find if count// of divisors is even or odd import java.io.*;import java.math.*; class GFG{ // Function to count // the divisors static void countDivisors(int n) { // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) System.out.println(\"Even\"); else System.out.println(\"Odd\"); } // Driver Code public static void main(String args[]) { System.out.print(\"The count of divisor: \"); countDivisors(10); }}// This code is contributed by Nikita Tiwari",
"e": 29014,
"s": 28048,
"text": null
},
{
"code": "# Naive Solution to find if count # of divisors is even or oddimport math # Function to count# the divisorsdef countDivisors(n) : # Initialize count # of divisors count = 0 # Note that this loop # runs till square # root for i in range(1, (int)(math.sqrt(n)) + 2) : if (n % i == 0) : # If divisors are # equal, increment # count by one # Otherwise increment # count by 2 if( n // i == i) : count = count + 1 else : count = count + 2 if (count % 2 == 0) : print(\"Even\") else : print(\"Odd\") # Driver Codeprint(\"The count of divisor: \")countDivisors(10) # This code is contributed by Nikita Tiwari",
"e": 29785,
"s": 29014,
"text": null
},
{
"code": "// C# program using Naive// Solution to find if// count of divisors// is even or oddusing System; class GFG { // Function to count // the divisors static void countDivisors(int n) { // Initialize count // of divisors int count = 0; // Note that this // loop runs till // square root for (int i = 1; i <= Math.Sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (n / i == i) ? 1 : 2; } if (count % 2 == 0) Console.Write(\"Even\"); else Console.Write(\"Odd\"); } // Driver code public static void Main() { Console.Write(\"The count of divisor: \"); countDivisors(10); }} // This code is contributed by Sam007.",
"e": 30755,
"s": 29785,
"text": null
},
{
"code": "<?php// Naive Solution to// find if count of// divisors is even// or odd // Function to count// the divisorsfunction countDivisors($n){ // Initialize count // of divisors $count = 0; // Note that this // loop runs till // square root for ($i = 1; $i <= sqrt($n) + 1; $i++) { if ($n % $i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 $count += ($n / $i == $i)? 1 : 2; } if ($count % 2 == 0) echo \"Even\\n\"; else echo \"Odd\\n\";} // Driver Code echo \"The count of divisor: \"; countDivisors(10); // This code is contributed by ajit.?>",
"e": 31486,
"s": 30755,
"text": null
},
{
"code": "<script> // Naive Solution to find// if count of divisors// is even or odd // Function to count// the divisorsfunction countDivisors(n){ // Initialize count // of divisors let count = 0; // Note that this // loop runs till // square root for (let i = 1; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) // If divisors are // equal increment // count by one // Otherwise increment // count by 2 count += (Math.floor(n / i) == i) ? 1 : 2; } if (count % 2 == 0) document.write(\"Even\" + \"<br>\"); else document.write(\"Odd\" + \"<br>\");} // Driver Code document.write(\"The count of divisor: \"); countDivisors(10); // This code is contributed by Surbhi Tyagi. </script>",
"e": 32273,
"s": 31486,
"text": null
},
{
"code": null,
"e": 32283,
"s": 32273,
"text": "Output : "
},
{
"code": null,
"e": 32311,
"s": 32283,
"text": "The count of divisor: Even "
},
{
"code": null,
"e": 32633,
"s": 32311,
"text": "Efficient Solution: We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it’s a perfect square, then the number of divisors would be odd, else it’d be even.Below is the implementation of above idea : "
},
{
"code": null,
"e": 32637,
"s": 32633,
"text": "C++"
},
{
"code": null,
"e": 32642,
"s": 32637,
"text": "Java"
},
{
"code": null,
"e": 32650,
"s": 32642,
"text": "Python3"
},
{
"code": null,
"e": 32653,
"s": 32650,
"text": "C#"
},
{
"code": null,
"e": 32657,
"s": 32653,
"text": "PHP"
},
{
"code": null,
"e": 32668,
"s": 32657,
"text": "Javascript"
},
{
"code": "// C++ program for// Efficient Solution to find// if count of divisors is// even or odd#include <bits/stdc++.h>using namespace std; // Function to find if count// of divisors is even or// oddvoid countDivisors(int n){ int root_n = sqrt(n); // If n is a perfect square, // then it has odd divisors if (root_n * root_n == n) printf(\"Odd\\n\"); else printf(\"Even\\n\");} // Driver Codeint main(){ cout << \"The count of divisors\" << \" of 10 is: \"; countDivisors(14); return 0;}",
"e": 33186,
"s": 32668,
"text": null
},
{
"code": "// Java program for Efficient// Solution to find if count of// divisors is even or oddimport java.io.*;import java.math.*; class GFG{ // Function to find if count // of divisors is even or // odd static void countDivisors(int n) { int root_n = (int)(Math.sqrt(n)); // If n is a perfect square, // then, it has odd divisors if (root_n * root_n == n) System.out.println(\"Odd\"); else System.out.println(\"Even\"); } // Driver code public static void main(String args[]) throws IOException { System.out.print(\"The count of\" + \"divisors of 10 is: \"); countDivisors(10); }} // This code is contributed by Nikita Tiwari",
"e": 33929,
"s": 33186,
"text": null
},
{
"code": "# Python program for# Efficient Solution to find# find if count of divisors# is even or oddimport math def NumOfDivisor(n): if n < 1: return root_n = int(math.sqrt(n)) # If n is a perfect square, # then it has odd divisors if root_n**2 == n: print('Odd') else: print('Even') # Driver code if __name__ == '__main__': print(\"The count of divisor is:\") NumOfDivisor(14) # This code is contributed by Yt R ",
"e": 34399,
"s": 33929,
"text": null
},
{
"code": "// C# program for efficient// solution to find of// count of divisors is// even or oddusing System; class GFG { // Function to find if // count of divisors // is even or odd static void countDivisors(int n) { int root_n = (int)(Math.Sqrt(n)); // If n is a perfect square, // then, it has odd divisors if (root_n * root_n == n) Console.WriteLine(\"Odd\"); else Console.WriteLine(\"Even\"); } // Driver code public static void Main() { Console.Write(\"The count of divisors : \"); countDivisors(10); }} // This code is contributed by Sam007.",
"e": 35039,
"s": 34399,
"text": null
},
{
"code": "<?php// Php program for Efficient// Solution to find if count of// divisors is even or odd // Function to find if count// of divisors is even or// odd function countDivisors($n){ $root_n = sqrt($n); // If n is a perfect square, // then it has odd divisors if ($root_n * $root_n == $n) echo \"Odd\\n\"; else echo \"Even\\n\";} // Driver Codeecho \"The count of divisors of 10 is: \"; countDivisors(10); // This code is contributed by ajit?>",
"e": 35501,
"s": 35039,
"text": null
},
{
"code": "<script> // JavaScript program for// Efficient Solution to find// if count of divisors// is even or odd // Function to count// the divisorsfunction countDivisors(n){ // Store square root of n let root_n = Math.sqrt(n); // If n is a perfect square, // then it has odd divisors if (root_n * root_n == n) document.write(\"Odd\" + \"<br>\"); else document.write(\"Even\" + \"<br>\"); } // Driver Code document.write(\"The count of divisor: \"); countDivisors(10); // This code is contributed by Surbhi Tyagi. </script>",
"e": 36049,
"s": 35501,
"text": null
},
{
"code": null,
"e": 36060,
"s": 36049,
"text": "Output : "
},
{
"code": null,
"e": 36087,
"s": 36060,
"text": "The count of divisor: Even"
},
{
"code": null,
"e": 36261,
"s": 36089,
"text": "This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36270,
"s": 36263,
"text": "Sam007"
},
{
"code": null,
"e": 36276,
"s": 36270,
"text": "jit_t"
},
{
"code": null,
"e": 36291,
"s": 36276,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 36305,
"s": 36291,
"text": "surbhityagi15"
},
{
"code": null,
"e": 36325,
"s": 36305,
"text": "sudhanshugupta2019a"
},
{
"code": null,
"e": 36343,
"s": 36325,
"text": "hridyakrishnar127"
},
{
"code": null,
"e": 36359,
"s": 36343,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 36368,
"s": 36359,
"text": "divisors"
},
{
"code": null,
"e": 36381,
"s": 36368,
"text": "Mathematical"
},
{
"code": null,
"e": 36394,
"s": 36381,
"text": "Mathematical"
},
{
"code": null,
"e": 36492,
"s": 36394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36516,
"s": 36492,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 36559,
"s": 36516,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36573,
"s": 36559,
"text": "Prime Numbers"
},
{
"code": null,
"e": 36646,
"s": 36573,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 36667,
"s": 36646,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 36701,
"s": 36667,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 36744,
"s": 36701,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 36797,
"s": 36744,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 36838,
"s": 36797,
"text": "Program for Decimal to Binary Conversion"
}
] |
SQL Inner Join - GeeksforGeeks
|
10 May, 2021
Overview :Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. A join is a combination of a Cartesian product followed by a selection process. A join operation pairs two tuples from different relations if and only if a given join condition is satisfied. An inner join is the one in which only those tuples are included that satisfy some conditions. In this article, we will be using MySQL to demonstrate the working of SQL Inner Join.
Steps to implement the SQL Inner Join :Here, we will discuss the implementation of SQL Inner Join as follows.
Step-1: Creating Database :Here, we will create the database by using the following SQL query as follows.
CREATE DATABASE geeks;
Step-2: Using the Database :Here, we will use the geeks database.
USE geeks;
Step-3: Adding Tables :We will add 2 tables to the database as follows.
The first table will be the professor which will contain ID, the name of the professor, and salary.The second table will be taught which will contain the ID of the course, professor’s ID, and name of the course.
The first table will be the professor which will contain ID, the name of the professor, and salary.
The second table will be taught which will contain the ID of the course, professor’s ID, and name of the course.
Adding table professor –
CREATE TABLE professor(
ID int,
Name varchar(20),
Salary int
);
Adding table teaches –
CREATE TABLE teaches(
course_id int,
prof_id int,
course_name varchar(20)
);
Step-4: Description of the Tables :We can get the description of the 2 tables using the following SQL command as follows.
DESCRIBE professor
Output :
DESCRIBE teaches
Output :
Step-5: Inserting the rows :Here, we will insert the rows in both tables one by one as follows.
Inserting rows inside professor table –
INSERT INTO professor VALUES (1, 'Rohan', 57000);
INSERT INTO professor VALUES (2, 'Aryan', 45000);
INSERT INTO professor VALUES (3, 'Arpit', 60000);
INSERT INTO professor VALUES (4, 'Harsh', 50000);
INSERT INTO professor VALUES (5, 'Tara', 55000);
Output :
Inserting rows inside teaches table –
INSERT INTO teaches VALUES (1, 1, 'English');
INSERT INTO teaches VALUES (1, 3, 'Physics');
INSERT INTO teaches VALUES (2, 4, 'Chemistry');
INSERT INTO teaches VALUES (2, 5, 'Mathematics');
Output :
Step-6: Current State of the Tables :Verifying the data in both tables as follows.
professor Table –
SELECT * FROM professor;
Output :
teaches Table –
SELECT * FROM teaches;
Output :
Step-7: INNER JOIN Query :
Syntax :
SELECT comma_separated_column_names
FROM table1 INNER JOIN table2 ON condition
Example –
SELECT teaches.course_id, teaches.prof_id, professor.Name, professor.Salary
FROM professor INNER JOIN teaches ON professor.ID = teaches.prof_id;
Output :Using the Inner Join we are able to combine the information in the two tables based on a condition and the tuples in the Cartesian product of the two tables that do not satisfy the required condition are not included in the resulting table.
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25513,
"s": 25485,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 26066,
"s": 25513,
"text": "Overview :Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. A join is a combination of a Cartesian product followed by a selection process. A join operation pairs two tuples from different relations if and only if a given join condition is satisfied. An inner join is the one in which only those tuples are included that satisfy some conditions. In this article, we will be using MySQL to demonstrate the working of SQL Inner Join."
},
{
"code": null,
"e": 26176,
"s": 26066,
"text": "Steps to implement the SQL Inner Join :Here, we will discuss the implementation of SQL Inner Join as follows."
},
{
"code": null,
"e": 26282,
"s": 26176,
"text": "Step-1: Creating Database :Here, we will create the database by using the following SQL query as follows."
},
{
"code": null,
"e": 26305,
"s": 26282,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 26371,
"s": 26305,
"text": "Step-2: Using the Database :Here, we will use the geeks database."
},
{
"code": null,
"e": 26382,
"s": 26371,
"text": "USE geeks;"
},
{
"code": null,
"e": 26454,
"s": 26382,
"text": "Step-3: Adding Tables :We will add 2 tables to the database as follows."
},
{
"code": null,
"e": 26666,
"s": 26454,
"text": "The first table will be the professor which will contain ID, the name of the professor, and salary.The second table will be taught which will contain the ID of the course, professor’s ID, and name of the course."
},
{
"code": null,
"e": 26766,
"s": 26666,
"text": "The first table will be the professor which will contain ID, the name of the professor, and salary."
},
{
"code": null,
"e": 26879,
"s": 26766,
"text": "The second table will be taught which will contain the ID of the course, professor’s ID, and name of the course."
},
{
"code": null,
"e": 26904,
"s": 26879,
"text": "Adding table professor –"
},
{
"code": null,
"e": 26980,
"s": 26904,
"text": "CREATE TABLE professor(\n ID int,\n Name varchar(20),\n Salary int\n);"
},
{
"code": null,
"e": 27003,
"s": 26980,
"text": "Adding table teaches –"
},
{
"code": null,
"e": 27092,
"s": 27003,
"text": "CREATE TABLE teaches(\n course_id int,\n prof_id int,\n course_name varchar(20)\n);"
},
{
"code": null,
"e": 27214,
"s": 27092,
"text": "Step-4: Description of the Tables :We can get the description of the 2 tables using the following SQL command as follows."
},
{
"code": null,
"e": 27233,
"s": 27214,
"text": "DESCRIBE professor"
},
{
"code": null,
"e": 27242,
"s": 27233,
"text": "Output :"
},
{
"code": null,
"e": 27259,
"s": 27242,
"text": "DESCRIBE teaches"
},
{
"code": null,
"e": 27268,
"s": 27259,
"text": "Output :"
},
{
"code": null,
"e": 27364,
"s": 27268,
"text": "Step-5: Inserting the rows :Here, we will insert the rows in both tables one by one as follows."
},
{
"code": null,
"e": 27404,
"s": 27364,
"text": "Inserting rows inside professor table –"
},
{
"code": null,
"e": 27653,
"s": 27404,
"text": "INSERT INTO professor VALUES (1, 'Rohan', 57000);\nINSERT INTO professor VALUES (2, 'Aryan', 45000);\nINSERT INTO professor VALUES (3, 'Arpit', 60000);\nINSERT INTO professor VALUES (4, 'Harsh', 50000);\nINSERT INTO professor VALUES (5, 'Tara', 55000);"
},
{
"code": null,
"e": 27662,
"s": 27653,
"text": "Output :"
},
{
"code": null,
"e": 27700,
"s": 27662,
"text": "Inserting rows inside teaches table –"
},
{
"code": null,
"e": 27890,
"s": 27700,
"text": "INSERT INTO teaches VALUES (1, 1, 'English');\nINSERT INTO teaches VALUES (1, 3, 'Physics');\nINSERT INTO teaches VALUES (2, 4, 'Chemistry');\nINSERT INTO teaches VALUES (2, 5, 'Mathematics');"
},
{
"code": null,
"e": 27899,
"s": 27890,
"text": "Output :"
},
{
"code": null,
"e": 27982,
"s": 27899,
"text": "Step-6: Current State of the Tables :Verifying the data in both tables as follows."
},
{
"code": null,
"e": 28000,
"s": 27982,
"text": "professor Table –"
},
{
"code": null,
"e": 28025,
"s": 28000,
"text": "SELECT * FROM professor;"
},
{
"code": null,
"e": 28034,
"s": 28025,
"text": "Output :"
},
{
"code": null,
"e": 28050,
"s": 28034,
"text": "teaches Table –"
},
{
"code": null,
"e": 28073,
"s": 28050,
"text": "SELECT * FROM teaches;"
},
{
"code": null,
"e": 28082,
"s": 28073,
"text": "Output :"
},
{
"code": null,
"e": 28109,
"s": 28082,
"text": "Step-7: INNER JOIN Query :"
},
{
"code": null,
"e": 28118,
"s": 28109,
"text": "Syntax :"
},
{
"code": null,
"e": 28197,
"s": 28118,
"text": "SELECT comma_separated_column_names\nFROM table1 INNER JOIN table2 ON condition"
},
{
"code": null,
"e": 28207,
"s": 28197,
"text": "Example –"
},
{
"code": null,
"e": 28352,
"s": 28207,
"text": "SELECT teaches.course_id, teaches.prof_id, professor.Name, professor.Salary\nFROM professor INNER JOIN teaches ON professor.ID = teaches.prof_id;"
},
{
"code": null,
"e": 28601,
"s": 28352,
"text": "Output :Using the Inner Join we are able to combine the information in the two tables based on a condition and the tuples in the Cartesian product of the two tables that do not satisfy the required condition are not included in the resulting table."
},
{
"code": null,
"e": 28610,
"s": 28601,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 28617,
"s": 28610,
"text": "Picked"
},
{
"code": null,
"e": 28621,
"s": 28617,
"text": "SQL"
},
{
"code": null,
"e": 28625,
"s": 28621,
"text": "SQL"
},
{
"code": null,
"e": 28723,
"s": 28625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28789,
"s": 28723,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 28804,
"s": 28789,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 28861,
"s": 28804,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 28893,
"s": 28861,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 28971,
"s": 28893,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 29007,
"s": 28971,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 29024,
"s": 29007,
"text": "SQL using Python"
},
{
"code": null,
"e": 29090,
"s": 29024,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 29152,
"s": 29090,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
ML | Multiple Linear Regression using Python - GeeksforGeeks
|
14 Sep, 2021
Linear Regression:
It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables.
These are of two types:
Simple linear RegressionMultiple Linear Regression
Simple linear Regression
Multiple Linear Regression
Let’s Discuss Multiple Linear Regression using Python.
Multiple Linear Regression attempts to model the relationship between two or more features and a response by fitting a linear equation to observed data. The steps to perform multiple linear Regression are almost similar to that of simple linear Regression. The Difference Lies in the evaluation. We can use it to find out which factor has the highest impact on the predicted output and now different variables relate to each other.
Here : Y = b0 + b1 * x1 + b2 * x2 + b3 * x3 + ...... bn * xn Y = Dependent variable and x1, x2, x3, ...... xn = multiple independent variables
Assumption of Regression Model :
Linearity: The relationship between dependent and independent variables should be linear.
Homoscedasticity: Constant variance of the errors should be maintained.
Multivariate normality: Multiple Regression assumes that the residuals are normally distributed.
Lack of Multicollinearity: It is assumed that there is little or no multicollinearity in the data.
Dummy Variable:
As we know in the Multiple Regression Model we use a lot of categorical data. Using Categorical Data is a good method to include non-numeric data into the respective Regression Model. Categorical Data refers to data values that represent categories-data values with the fixed and unordered number of values, for instance, gender(male/female). In the regression model, these values can be represented by Dummy Variables. These variables consist of values such as 0 or 1 representing the presence and absence of categorical values.
Dummy Variable Trap:The Dummy Variable Trap is a condition in which two or more are Highly Correlated. In the simple term, we can say that one variable can be predicted from the prediction of the other. The solution of the Dummy Variable Trap is to drop one of the categorical variables. So if there are m Dummy variables then m-1 variables are used in the model.
D2 = D1-1
Here D2, D1 = Dummy Variables
All-in
Backward-Elimination
Forward Selection
Bidirectional Elimination
Score Comparison
Step #1: Select a significant level to start in the model. Step #2: Fit the full model with all possible predictors. Step #3: Consider the predictor with the highest P-value. If P > SL go to STEP 4, otherwise the model is Ready. Step #4: Remove the predictor. Step #5: Fit the model without this variable.
Step #1 : Select a significance level to enter the model(e.g. SL = 0.05) Step #2: Fit all simple regression models y~ x(n). Select the one with the lowest P-value. Step #3: Keep this variable and fit all possible models with one extra predictor added to the one(s) you already have. Step #4: Consider the predictor with the lowest P-value. If P < SL, go to Step #3, otherwise the model is Ready.
Step #1: Data Pre Processing
Importing The Libraries.Importing the Data Set.Encoding the Categorical Data.Avoiding the Dummy Variable Trap.Splitting the Data set into Training Set and Test Set.
Importing The Libraries.
Importing the Data Set.
Encoding the Categorical Data.
Avoiding the Dummy Variable Trap.
Splitting the Data set into Training Set and Test Set.
Step #2: Fitting Multiple Linear Regression to the Training set Step #3: Predicting the Test set results.
Code 1 :
Python3
import numpy as npimport matplotlib as mplfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt def generate_dataset(n): x = [] y = [] random_x1 = np.random.rand() random_x2 = np.random.rand() for i in range(n): x1 = i x2 = i/2 + np.random.rand()*n x.append([1, x1, x2]) y.append(random_x1 * x1 + random_x2 * x2 + 1) return np.array(x), np.array(y) x, y = generate_dataset(200) mpl.rcParams['legend.fontsize'] = 12 fig = plt.figure()ax = fig.gca(projection ='3d') ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5)ax.legend()ax.view_init(45, 0) plt.show()
Output:
Code 2:
Python3
def mse(coef, x, y): return np.mean((np.dot(x, coef) - y)**2)/2 def gradients(coef, x, y): return np.mean(x.transpose()*(np.dot(x, coef) - y), axis = 1) def multilinear_regression(coef, x, y, lr, b1 = 0.9, b2 = 0.999, epsilon = 1e-8): prev_error = 0 m_coef = np.zeros(coef.shape) v_coef = np.zeros(coef.shape) moment_m_coef = np.zeros(coef.shape) moment_v_coef = np.zeros(coef.shape) t = 0 while True: error = mse(coef, x, y) if abs(error - prev_error) <= epsilon: break prev_error = error grad = gradients(coef, x, y) t += 1 m_coef = b1 * m_coef + (1-b1)*grad v_coef = b2 * v_coef + (1-b2)*grad**2 moment_m_coef = m_coef / (1-b1**t) moment_v_coef = v_coef / (1-b2**t) delta = ((lr / moment_v_coef**0.5 + 1e-8) * (b1 * moment_m_coef + (1-b1)*grad/(1-b1**t))) coef = np.subtract(coef, delta) return coef coef = np.array([0, 0, 0])c = multilinear_regression(coef, x, y, 1e-1)fig = plt.figure()ax = fig.gca(projection ='3d') ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5, color ="dodgerblue") ax.scatter(x[:, 1], x[:, 2], c[0] + c[1]*x[:, 1] + c[2]*x[:, 2], label ='regression', s = 5, color ="orange") ax.view_init(45, 0)ax.legend()plt.show()
Output:
vaibhavsinghtanwar
Regression
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Python | Decision tree implementation
ML | Underfitting and Overfitting
Search Algorithms in AI
Clustering in Machine Learning
Intuition of Adam Optimizer
Random Forest Regression in Python
Elbow Method for optimal value of k in KMeans
|
[
{
"code": null,
"e": 25887,
"s": 25859,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25907,
"s": 25887,
"text": "Linear Regression: "
},
{
"code": null,
"e": 26101,
"s": 25907,
"text": "It is the basic and commonly used type for predictive analysis. It is a statistical approach to modeling the relationship between a dependent variable and a given set of independent variables. "
},
{
"code": null,
"e": 26126,
"s": 26101,
"text": "These are of two types: "
},
{
"code": null,
"e": 26177,
"s": 26126,
"text": "Simple linear RegressionMultiple Linear Regression"
},
{
"code": null,
"e": 26202,
"s": 26177,
"text": "Simple linear Regression"
},
{
"code": null,
"e": 26229,
"s": 26202,
"text": "Multiple Linear Regression"
},
{
"code": null,
"e": 26284,
"s": 26229,
"text": "Let’s Discuss Multiple Linear Regression using Python."
},
{
"code": null,
"e": 26717,
"s": 26284,
"text": "Multiple Linear Regression attempts to model the relationship between two or more features and a response by fitting a linear equation to observed data. The steps to perform multiple linear Regression are almost similar to that of simple linear Regression. The Difference Lies in the evaluation. We can use it to find out which factor has the highest impact on the predicted output and now different variables relate to each other. "
},
{
"code": null,
"e": 26861,
"s": 26717,
"text": "Here : Y = b0 + b1 * x1 + b2 * x2 + b3 * x3 + ...... bn * xn Y = Dependent variable and x1, x2, x3, ...... xn = multiple independent variables "
},
{
"code": null,
"e": 26895,
"s": 26861,
"text": "Assumption of Regression Model : "
},
{
"code": null,
"e": 26985,
"s": 26895,
"text": "Linearity: The relationship between dependent and independent variables should be linear."
},
{
"code": null,
"e": 27057,
"s": 26985,
"text": "Homoscedasticity: Constant variance of the errors should be maintained."
},
{
"code": null,
"e": 27154,
"s": 27057,
"text": "Multivariate normality: Multiple Regression assumes that the residuals are normally distributed."
},
{
"code": null,
"e": 27253,
"s": 27154,
"text": "Lack of Multicollinearity: It is assumed that there is little or no multicollinearity in the data."
},
{
"code": null,
"e": 27269,
"s": 27253,
"text": "Dummy Variable:"
},
{
"code": null,
"e": 27801,
"s": 27269,
"text": "As we know in the Multiple Regression Model we use a lot of categorical data. Using Categorical Data is a good method to include non-numeric data into the respective Regression Model. Categorical Data refers to data values that represent categories-data values with the fixed and unordered number of values, for instance, gender(male/female). In the regression model, these values can be represented by Dummy Variables. These variables consist of values such as 0 or 1 representing the presence and absence of categorical values. "
},
{
"code": null,
"e": 28166,
"s": 27801,
"text": "Dummy Variable Trap:The Dummy Variable Trap is a condition in which two or more are Highly Correlated. In the simple term, we can say that one variable can be predicted from the prediction of the other. The solution of the Dummy Variable Trap is to drop one of the categorical variables. So if there are m Dummy variables then m-1 variables are used in the model. "
},
{
"code": null,
"e": 28211,
"s": 28166,
"text": " D2 = D1-1 \n Here D2, D1 = Dummy Variables"
},
{
"code": null,
"e": 28218,
"s": 28211,
"text": "All-in"
},
{
"code": null,
"e": 28239,
"s": 28218,
"text": "Backward-Elimination"
},
{
"code": null,
"e": 28257,
"s": 28239,
"text": "Forward Selection"
},
{
"code": null,
"e": 28283,
"s": 28257,
"text": "Bidirectional Elimination"
},
{
"code": null,
"e": 28300,
"s": 28283,
"text": "Score Comparison"
},
{
"code": null,
"e": 28607,
"s": 28300,
"text": "Step #1: Select a significant level to start in the model. Step #2: Fit the full model with all possible predictors. Step #3: Consider the predictor with the highest P-value. If P > SL go to STEP 4, otherwise the model is Ready. Step #4: Remove the predictor. Step #5: Fit the model without this variable. "
},
{
"code": null,
"e": 29004,
"s": 28607,
"text": "Step #1 : Select a significance level to enter the model(e.g. SL = 0.05) Step #2: Fit all simple regression models y~ x(n). Select the one with the lowest P-value. Step #3: Keep this variable and fit all possible models with one extra predictor added to the one(s) you already have. Step #4: Consider the predictor with the lowest P-value. If P < SL, go to Step #3, otherwise the model is Ready. "
},
{
"code": null,
"e": 29034,
"s": 29004,
"text": "Step #1: Data Pre Processing "
},
{
"code": null,
"e": 29199,
"s": 29034,
"text": "Importing The Libraries.Importing the Data Set.Encoding the Categorical Data.Avoiding the Dummy Variable Trap.Splitting the Data set into Training Set and Test Set."
},
{
"code": null,
"e": 29224,
"s": 29199,
"text": "Importing The Libraries."
},
{
"code": null,
"e": 29248,
"s": 29224,
"text": "Importing the Data Set."
},
{
"code": null,
"e": 29279,
"s": 29248,
"text": "Encoding the Categorical Data."
},
{
"code": null,
"e": 29313,
"s": 29279,
"text": "Avoiding the Dummy Variable Trap."
},
{
"code": null,
"e": 29368,
"s": 29313,
"text": "Splitting the Data set into Training Set and Test Set."
},
{
"code": null,
"e": 29475,
"s": 29368,
"text": "Step #2: Fitting Multiple Linear Regression to the Training set Step #3: Predicting the Test set results. "
},
{
"code": null,
"e": 29485,
"s": 29475,
"text": "Code 1 : "
},
{
"code": null,
"e": 29493,
"s": 29485,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib as mplfrom mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as plt def generate_dataset(n): x = [] y = [] random_x1 = np.random.rand() random_x2 = np.random.rand() for i in range(n): x1 = i x2 = i/2 + np.random.rand()*n x.append([1, x1, x2]) y.append(random_x1 * x1 + random_x2 * x2 + 1) return np.array(x), np.array(y) x, y = generate_dataset(200) mpl.rcParams['legend.fontsize'] = 12 fig = plt.figure()ax = fig.gca(projection ='3d') ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5)ax.legend()ax.view_init(45, 0) plt.show()",
"e": 30112,
"s": 29493,
"text": null
},
{
"code": null,
"e": 30122,
"s": 30112,
"text": "Output: "
},
{
"code": null,
"e": 30131,
"s": 30122,
"text": "Code 2: "
},
{
"code": null,
"e": 30139,
"s": 30131,
"text": "Python3"
},
{
"code": "def mse(coef, x, y): return np.mean((np.dot(x, coef) - y)**2)/2 def gradients(coef, x, y): return np.mean(x.transpose()*(np.dot(x, coef) - y), axis = 1) def multilinear_regression(coef, x, y, lr, b1 = 0.9, b2 = 0.999, epsilon = 1e-8): prev_error = 0 m_coef = np.zeros(coef.shape) v_coef = np.zeros(coef.shape) moment_m_coef = np.zeros(coef.shape) moment_v_coef = np.zeros(coef.shape) t = 0 while True: error = mse(coef, x, y) if abs(error - prev_error) <= epsilon: break prev_error = error grad = gradients(coef, x, y) t += 1 m_coef = b1 * m_coef + (1-b1)*grad v_coef = b2 * v_coef + (1-b2)*grad**2 moment_m_coef = m_coef / (1-b1**t) moment_v_coef = v_coef / (1-b2**t) delta = ((lr / moment_v_coef**0.5 + 1e-8) * (b1 * moment_m_coef + (1-b1)*grad/(1-b1**t))) coef = np.subtract(coef, delta) return coef coef = np.array([0, 0, 0])c = multilinear_regression(coef, x, y, 1e-1)fig = plt.figure()ax = fig.gca(projection ='3d') ax.scatter(x[:, 1], x[:, 2], y, label ='y', s = 5, color =\"dodgerblue\") ax.scatter(x[:, 1], x[:, 2], c[0] + c[1]*x[:, 1] + c[2]*x[:, 2], label ='regression', s = 5, color =\"orange\") ax.view_init(45, 0)ax.legend()plt.show()",
"e": 31455,
"s": 30139,
"text": null
},
{
"code": null,
"e": 31465,
"s": 31455,
"text": "Output: "
},
{
"code": null,
"e": 31486,
"s": 31467,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 31497,
"s": 31486,
"text": "Regression"
},
{
"code": null,
"e": 31514,
"s": 31497,
"text": "Machine Learning"
},
{
"code": null,
"e": 31531,
"s": 31514,
"text": "Machine Learning"
},
{
"code": null,
"e": 31629,
"s": 31531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31669,
"s": 31629,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 31710,
"s": 31669,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 31743,
"s": 31710,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 31781,
"s": 31743,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 31815,
"s": 31781,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 31839,
"s": 31815,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 31870,
"s": 31839,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 31898,
"s": 31870,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 31933,
"s": 31898,
"text": "Random Forest Regression in Python"
}
] |
How to Create a Basic Color Picker Tool in Android? - GeeksforGeeks
|
22 Oct, 2020
There are many open-source color picker tools for android applications to choose from. In this discussion, At the end of this article, one will be able to implement the color picker tool in the android application, have a look at the following image to get an overview of the discussion. In this article, it’s been discussed to implement the very basic color picker tool.
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
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: Adding the AmbilWarna color picker library dependency
AmbilWarna is an open-source color picker library which can be found here. Which has only one release and this is one of the final releases.
Now adding its dependency to the app-level gradle file.
implementation ‘com.github.yukuku:ambilwarna:2.0.1’
Make sure the system should be connected to the network (so that it downloads the required files) and after invoking the dependency click on the “Sync Now” button.
Refer to the following image to locate the app-level gradle file and invoke the dependency.
Step 3: Working with the actvity_main.xml file
Next, go to the activity_main.xml file, which represents the UI of the project.
Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--Give all widgets, the proper id to handle them in MainActivity.java--> <!--GeeksforGeeks Text--> <TextView android:id="@+id/gfg_heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:text="GeeksforGeeks" android:textSize="42sp" android:textStyle="bold" /> <!--Pick color Button--> <Button android:id="@+id/pick_color_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:layout_marginStart="32dp" android:layout_marginEnd="32dp" android:text="Pick Color" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:textSize="18sp" android:text="Your picked color is:" /> <!--sample view to preview selected color by user--> <!--by default this has been set to darker gery--> <!--this can be overridden after user chose the color from color picker--> <!--which has been handled in the MainActivity.java--> <View android:id="@+id/preview_selected_color" android:layout_width="48dp" android:layout_height="48dp" android:layout_gravity="center" android:background="@android:color/darker_gray" android:layout_marginTop="8dp" /> <!--set color button to overwrite the color for GeeksforGeeks text--> <Button android:id="@+id/set_color_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="32dp" android:layout_marginStart="32dp" android:layout_marginEnd="32dp" android:text="Set Color" /> </LinearLayout>
Output UI:
Before going to handle the color picker tool dialog functionality, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code.
Step 4: Working with the MainActivity.java file
Finally, 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.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import yuku.ambilwarna.AmbilWarnaDialog; public class MainActivity extends AppCompatActivity { // text view variable to set the color for GFG text private TextView gfgTextView; // two buttons to open color picker dialog and one to // set the color for GFG text private Button mSetColorButton, mPickColorButton; // view box to preview the selected color private View mColorPreview; // this is the default color of the preview box private int mDefaultColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the GFG text with appropriate ID gfgTextView = findViewById(R.id.gfg_heading); // register two of the buttons with their // appropriate IDs mPickColorButton = findViewById(R.id.pick_color_button); mSetColorButton = findViewById(R.id.set_color_button); // and also register the view which shows the // preview of the color chosen by the user mColorPreview = findViewById(R.id.preview_selected_color); // set the default color to 0 as it is black mDefaultColor = 0; // button open the AmbilWanra color picker dialog. mPickColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // to make code look cleaner the color // picker dialog functionality are // handled in openColorPickerDialogue() // function openColorPickerDialogue(); } }); // button to set the color GFG text mSetColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // as the mDefaultColor is the global // variable its value will be changed as // soon as ok button is clicked from the // color picker dialog. gfgTextView.setTextColor(mDefaultColor); } }); } // the dialog functionality is handled separately // using openColorPickerDialog this is triggered as // soon as the user clicks on the Pick Color button And // the AmbilWarnaDialog has 2 methods to be overridden // those are onCancel and onOk which handle the "Cancel" // and "OK" button of color picker dialog public void openColorPickerDialogue() { // the AmbilWarnaDialog callback needs 3 parameters // one is the context, second is default color, final AmbilWarnaDialog colorPickerDialogue = new AmbilWarnaDialog(this, mDefaultColor, new AmbilWarnaDialog.OnAmbilWarnaListener() { @Override public void onCancel(AmbilWarnaDialog dialog) { // leave this function body as // blank, as the dialog // automatically closes when // clicked on cancel button } @Override public void onOk(AmbilWarnaDialog dialog, int color) { // change the mDefaultColor to // change the GFG text color as // it is returned when the OK // button is clicked from the // color picker dialog mDefaultColor = color; // now change the picked color // preview box to mDefaultColor mColorPreview.setBackgroundColor(mDefaultColor); } }); colorPickerDialogue.show(); }}
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Resource Raw Folder in Android Studio
Broadcast Receiver in Android With Example
Services in Android with Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
|
[
{
"code": null,
"e": 25993,
"s": 25965,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 26365,
"s": 25993,
"text": "There are many open-source color picker tools for android applications to choose from. In this discussion, At the end of this article, one will be able to implement the color picker tool in the android application, have a look at the following image to get an overview of the discussion. In this article, it’s been discussed to implement the very basic color picker tool."
},
{
"code": null,
"e": 26529,
"s": 26365,
"text": "A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language."
},
{
"code": null,
"e": 26558,
"s": 26529,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 26670,
"s": 26558,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. "
},
{
"code": null,
"e": 26721,
"s": 26670,
"text": "Note that select Java as the programming language."
},
{
"code": null,
"e": 26783,
"s": 26721,
"text": "Step 2: Adding the AmbilWarna color picker library dependency"
},
{
"code": null,
"e": 26924,
"s": 26783,
"text": "AmbilWarna is an open-source color picker library which can be found here. Which has only one release and this is one of the final releases."
},
{
"code": null,
"e": 26980,
"s": 26924,
"text": "Now adding its dependency to the app-level gradle file."
},
{
"code": null,
"e": 27032,
"s": 26980,
"text": "implementation ‘com.github.yukuku:ambilwarna:2.0.1’"
},
{
"code": null,
"e": 27196,
"s": 27032,
"text": "Make sure the system should be connected to the network (so that it downloads the required files) and after invoking the dependency click on the “Sync Now” button."
},
{
"code": null,
"e": 27288,
"s": 27196,
"text": "Refer to the following image to locate the app-level gradle file and invoke the dependency."
},
{
"code": null,
"e": 27335,
"s": 27288,
"text": "Step 3: Working with the actvity_main.xml file"
},
{
"code": null,
"e": 27415,
"s": 27335,
"text": "Next, go to the activity_main.xml file, which represents the UI of the project."
},
{
"code": null,
"e": 27539,
"s": 27415,
"text": "Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 27543,
"s": 27539,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--Give all widgets, the proper id to handle them in MainActivity.java--> <!--GeeksforGeeks Text--> <TextView android:id=\"@+id/gfg_heading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:text=\"GeeksforGeeks\" android:textSize=\"42sp\" android:textStyle=\"bold\" /> <!--Pick color Button--> <Button android:id=\"@+id/pick_color_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:layout_marginStart=\"32dp\" android:layout_marginEnd=\"32dp\" android:text=\"Pick Color\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:textSize=\"18sp\" android:text=\"Your picked color is:\" /> <!--sample view to preview selected color by user--> <!--by default this has been set to darker gery--> <!--this can be overridden after user chose the color from color picker--> <!--which has been handled in the MainActivity.java--> <View android:id=\"@+id/preview_selected_color\" android:layout_width=\"48dp\" android:layout_height=\"48dp\" android:layout_gravity=\"center\" android:background=\"@android:color/darker_gray\" android:layout_marginTop=\"8dp\" /> <!--set color button to overwrite the color for GeeksforGeeks text--> <Button android:id=\"@+id/set_color_button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"32dp\" android:layout_marginStart=\"32dp\" android:layout_marginEnd=\"32dp\" android:text=\"Set Color\" /> </LinearLayout>",
"e": 29898,
"s": 27543,
"text": null
},
{
"code": null,
"e": 29909,
"s": 29898,
"text": "Output UI:"
},
{
"code": null,
"e": 30117,
"s": 29909,
"text": "Before going to handle the color picker tool dialog functionality, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code."
},
{
"code": null,
"e": 30165,
"s": 30117,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 30241,
"s": 30165,
"text": "Finally, go to the MainActivity.java file, and refer to the following code."
},
{
"code": null,
"e": 30365,
"s": 30241,
"text": "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": 30370,
"s": 30365,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import yuku.ambilwarna.AmbilWarnaDialog; public class MainActivity extends AppCompatActivity { // text view variable to set the color for GFG text private TextView gfgTextView; // two buttons to open color picker dialog and one to // set the color for GFG text private Button mSetColorButton, mPickColorButton; // view box to preview the selected color private View mColorPreview; // this is the default color of the preview box private int mDefaultColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // register the GFG text with appropriate ID gfgTextView = findViewById(R.id.gfg_heading); // register two of the buttons with their // appropriate IDs mPickColorButton = findViewById(R.id.pick_color_button); mSetColorButton = findViewById(R.id.set_color_button); // and also register the view which shows the // preview of the color chosen by the user mColorPreview = findViewById(R.id.preview_selected_color); // set the default color to 0 as it is black mDefaultColor = 0; // button open the AmbilWanra color picker dialog. mPickColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // to make code look cleaner the color // picker dialog functionality are // handled in openColorPickerDialogue() // function openColorPickerDialogue(); } }); // button to set the color GFG text mSetColorButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // as the mDefaultColor is the global // variable its value will be changed as // soon as ok button is clicked from the // color picker dialog. gfgTextView.setTextColor(mDefaultColor); } }); } // the dialog functionality is handled separately // using openColorPickerDialog this is triggered as // soon as the user clicks on the Pick Color button And // the AmbilWarnaDialog has 2 methods to be overridden // those are onCancel and onOk which handle the \"Cancel\" // and \"OK\" button of color picker dialog public void openColorPickerDialogue() { // the AmbilWarnaDialog callback needs 3 parameters // one is the context, second is default color, final AmbilWarnaDialog colorPickerDialogue = new AmbilWarnaDialog(this, mDefaultColor, new AmbilWarnaDialog.OnAmbilWarnaListener() { @Override public void onCancel(AmbilWarnaDialog dialog) { // leave this function body as // blank, as the dialog // automatically closes when // clicked on cancel button } @Override public void onOk(AmbilWarnaDialog dialog, int color) { // change the mDefaultColor to // change the GFG text color as // it is returned when the OK // button is clicked from the // color picker dialog mDefaultColor = color; // now change the picked color // preview box to mDefaultColor mColorPreview.setBackgroundColor(mDefaultColor); } }); colorPickerDialogue.show(); }}",
"e": 34474,
"s": 30370,
"text": null
},
{
"code": null,
"e": 34482,
"s": 34474,
"text": "android"
},
{
"code": null,
"e": 34490,
"s": 34482,
"text": "Android"
},
{
"code": null,
"e": 34495,
"s": 34490,
"text": "Java"
},
{
"code": null,
"e": 34500,
"s": 34495,
"text": "Java"
},
{
"code": null,
"e": 34508,
"s": 34500,
"text": "Android"
},
{
"code": null,
"e": 34606,
"s": 34508,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34664,
"s": 34606,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 34702,
"s": 34664,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 34745,
"s": 34702,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 34778,
"s": 34745,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 34809,
"s": 34778,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 34824,
"s": 34809,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34868,
"s": 34824,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34890,
"s": 34868,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34941,
"s": 34890,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Queries for greater than and not less than - GeeksforGeeks
|
26 Mar, 2021
Given an array of N integers. There will be Q queries, each include two integer of form q and x, 0 <= q <= 1. Queries are of two types:
In first query (q = 0), the task is to find count of integers which are not less than x (OR greater than or equal to x).
In second query (q = 1), the task is to find count of integers greater than x.
Examples:
Input : arr[] = { 1, 2, 3, 4 } and Q = 3
Query 1: 0 5
Query 2: 1 3
Query 3: 0 3
Output :0
1
2
Explanation:
x = 5, q = 0 : There are no elements greater than or equal to it.
x = 3, q = 1 : There is one element greater than 3 which is 4.
x = 3, q = 0 : There are two elements greater than or equal to 3.
Method 1: A Naive approach can be for each query, traverse the whole array and count integers less or greater than x, depending on q. Time Complexity for this approach will be O(Q*N).Method 2: An efficient approach can be sort the array and use binary search for each query. This will take O(NlogN + QlogN).Below is the implementation of this approach :
C++
Java
Python3
C#
PHP
Javascript
// C++ to find number of integer less or greater given// integer queries#include<bits/stdc++.h>using namespace std; // Return the index of integer which are not less than x// (or greater than or equal to x)int lower_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer which are greater than x.int upper_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} void query(int arr[], int n, int type, int x){ // Counting number of integer which are greater than x. if (type) cout << n - upper_bound(arr, 0, n, x) << endl; // Counting number of integer which are not less than x // (Or greater than or equal to x) else cout << n - lower_bound(arr, 0, n, x) << endl;} // Driven Programint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr + n); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3); return 0;}
// Java to find number of integer// less or greater given// integer queriesimport java.util.Arrays;class GFG{// Return the index of integer// which are not less than x// (or greater than or equal// to x)static int lower_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.static int upper_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} static void query(int arr[], int n, int type, int x){ // Counting number of integer // which are greater than x. if (type==1) System.out.println(n - upper_bound(arr, 0, n, x)); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else System.out.println(n - lower_bound(arr, 0, n, x));} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 3, 4 }; int n = arr.length; Arrays.sort(arr); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3);}} // This code is contributed by Anant Agarwal.
# Python3 program to find number of integer# less or greater given integer queries # Return the index of integer # which are not less than x# (or greater than or equal to x)def lower_bound(arr, start, end, x): while (start < end): mid = (start + end) >> 1 if (arr[mid] >= x): end = mid else: start = mid + 1 return start # Return the index of integer# which are greater than x.def upper_bound(arr, start, end, x): while (start < end): mid = (start + end) >> 1 if (arr[mid] <= x): start = mid + 1 else: end = mid return start def query(arr, n, type, x): # Counting number of integer # which are greater than x. if (type == 1): print(n - upper_bound(arr, 0, n, x)) # Counting number of integer # which are not less than x # (Or greater than or equal to x) else: print(n - lower_bound(arr, 0, n, x)) # Driver codearr = [ 1, 2, 3, 4 ]n =len(arr) arr.sort() query(arr, n, 0, 5)query(arr, n, 1, 3)query(arr, n, 0, 3) # This code is contributed by Anant Agarwal.
// C# to find number of integer less// or greater given integer queriesusing System; class GFG { // Return the index of integer which are// not less than x (or greater than or// equal to x)static int lower_bound(int []arr, int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.static int upper_bound(int []arr, int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} static void query(int []arr, int n, int type, int x){ // Counting number of integer // which are greater than x. if (type==1) Console.WriteLine(n - upper_bound(arr, 0, n, x)); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else Console.WriteLine(n - lower_bound(arr, 0, n, x));} // Driver codepublic static void Main (){ int []arr = {1, 2, 3, 4}; int n = arr.Length; Array.Sort(arr); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3);}} // This code is contributed by vt_m.
<?php// PHP to find number of integer// less or greater given// integer queries // Return the index of integer// which are not less than x// (or greater than or equal to x)function lower_bound($arr, $start, $end, $x){ while ($start < $end) { $mid = ($start + $end) >> 1; if ($arr[$mid] >= $x) $end = $mid; else $start = $mid + 1; } return $start;} // Return the index of integer// which are greater than x.function upper_bound($arr, $start, $end, $x){ while ($start < $end) { $mid = ($start + $end) >> 1; if ($arr[$mid] <= $x) $start = $mid + 1; else $end = $mid; } return $start;} function query($arr, $n, $type, $x){ // Counting number of integer // which are greater than x. if ($type) echo $n - upper_bound($arr, 0, $n, $x) ,"\n"; // Counting number of integer // which are not less than x // (Or greater than or equal to x) else echo $n - lower_bound($arr, 0, $n, $x) ,"\n";} // Driver Code $arr = array(1, 2, 3, 4); $n = count($arr); sort($arr); query($arr, $n, 0, 5); query($arr, $n, 1, 3); query($arr, $n, 0, 3); // This code is contributed by anuj_67.?>
<script> // JavaScript program to find number of integer// less or greater given// integer queries // Return the index of integer// which are not less than x// (or greater than or equal// to x)function lower_bound(arr, start, end, x){ while (start < end) { let mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.function upper_bound(arr, start, end, x){ while (start < end) { let mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} function query(arr, n, type, x){ // Counting number of integer // which are greater than x. if (type==1) document.write(n - upper_bound(arr, 0, n, x) + "<br/>"); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else document.write(n - lower_bound(arr, 0, n, x) + "<br/>");} // Driver code let arr = [ 1, 2, 3, 4 ]; let n = arr.length; arr.sort(); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3); </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
0
1
2
Time Complexity : O( (N + Q) * logN).
YouTubeGeeksforGeeks507K subscribersQueries for greater than and not less than | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rHwWSYdvAhg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
ManasChhabra2
chinmoy1997pal
Binary Search
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
3 Different ways to print Fibonacci series in Java
Find whether an array is subset of another array | Added Method 5
Given a sorted and rotated array, find if there is a pair with a given sum
Find a pair with the given difference
Find common elements in three sorted arrays
Interpolation search vs Binary search
Recursive Programs to find Minimum and Maximum elements of array
Program to remove vowels from a String
Find closest number in array
|
[
{
"code": null,
"e": 26215,
"s": 26187,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 26353,
"s": 26215,
"text": "Given an array of N integers. There will be Q queries, each include two integer of form q and x, 0 <= q <= 1. Queries are of two types: "
},
{
"code": null,
"e": 26476,
"s": 26353,
"text": "In first query (q = 0), the task is to find count of integers which are not less than x (OR greater than or equal to x). "
},
{
"code": null,
"e": 26557,
"s": 26476,
"text": "In second query (q = 1), the task is to find count of integers greater than x. "
},
{
"code": null,
"e": 26569,
"s": 26557,
"text": "Examples: "
},
{
"code": null,
"e": 26911,
"s": 26569,
"text": "Input : arr[] = { 1, 2, 3, 4 } and Q = 3\n Query 1: 0 5\n Query 2: 1 3\n Query 3: 0 3\nOutput :0\n 1\n 2\nExplanation:\nx = 5, q = 0 : There are no elements greater than or equal to it.\nx = 3, q = 1 : There is one element greater than 3 which is 4.\nx = 3, q = 0 : There are two elements greater than or equal to 3."
},
{
"code": null,
"e": 27269,
"s": 26913,
"text": "Method 1: A Naive approach can be for each query, traverse the whole array and count integers less or greater than x, depending on q. Time Complexity for this approach will be O(Q*N).Method 2: An efficient approach can be sort the array and use binary search for each query. This will take O(NlogN + QlogN).Below is the implementation of this approach : "
},
{
"code": null,
"e": 27273,
"s": 27269,
"text": "C++"
},
{
"code": null,
"e": 27278,
"s": 27273,
"text": "Java"
},
{
"code": null,
"e": 27286,
"s": 27278,
"text": "Python3"
},
{
"code": null,
"e": 27289,
"s": 27286,
"text": "C#"
},
{
"code": null,
"e": 27293,
"s": 27289,
"text": "PHP"
},
{
"code": null,
"e": 27304,
"s": 27293,
"text": "Javascript"
},
{
"code": "// C++ to find number of integer less or greater given// integer queries#include<bits/stdc++.h>using namespace std; // Return the index of integer which are not less than x// (or greater than or equal to x)int lower_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer which are greater than x.int upper_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} void query(int arr[], int n, int type, int x){ // Counting number of integer which are greater than x. if (type) cout << n - upper_bound(arr, 0, n, x) << endl; // Counting number of integer which are not less than x // (Or greater than or equal to x) else cout << n - lower_bound(arr, 0, n, x) << endl;} // Driven Programint main(){ int arr[] = { 1, 2, 3, 4 }; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr + n); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3); return 0;}",
"e": 28571,
"s": 27304,
"text": null
},
{
"code": "// Java to find number of integer// less or greater given// integer queriesimport java.util.Arrays;class GFG{// Return the index of integer// which are not less than x// (or greater than or equal// to x)static int lower_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.static int upper_bound(int arr[], int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} static void query(int arr[], int n, int type, int x){ // Counting number of integer // which are greater than x. if (type==1) System.out.println(n - upper_bound(arr, 0, n, x)); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else System.out.println(n - lower_bound(arr, 0, n, x));} // Driver codepublic static void main (String[] args){ int arr[] = { 1, 2, 3, 4 }; int n = arr.length; Arrays.sort(arr); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3);}} // This code is contributed by Anant Agarwal.",
"e": 29949,
"s": 28571,
"text": null
},
{
"code": "# Python3 program to find number of integer# less or greater given integer queries # Return the index of integer # which are not less than x# (or greater than or equal to x)def lower_bound(arr, start, end, x): while (start < end): mid = (start + end) >> 1 if (arr[mid] >= x): end = mid else: start = mid + 1 return start # Return the index of integer# which are greater than x.def upper_bound(arr, start, end, x): while (start < end): mid = (start + end) >> 1 if (arr[mid] <= x): start = mid + 1 else: end = mid return start def query(arr, n, type, x): # Counting number of integer # which are greater than x. if (type == 1): print(n - upper_bound(arr, 0, n, x)) # Counting number of integer # which are not less than x # (Or greater than or equal to x) else: print(n - lower_bound(arr, 0, n, x)) # Driver codearr = [ 1, 2, 3, 4 ]n =len(arr) arr.sort() query(arr, n, 0, 5)query(arr, n, 1, 3)query(arr, n, 0, 3) # This code is contributed by Anant Agarwal.",
"e": 31062,
"s": 29949,
"text": null
},
{
"code": "// C# to find number of integer less// or greater given integer queriesusing System; class GFG { // Return the index of integer which are// not less than x (or greater than or// equal to x)static int lower_bound(int []arr, int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.static int upper_bound(int []arr, int start, int end, int x){ while (start < end) { int mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} static void query(int []arr, int n, int type, int x){ // Counting number of integer // which are greater than x. if (type==1) Console.WriteLine(n - upper_bound(arr, 0, n, x)); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else Console.WriteLine(n - lower_bound(arr, 0, n, x));} // Driver codepublic static void Main (){ int []arr = {1, 2, 3, 4}; int n = arr.Length; Array.Sort(arr); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3);}} // This code is contributed by vt_m.",
"e": 32432,
"s": 31062,
"text": null
},
{
"code": "<?php// PHP to find number of integer// less or greater given// integer queries // Return the index of integer// which are not less than x// (or greater than or equal to x)function lower_bound($arr, $start, $end, $x){ while ($start < $end) { $mid = ($start + $end) >> 1; if ($arr[$mid] >= $x) $end = $mid; else $start = $mid + 1; } return $start;} // Return the index of integer// which are greater than x.function upper_bound($arr, $start, $end, $x){ while ($start < $end) { $mid = ($start + $end) >> 1; if ($arr[$mid] <= $x) $start = $mid + 1; else $end = $mid; } return $start;} function query($arr, $n, $type, $x){ // Counting number of integer // which are greater than x. if ($type) echo $n - upper_bound($arr, 0, $n, $x) ,\"\\n\"; // Counting number of integer // which are not less than x // (Or greater than or equal to x) else echo $n - lower_bound($arr, 0, $n, $x) ,\"\\n\";} // Driver Code $arr = array(1, 2, 3, 4); $n = count($arr); sort($arr); query($arr, $n, 0, 5); query($arr, $n, 1, 3); query($arr, $n, 0, 3); // This code is contributed by anuj_67.?>",
"e": 33668,
"s": 32432,
"text": null
},
{
"code": "<script> // JavaScript program to find number of integer// less or greater given// integer queries // Return the index of integer// which are not less than x// (or greater than or equal// to x)function lower_bound(arr, start, end, x){ while (start < end) { let mid = (start + end)>>1; if (arr[mid] >= x) end = mid; else start = mid + 1; } return start;} // Return the index of integer// which are greater than x.function upper_bound(arr, start, end, x){ while (start < end) { let mid = (start + end)>>1; if (arr[mid] <= x) start = mid + 1; else end = mid; } return start;} function query(arr, n, type, x){ // Counting number of integer // which are greater than x. if (type==1) document.write(n - upper_bound(arr, 0, n, x) + \"<br/>\"); // Counting number of integer which // are not less than x (Or greater // than or equal to x) else document.write(n - lower_bound(arr, 0, n, x) + \"<br/>\");} // Driver code let arr = [ 1, 2, 3, 4 ]; let n = arr.length; arr.sort(); query(arr, n, 0, 5); query(arr, n, 1, 3); query(arr, n, 0, 3); </script>",
"e": 34920,
"s": 33668,
"text": null
},
{
"code": null,
"e": 34929,
"s": 34920,
"text": "Output: "
},
{
"code": null,
"e": 34938,
"s": 34929,
"text": "Chapters"
},
{
"code": null,
"e": 34965,
"s": 34938,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 35015,
"s": 34965,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 35038,
"s": 35015,
"text": "captions off, selected"
},
{
"code": null,
"e": 35046,
"s": 35038,
"text": "English"
},
{
"code": null,
"e": 35070,
"s": 35046,
"text": "This is a modal window."
},
{
"code": null,
"e": 35139,
"s": 35070,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 35161,
"s": 35139,
"text": "End of dialog window."
},
{
"code": null,
"e": 35167,
"s": 35161,
"text": "0\n1\n2"
},
{
"code": null,
"e": 35206,
"s": 35167,
"text": "Time Complexity : O( (N + Q) * logN). "
},
{
"code": null,
"e": 36047,
"s": 35206,
"text": "YouTubeGeeksforGeeks507K subscribersQueries for greater than and not less than | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:31•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rHwWSYdvAhg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 36472,
"s": 36047,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36477,
"s": 36472,
"text": "vt_m"
},
{
"code": null,
"e": 36491,
"s": 36477,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 36506,
"s": 36491,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 36520,
"s": 36506,
"text": "Binary Search"
},
{
"code": null,
"e": 36530,
"s": 36520,
"text": "Searching"
},
{
"code": null,
"e": 36540,
"s": 36530,
"text": "Searching"
},
{
"code": null,
"e": 36554,
"s": 36540,
"text": "Binary Search"
},
{
"code": null,
"e": 36652,
"s": 36554,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36688,
"s": 36652,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 36739,
"s": 36688,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 36805,
"s": 36739,
"text": "Find whether an array is subset of another array | Added Method 5"
},
{
"code": null,
"e": 36880,
"s": 36805,
"text": "Given a sorted and rotated array, find if there is a pair with a given sum"
},
{
"code": null,
"e": 36918,
"s": 36880,
"text": "Find a pair with the given difference"
},
{
"code": null,
"e": 36962,
"s": 36918,
"text": "Find common elements in three sorted arrays"
},
{
"code": null,
"e": 37000,
"s": 36962,
"text": "Interpolation search vs Binary search"
},
{
"code": null,
"e": 37065,
"s": 37000,
"text": "Recursive Programs to find Minimum and Maximum elements of array"
},
{
"code": null,
"e": 37104,
"s": 37065,
"text": "Program to remove vowels from a String"
}
] |
PHP | settype() Function - GeeksforGeeks
|
14 Mar, 2018
The settype() function is a built-in function in PHP. The settype() function is used to the set the type of a variable. It is used to set type or modify type of an existing variable.
Syntax:
boolean settype($variable_name, $type)
Parameters: The settype() function accepts two parameters as shown in above syntax and are described below.
$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc.$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null.
$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc.
$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null.
Return value: This function returns a boolean type value. It returns TRUE in case of success and FALSE in case of failure.
Below programs illustrate the settype() function in PHP:
Program 1:
<?php // PHP program to illustrate settype() function $var1 = "123xyz";$var2 = 3;$r = true;settype($var1, "integer");settype($var2, "float");settype($r, "string");echo $var1."\n";echo $var2."\n";echo $r."\n"; ?>
Output:
123
3
1
Program 2:
<?php // PHP program to illustrate settype() function $var1 = "a12b";$var2 = 3.566;$r = true;settype($var1, "integer");settype($var2, "integer");settype($r, "string");echo $var1."\n";echo $var2."\n";echo $r."\n"; ?>
Output:
0
3
1
Reference:http://php.net/manual/en/function.settype.php
PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Different ways for passing data to view in Laravel
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n14 Mar, 2018"
},
{
"code": null,
"e": 26400,
"s": 26217,
"text": "The settype() function is a built-in function in PHP. The settype() function is used to the set the type of a variable. It is used to set type or modify type of an existing variable."
},
{
"code": null,
"e": 26408,
"s": 26400,
"text": "Syntax:"
},
{
"code": null,
"e": 26447,
"s": 26408,
"text": "boolean settype($variable_name, $type)"
},
{
"code": null,
"e": 26555,
"s": 26447,
"text": "Parameters: The settype() function accepts two parameters as shown in above syntax and are described below."
},
{
"code": null,
"e": 26898,
"s": 26555,
"text": "$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc.$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null."
},
{
"code": null,
"e": 27080,
"s": 26898,
"text": "$variable_name: This parameter specifies the name of variablewhose type we want to modify. This parameter can be of any type that is, it can be of integer type or a string type etc."
},
{
"code": null,
"e": 27242,
"s": 27080,
"text": "$type: This parameter specifies the type of variable that is needed. Possible values of this parameter are: boolean, integer, float, string, array, object, null."
},
{
"code": null,
"e": 27365,
"s": 27242,
"text": "Return value: This function returns a boolean type value. It returns TRUE in case of success and FALSE in case of failure."
},
{
"code": null,
"e": 27422,
"s": 27365,
"text": "Below programs illustrate the settype() function in PHP:"
},
{
"code": null,
"e": 27433,
"s": 27422,
"text": "Program 1:"
},
{
"code": "<?php // PHP program to illustrate settype() function $var1 = \"123xyz\";$var2 = 3;$r = true;settype($var1, \"integer\");settype($var2, \"float\");settype($r, \"string\");echo $var1.\"\\n\";echo $var2.\"\\n\";echo $r.\"\\n\"; ?>",
"e": 27648,
"s": 27433,
"text": null
},
{
"code": null,
"e": 27656,
"s": 27648,
"text": "Output:"
},
{
"code": null,
"e": 27664,
"s": 27656,
"text": "123\n3\n1"
},
{
"code": null,
"e": 27675,
"s": 27664,
"text": "Program 2:"
},
{
"code": "<?php // PHP program to illustrate settype() function $var1 = \"a12b\";$var2 = 3.566;$r = true;settype($var1, \"integer\");settype($var2, \"integer\");settype($r, \"string\");echo $var1.\"\\n\";echo $var2.\"\\n\";echo $r.\"\\n\"; ?>",
"e": 27894,
"s": 27675,
"text": null
},
{
"code": null,
"e": 27902,
"s": 27894,
"text": "Output:"
},
{
"code": null,
"e": 27909,
"s": 27902,
"text": "0\n3\n1\n"
},
{
"code": null,
"e": 27965,
"s": 27909,
"text": "Reference:http://php.net/manual/en/function.settype.php"
},
{
"code": null,
"e": 27976,
"s": 27965,
"text": "PHP-basics"
},
{
"code": null,
"e": 27980,
"s": 27976,
"text": "PHP"
},
{
"code": null,
"e": 27997,
"s": 27980,
"text": "Web Technologies"
},
{
"code": null,
"e": 28001,
"s": 27997,
"text": "PHP"
},
{
"code": null,
"e": 28099,
"s": 28001,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28181,
"s": 28099,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 28223,
"s": 28181,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 28250,
"s": 28223,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 28314,
"s": 28250,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 28365,
"s": 28314,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 28405,
"s": 28365,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28438,
"s": 28405,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28483,
"s": 28438,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28526,
"s": 28483,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Add Splash Screen in Flutter App? - GeeksforGeeks
|
18 Oct, 2021
We all have heard of Flutter right, it’s a cross-platform application development tool. Flutter can be used to make Android, IOS, and Web applications with just one code base (Dart programming language). In this article let’s see how we can add a splash screen to our applications.
When we open an application on our phones, the first thing we see is a screen with the logo of the app in the center that screen is referred to as a splash screen Now this splash screen can be used to make our applications look fancy but there’s more to it.
When we open an app on our device, some apps are required to authenticate the user (who’s opening the app) before they let us use the app. This authentication sometimes requires a fraction of a second during which time the user is presented with a splash screen so that the application does not appear to be stuck.
Flutter is all about packages, there is always a package available for our use. In this problem of ours, we will use a package called animated_splash_screen.
To install this package, add the following code to the pubspec.yaml file and run pub get :
dependencies:
animated_splash_screen: ^1.1.0
Note: Watch the indentation, if you get the indentation wrong you will get an error and we definitely don’t like errors.
When we create a flutter app from scratch, we will see some boilerplate code like the one below, in the main.dart file.
Dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // Application name title: 'Flutter Hello World', // Application theme data, you can set // the colors for the application as // you want theme: ThemeData( primarySwatch: Colors.blue, ), // A widget which will be started on application startup home: MyHomePage(title: 'Flutter Demo Home Page'), ); }} class MyHomePage extends StatelessWidget { final String title; const MyHomePage({@required this.title}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // The title text which will // be shown on the action bar title: Text(title), ), body: Center( child: Text( 'Hello, World!', ), ), ); }}
In the above code instead of returning MyHomePage, we will return an AnimatedSplashScreen which has also required a nextScreen, where we will return our MyHomePage. Like this:
Dart
import 'package:flutter/material.dart';import 'package:animated_splash_screen/animated_splash_screen.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // Application name title: 'GFG tutotial', // Application theme data, you can set the // colors for the application as // you want theme: ThemeData( primarySwatch: Colors.green, ), // A widget which will be started on application startup home: AnimatedSplashScreen( splash: 'images/gfg.png', nextScreen: MyHomePage(title: 'GeeksForGeeks'), splashTransition: SplashTransition.fadeTransition, ), ); }} class MyHomePage extends StatelessWidget { final String title; const MyHomePage({@required this.title}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // The title text which will be shown on the action bar title: Text(title), ), body: Center( child: Text( 'GeeksForGeeks!', ), ), ); }}
To use our own image for the splash screen we have to include the images under the assets section in pubspec.yaml file :
Output :
Flutter UI-components
TrueGeek-2021
Dart
Flutter
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Dialogs
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Flexible Widget
Flutter - Stack Widget
Flutter - Dialogs
|
[
{
"code": null,
"e": 25261,
"s": 25233,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 25543,
"s": 25261,
"text": "We all have heard of Flutter right, it’s a cross-platform application development tool. Flutter can be used to make Android, IOS, and Web applications with just one code base (Dart programming language). In this article let’s see how we can add a splash screen to our applications."
},
{
"code": null,
"e": 25801,
"s": 25543,
"text": "When we open an application on our phones, the first thing we see is a screen with the logo of the app in the center that screen is referred to as a splash screen Now this splash screen can be used to make our applications look fancy but there’s more to it."
},
{
"code": null,
"e": 26116,
"s": 25801,
"text": "When we open an app on our device, some apps are required to authenticate the user (who’s opening the app) before they let us use the app. This authentication sometimes requires a fraction of a second during which time the user is presented with a splash screen so that the application does not appear to be stuck."
},
{
"code": null,
"e": 26274,
"s": 26116,
"text": "Flutter is all about packages, there is always a package available for our use. In this problem of ours, we will use a package called animated_splash_screen."
},
{
"code": null,
"e": 26365,
"s": 26274,
"text": "To install this package, add the following code to the pubspec.yaml file and run pub get :"
},
{
"code": null,
"e": 26412,
"s": 26365,
"text": "dependencies:\n animated_splash_screen: ^1.1.0"
},
{
"code": null,
"e": 26533,
"s": 26412,
"text": "Note: Watch the indentation, if you get the indentation wrong you will get an error and we definitely don’t like errors."
},
{
"code": null,
"e": 26653,
"s": 26533,
"text": "When we create a flutter app from scratch, we will see some boilerplate code like the one below, in the main.dart file."
},
{
"code": null,
"e": 26658,
"s": 26653,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // Application name title: 'Flutter Hello World', // Application theme data, you can set // the colors for the application as // you want theme: ThemeData( primarySwatch: Colors.blue, ), // A widget which will be started on application startup home: MyHomePage(title: 'Flutter Demo Home Page'), ); }} class MyHomePage extends StatelessWidget { final String title; const MyHomePage({@required this.title}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // The title text which will // be shown on the action bar title: Text(title), ), body: Center( child: Text( 'Hello, World!', ), ), ); }}",
"e": 27689,
"s": 26658,
"text": null
},
{
"code": null,
"e": 27865,
"s": 27689,
"text": "In the above code instead of returning MyHomePage, we will return an AnimatedSplashScreen which has also required a nextScreen, where we will return our MyHomePage. Like this:"
},
{
"code": null,
"e": 27870,
"s": 27865,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart';import 'package:animated_splash_screen/animated_splash_screen.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( // Application name title: 'GFG tutotial', // Application theme data, you can set the // colors for the application as // you want theme: ThemeData( primarySwatch: Colors.green, ), // A widget which will be started on application startup home: AnimatedSplashScreen( splash: 'images/gfg.png', nextScreen: MyHomePage(title: 'GeeksForGeeks'), splashTransition: SplashTransition.fadeTransition, ), ); }} class MyHomePage extends StatelessWidget { final String title; const MyHomePage({@required this.title}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // The title text which will be shown on the action bar title: Text(title), ), body: Center( child: Text( 'GeeksForGeeks!', ), ), ); }}",
"e": 29085,
"s": 27870,
"text": null
},
{
"code": null,
"e": 29206,
"s": 29085,
"text": "To use our own image for the splash screen we have to include the images under the assets section in pubspec.yaml file :"
},
{
"code": null,
"e": 29215,
"s": 29206,
"text": "Output :"
},
{
"code": null,
"e": 29237,
"s": 29215,
"text": "Flutter UI-components"
},
{
"code": null,
"e": 29251,
"s": 29237,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 29256,
"s": 29251,
"text": "Dart"
},
{
"code": null,
"e": 29264,
"s": 29256,
"text": "Flutter"
},
{
"code": null,
"e": 29273,
"s": 29264,
"text": "TrueGeek"
},
{
"code": null,
"e": 29371,
"s": 29273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29410,
"s": 29371,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29436,
"s": 29410,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 29462,
"s": 29436,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29485,
"s": 29462,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 29503,
"s": 29485,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 29542,
"s": 29503,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29559,
"s": 29542,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 29585,
"s": 29559,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 29608,
"s": 29585,
"text": "Flutter - Stack Widget"
}
] |
Remove Newline from Character String in R - GeeksforGeeks
|
23 Aug, 2021
In this article, we are going to see how to remove the new line from a character string in R Programming Language.
Example:
Input: String with newline: "Hello\nGeeks\rFor\r\n Geeks"
Output: String after removing new line: "HelloGeeksFor Geeks"
gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is.
Syntax:gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)
Parameters:pattern: string to be matchedreplacement: string for replacementstring: String or String vectorignore.case: Boolean value for case-sensitive replacement
Example: R program to remove the newline from character string using gsub() function.
Syntax: gsub(“[\r\n]”, “”, string)
where
[\r\n] is a first parameter which is a pattern to remove new lines
“” is the second parameter that replaces when new line occurs as empty
string is the input string of characters.
Code:
R
# consider a stringstring = "Hello\nGeeks\nFor\nGeeks\n" # display stringprint("Original string: ")cat(string) # string after removing new linesprint("string after removing new lines: ")cat(gsub("[\r\n]", "", string))
Output:
[1] "Original string: "
Hello
Geeks
For
Geeks
[1] "string after removing new lines: "
HelloGeeksForGeeks
This function is available in stringr package which is also used to remove the new line from a character string
Syntax: str_replace_all(string, “[\r\n]” , “”)
where
string is the first parameter that takes string as input.
[\r\n] is a second parameter which is a pattern to remove new lines
“” is the third parameter that replaces when new line occurs as empty
Example: R program to remove newline from string using stringr package
R
library(stringr) # consider a stringstring="Hello\nGeeks\rFor\r\nGeeks\n" # display stringprint("Original string: ")cat(string) # string after removing new linesprint("string after removing new lines: ")print(str_replace_all(string, "[\r\n]" , ""))
Output:
[1] "Original string: "
Hello
Forks
Geeks
[1] "string after removing new lines: "
[1] "HelloGeeksForGeeks"
Picked
R String-Programs
R-strings
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 26602,
"s": 26487,
"text": "In this article, we are going to see how to remove the new line from a character string in R Programming Language."
},
{
"code": null,
"e": 26611,
"s": 26602,
"text": "Example:"
},
{
"code": null,
"e": 26731,
"s": 26611,
"text": "Input: String with newline: \"Hello\\nGeeks\\rFor\\r\\n Geeks\"\nOutput: String after removing new line: \"HelloGeeksFor Geeks\""
},
{
"code": null,
"e": 26890,
"s": 26731,
"text": "gsub() function in R Language is used to replace all the matches of a pattern from a string. If the pattern is not found the string will be returned as it is."
},
{
"code": null,
"e": 26956,
"s": 26890,
"text": "Syntax:gsub(pattern, replacement, string, ignore.case=TRUE/FALSE)"
},
{
"code": null,
"e": 27120,
"s": 26956,
"text": "Parameters:pattern: string to be matchedreplacement: string for replacementstring: String or String vectorignore.case: Boolean value for case-sensitive replacement"
},
{
"code": null,
"e": 27206,
"s": 27120,
"text": "Example: R program to remove the newline from character string using gsub() function."
},
{
"code": null,
"e": 27241,
"s": 27206,
"text": "Syntax: gsub(“[\\r\\n]”, “”, string)"
},
{
"code": null,
"e": 27247,
"s": 27241,
"text": "where"
},
{
"code": null,
"e": 27314,
"s": 27247,
"text": "[\\r\\n] is a first parameter which is a pattern to remove new lines"
},
{
"code": null,
"e": 27385,
"s": 27314,
"text": "“” is the second parameter that replaces when new line occurs as empty"
},
{
"code": null,
"e": 27427,
"s": 27385,
"text": "string is the input string of characters."
},
{
"code": null,
"e": 27433,
"s": 27427,
"text": "Code:"
},
{
"code": null,
"e": 27435,
"s": 27433,
"text": "R"
},
{
"code": "# consider a stringstring = \"Hello\\nGeeks\\nFor\\nGeeks\\n\" # display stringprint(\"Original string: \")cat(string) # string after removing new linesprint(\"string after removing new lines: \")cat(gsub(\"[\\r\\n]\", \"\", string))",
"e": 27655,
"s": 27435,
"text": null
},
{
"code": null,
"e": 27663,
"s": 27655,
"text": "Output:"
},
{
"code": null,
"e": 27768,
"s": 27663,
"text": "[1] \"Original string: \"\nHello\nGeeks\nFor\nGeeks\n[1] \"string after removing new lines: \"\nHelloGeeksForGeeks"
},
{
"code": null,
"e": 27881,
"s": 27768,
"text": "This function is available in stringr package which is also used to remove the new line from a character string"
},
{
"code": null,
"e": 27928,
"s": 27881,
"text": "Syntax: str_replace_all(string, “[\\r\\n]” , “”)"
},
{
"code": null,
"e": 27934,
"s": 27928,
"text": "where"
},
{
"code": null,
"e": 27992,
"s": 27934,
"text": "string is the first parameter that takes string as input."
},
{
"code": null,
"e": 28060,
"s": 27992,
"text": "[\\r\\n] is a second parameter which is a pattern to remove new lines"
},
{
"code": null,
"e": 28130,
"s": 28060,
"text": "“” is the third parameter that replaces when new line occurs as empty"
},
{
"code": null,
"e": 28201,
"s": 28130,
"text": "Example: R program to remove newline from string using stringr package"
},
{
"code": null,
"e": 28203,
"s": 28201,
"text": "R"
},
{
"code": "library(stringr) # consider a stringstring=\"Hello\\nGeeks\\rFor\\r\\nGeeks\\n\" # display stringprint(\"Original string: \")cat(string) # string after removing new linesprint(\"string after removing new lines: \")print(str_replace_all(string, \"[\\r\\n]\" , \"\"))",
"e": 28455,
"s": 28203,
"text": null
},
{
"code": null,
"e": 28463,
"s": 28455,
"text": "Output:"
},
{
"code": null,
"e": 28570,
"s": 28463,
"text": "[1] \"Original string: \"\nHello\nForks\nGeeks\n[1] \"string after removing new lines: \"\n[1] \"HelloGeeksForGeeks\""
},
{
"code": null,
"e": 28577,
"s": 28570,
"text": "Picked"
},
{
"code": null,
"e": 28595,
"s": 28577,
"text": "R String-Programs"
},
{
"code": null,
"e": 28605,
"s": 28595,
"text": "R-strings"
},
{
"code": null,
"e": 28616,
"s": 28605,
"text": "R Language"
},
{
"code": null,
"e": 28627,
"s": 28616,
"text": "R Programs"
},
{
"code": null,
"e": 28725,
"s": 28627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28777,
"s": 28725,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28812,
"s": 28777,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28850,
"s": 28812,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28908,
"s": 28850,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28951,
"s": 28908,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29009,
"s": 28951,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29052,
"s": 29009,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29101,
"s": 29052,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29151,
"s": 29101,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
C# - Basic Syntax
|
C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class.
For example, let us consider a Rectangle object. It has attributes such as length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating the area, and displaying details.
Let us look at implementation of a Rectangle class and discuss C# basic syntax −
using System;
namespace RectangleApplication {
class Rectangle {
// member variables
double length;
double width;
public void Acceptdetails() {
length = 4.5;
width = 3.5;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
The first statement in any C# program is
using System;
The using keyword is used for including the namespaces in the program. A program can include multiple using statements.
The class keyword is used for declaring a class.
Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below −
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol. For example,
}//end class Rectangle
Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width.
Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display.
In the preceding program, the class ExecuteRectangle contains the Main() method and instantiates the Rectangle class.
An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
It should not be a C# keyword.
It should not be a C# keyword.
Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. However, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character.
In C#, some identifiers have special meaning in context of code, such as get and set are called contextual keywords.
The following table lists the reserved keywords and contextual keywords in C# −
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2600,
"s": 2270,
"text": "C# is an object-oriented programming language. In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions. The actions that an object may take are called methods. Objects of the same kind are said to have the same type or, are said to be in the same class."
},
{
"code": null,
"e": 2829,
"s": 2600,
"text": "For example, let us consider a Rectangle object. It has attributes such as length and width. Depending upon the design, it may need ways for accepting the values of these attributes, calculating the area, and displaying details."
},
{
"code": null,
"e": 2910,
"s": 2829,
"text": "Let us look at implementation of a Rectangle class and discuss C# basic syntax −"
},
{
"code": null,
"e": 3624,
"s": 2910,
"text": "using System;\n\nnamespace RectangleApplication {\n class Rectangle {\n \n // member variables\n double length;\n double width;\n \n public void Acceptdetails() {\n length = 4.5; \n width = 3.5;\n }\n public double GetArea() {\n return length * width; \n }\n public void Display() {\n Console.WriteLine(\"Length: {0}\", length);\n Console.WriteLine(\"Width: {0}\", width);\n Console.WriteLine(\"Area: {0}\", GetArea());\n }\n }\n class ExecuteRectangle {\n static void Main(string[] args) {\n Rectangle r = new Rectangle();\n r.Acceptdetails();\n r.Display();\n Console.ReadLine(); \n }\n }\n}"
},
{
"code": null,
"e": 3705,
"s": 3624,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3741,
"s": 3705,
"text": "Length: 4.5\nWidth: 3.5\nArea: 15.75\n"
},
{
"code": null,
"e": 3782,
"s": 3741,
"text": "The first statement in any C# program is"
},
{
"code": null,
"e": 3797,
"s": 3782,
"text": "using System;\n"
},
{
"code": null,
"e": 3917,
"s": 3797,
"text": "The using keyword is used for including the namespaces in the program. A program can include multiple using statements."
},
{
"code": null,
"e": 3966,
"s": 3917,
"text": "The class keyword is used for declaring a class."
},
{
"code": null,
"e": 4150,
"s": 3966,
"text": "Comments are used for explaining code. Compilers ignore the comment entries. The multiline comments in C# programs start with /* and terminates with the characters */ as shown below −"
},
{
"code": null,
"e": 4227,
"s": 4150,
"text": "/* This program demonstrates\nThe basic syntax of C# programming \nLanguage */"
},
{
"code": null,
"e": 4295,
"s": 4227,
"text": "Single-line comments are indicated by the '//' symbol. For example,"
},
{
"code": null,
"e": 4322,
"s": 4295,
"text": "}//end class Rectangle "
},
{
"code": null,
"e": 4493,
"s": 4322,
"text": "Variables are attributes or data members of a class, used for storing data. In the preceding program, the Rectangle class has two member variables named length and width."
},
{
"code": null,
"e": 4715,
"s": 4493,
"text": "Functions are set of statements that perform a specific task. The member functions of a class are declared within the class. Our sample class Rectangle contains three member functions: AcceptDetails, GetArea and Display."
},
{
"code": null,
"e": 4834,
"s": 4715,
"text": "In the preceding program, the class ExecuteRectangle contains the Main() method and instantiates the Rectangle class."
},
{
"code": null,
"e": 4994,
"s": 4834,
"text": "An identifier is a name used to identify a class, variable, function, or any other user-defined item. The basic rules for naming classes in C# are as follows −"
},
{
"code": null,
"e": 5161,
"s": 4994,
"text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit."
},
{
"code": null,
"e": 5328,
"s": 5161,
"text": "A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or underscore. The first character in an identifier cannot be a digit."
},
{
"code": null,
"e": 5477,
"s": 5328,
"text": "It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used."
},
{
"code": null,
"e": 5626,
"s": 5477,
"text": "It must not contain any embedded space or symbol such as? - + ! @ # % ^ & * ( ) [ ] { } . ; : \" ' / and \\. However, an underscore ( _ ) can be used."
},
{
"code": null,
"e": 5657,
"s": 5626,
"text": "It should not be a C# keyword."
},
{
"code": null,
"e": 5688,
"s": 5657,
"text": "It should not be a C# keyword."
},
{
"code": null,
"e": 5901,
"s": 5688,
"text": "Keywords are reserved words predefined to the C# compiler. These keywords cannot be used as identifiers. However, if you want to use these keywords as identifiers, you may prefix the keyword with the @ character."
},
{
"code": null,
"e": 6018,
"s": 5901,
"text": "In C#, some identifiers have special meaning in context of code, such as get and set are called contextual keywords."
},
{
"code": null,
"e": 6098,
"s": 6018,
"text": "The following table lists the reserved keywords and contextual keywords in C# −"
},
{
"code": null,
"e": 6135,
"s": 6098,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 6148,
"s": 6135,
"text": " Raja Biswas"
},
{
"code": null,
"e": 6182,
"s": 6148,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6200,
"s": 6182,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6233,
"s": 6200,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6247,
"s": 6233,
"text": " Peter Jepson"
},
{
"code": null,
"e": 6284,
"s": 6247,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 6299,
"s": 6284,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 6334,
"s": 6299,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6349,
"s": 6334,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6384,
"s": 6349,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6396,
"s": 6384,
"text": " Eric Frick"
},
{
"code": null,
"e": 6403,
"s": 6396,
"text": " Print"
},
{
"code": null,
"e": 6414,
"s": 6403,
"text": " Add Notes"
}
] |
BigDecimal doubleValue() Method in Java - GeeksforGeeks
|
04 Dec, 2018
The java.math.BigDecimal.doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate or according to the passed object, if its magnitude is too big to be represented as a double.
Note: The information about the decimal precision of the Double value of the given BigDecimal value can be lost even if the return value is finite.
Syntax:
public double doubleValue()
Parameters: The method does not accept any parameters.
Return Value: This method returns the double value of this BigDecimal Object.
Examples:
Input : 11234
Output : 11234.0
Input : 2679.30000
Output : 2679.3
Below programs illustrates the use of byteValueExact() Function:Program 1:
// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal big; // Creating a Double object Double dob; big = new BigDecimal("4743"); // Assigning the converted value of bg to d dob = big.doubleValue(); // Printing the corresponding double value System.out.println("Double value of " + big + " is " + dob); }}
Double value of 4743 is 4743.0
Program 2:
// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal big; // Creating a Double object Double dob; big = new BigDecimal("6714592679.34008"); // Assigning the converted value of bg to d dob = big.doubleValue(); // Printing the corresponding double value System.out.println("Double value of " + big + " is " + dob); }}
Double value of 6714592679.34008 is 6.71459267934008E9
Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#doubleValue()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
|
[
{
"code": null,
"e": 24304,
"s": 24276,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 24620,
"s": 24304,
"text": "The java.math.BigDecimal.doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.NEGATIVE_INFINITY or Double.POSITIVE_INFINITY as appropriate or according to the passed object, if its magnitude is too big to be represented as a double."
},
{
"code": null,
"e": 24768,
"s": 24620,
"text": "Note: The information about the decimal precision of the Double value of the given BigDecimal value can be lost even if the return value is finite."
},
{
"code": null,
"e": 24776,
"s": 24768,
"text": "Syntax:"
},
{
"code": null,
"e": 24804,
"s": 24776,
"text": "public double doubleValue()"
},
{
"code": null,
"e": 24859,
"s": 24804,
"text": "Parameters: The method does not accept any parameters."
},
{
"code": null,
"e": 24937,
"s": 24859,
"text": "Return Value: This method returns the double value of this BigDecimal Object."
},
{
"code": null,
"e": 24947,
"s": 24937,
"text": "Examples:"
},
{
"code": null,
"e": 25015,
"s": 24947,
"text": "Input : 11234\nOutput : 11234.0\n\nInput : 2679.30000\nOutput : 2679.3\n"
},
{
"code": null,
"e": 25090,
"s": 25015,
"text": "Below programs illustrates the use of byteValueExact() Function:Program 1:"
},
{
"code": "// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal big; // Creating a Double object Double dob; big = new BigDecimal(\"4743\"); // Assigning the converted value of bg to d dob = big.doubleValue(); // Printing the corresponding double value System.out.println(\"Double value of \" + big + \" is \" + dob); }}",
"e": 25617,
"s": 25090,
"text": null
},
{
"code": null,
"e": 25649,
"s": 25617,
"text": "Double value of 4743 is 4743.0\n"
},
{
"code": null,
"e": 25660,
"s": 25649,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate doubleValue() methodimport java.io.*;import java.math.*; public class GFG { public static void main(String[] args) { // Creating a BigDecimal object BigDecimal big; // Creating a Double object Double dob; big = new BigDecimal(\"6714592679.34008\"); // Assigning the converted value of bg to d dob = big.doubleValue(); // Printing the corresponding double value System.out.println(\"Double value of \" + big + \" is \" + dob); }}",
"e": 26199,
"s": 25660,
"text": null
},
{
"code": null,
"e": 26255,
"s": 26199,
"text": "Double value of 6714592679.34008 is 6.71459267934008E9\n"
},
{
"code": null,
"e": 26347,
"s": 26255,
"text": "Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#doubleValue()"
},
{
"code": null,
"e": 26363,
"s": 26347,
"text": "Java-BigDecimal"
},
{
"code": null,
"e": 26378,
"s": 26363,
"text": "Java-Functions"
},
{
"code": null,
"e": 26388,
"s": 26378,
"text": "java-math"
},
{
"code": null,
"e": 26406,
"s": 26388,
"text": "Java-math-package"
},
{
"code": null,
"e": 26411,
"s": 26406,
"text": "Java"
},
{
"code": null,
"e": 26416,
"s": 26411,
"text": "Java"
},
{
"code": null,
"e": 26514,
"s": 26416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26523,
"s": 26514,
"text": "Comments"
},
{
"code": null,
"e": 26536,
"s": 26523,
"text": "Old Comments"
},
{
"code": null,
"e": 26566,
"s": 26536,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26585,
"s": 26566,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26617,
"s": 26585,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26668,
"s": 26617,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26686,
"s": 26668,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26717,
"s": 26686,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26749,
"s": 26717,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26768,
"s": 26749,
"text": "Overriding in Java"
},
{
"code": null,
"e": 26788,
"s": 26768,
"text": "Stack Class in Java"
}
] |
How do you reverse a string in place in C or C++?
|
In this section we will see how to reverse a string in place. So we will not use some other memory spaces for reversing. In C++, we can use the std::string. But for C we have to use the character array. In this program we are using the character array to take the string. Then reversing it.
Input: A string “This is a string”
Output: The reversed string “gnirts a si sihT”
Input − The string
Output − The reversed string.
len := the length of the string
i := 0 and j := (len-1)
while i < j, do
swap the characters from position i and j
i := i + 1
j := j - 1
done
Live Demo
#include <iostream>
#include<cstring>
using namespace std;
void reverse(char s[]) {
int len = strlen(s) ; //get the length of the string
int i, j;
for (i = 0, j = len - 1; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
int main() {
char s[20] = "This is a string";
cout << "Main String: " << s <<endl;
reverse(s);
cout << "Reversed String: " << s <<endl;
}
Main String: This is a string
Reversed String: gnirts a si sihT
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "In this section we will see how to reverse a string in place. So we will not use some other memory spaces for reversing. In C++, we can use the std::string. But for C we have to use the character array. In this program we are using the character array to take the string. Then reversing it."
},
{
"code": null,
"e": 1435,
"s": 1353,
"text": "Input: A string “This is a string”\nOutput: The reversed string “gnirts a si sihT”"
},
{
"code": null,
"e": 1454,
"s": 1435,
"text": "Input − The string"
},
{
"code": null,
"e": 1484,
"s": 1454,
"text": "Output − The reversed string."
},
{
"code": null,
"e": 1634,
"s": 1484,
"text": "len := the length of the string\ni := 0 and j := (len-1)\nwhile i < j, do\n swap the characters from position i and j\n i := i + 1\n j := j - 1\ndone"
},
{
"code": null,
"e": 1645,
"s": 1634,
"text": " Live Demo"
},
{
"code": null,
"e": 2026,
"s": 1645,
"text": "#include <iostream>\n#include<cstring>\nusing namespace std;\nvoid reverse(char s[]) {\n int len = strlen(s) ; //get the length of the string\n int i, j;\n for (i = 0, j = len - 1; i < j; i++, j--) {\n swap(s[i], s[j]);\n }\n}\nint main() {\n char s[20] = \"This is a string\";\n cout << \"Main String: \" << s <<endl;\n reverse(s);\n cout << \"Reversed String: \" << s <<endl;\n}"
},
{
"code": null,
"e": 2090,
"s": 2026,
"text": "Main String: This is a string\nReversed String: gnirts a si sihT"
}
] |
How to add two strings with a space in first string in JavaScript?
|
To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly.
In the following example since the string 'str1' has a space with in it, just only concatenation without space is adequate to add both the strings.
Live Demo
<html>
<body>
<script>
function str(str1, str2) {
return (str1 + str2);
}
document.write(str("tutorix is the best ","e-learning platform"));
</script>
</body>
</html>
tutorix is the best e-learning platform
In case if there is no space exist in first string then we have to create space(" ") and join the two strings as shown below.
Live Demo
<html>
<body>
<script>
function str(str1, str2) {
return (str1 + " " + str2);
}
document.write(str("tutorix is the best","e-learning platform"));
</script>
</body>
</html>
tutorix is the best e-learning platform
|
[
{
"code": null,
"e": 1249,
"s": 1062,
"text": "To add two strings we need a '+' operator to create some space between the strings, but when the first string itself has a space with in it, there is no need to assign space explicitly. "
},
{
"code": null,
"e": 1397,
"s": 1249,
"text": "In the following example since the string 'str1' has a space with in it, just only concatenation without space is adequate to add both the strings."
},
{
"code": null,
"e": 1407,
"s": 1397,
"text": "Live Demo"
},
{
"code": null,
"e": 1607,
"s": 1407,
"text": "<html>\n<body>\n <script>\n function str(str1, str2) {\n return (str1 + str2);\n }\n document.write(str(\"tutorix is the best \",\"e-learning platform\"));\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1647,
"s": 1607,
"text": "tutorix is the best e-learning platform"
},
{
"code": null,
"e": 1774,
"s": 1647,
"text": "In case if there is no space exist in first string then we have to create space(\" \") and join the two strings as shown below. "
},
{
"code": null,
"e": 1784,
"s": 1774,
"text": "Live Demo"
},
{
"code": null,
"e": 1989,
"s": 1784,
"text": "<html>\n<body>\n <script>\n function str(str1, str2) {\n return (str1 + \" \" + str2);\n }\n document.write(str(\"tutorix is the best\",\"e-learning platform\"));\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 2029,
"s": 1989,
"text": "tutorix is the best e-learning platform"
}
] |
Nearest Fibonacci Number to N
|
13 Apr, 2021
Given a positive integer N, the task is to find the nearest Fibonacci number to the given integer N. If there are two Fibonacci Numbers having same difference from N, then print the smaller value.
Examples:
Input: N = 20Output: 21Explanation: Nearest Fibonacci number to 20 is 21.
Input: N = 17Output: 13
Approach: Follow the steps below to solve the problem:
If N is equal to 0, then print 0 as the result.
Initialize a variable, say ans, to store the Fibonacci Number nearest to N.
Initialize two variables, say First as 0, and Second as 1, to store the first and second terms of the Fibonacci Series.
Store the sum of First and Second in a variable, say Third.
Iterate until the value of Third is at most N and perform the following steps: Update the value of First to Second and Second to Third.Store the sum of First and Second in the variable Third.
Update the value of First to Second and Second to Third.
Store the sum of First and Second in the variable Third.
If the absolute difference of Second and N is at most the value of Third and N, then update the value of ans as Second.
Otherwise, update the value of ans as Third.
After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the Fibonacci// number which is nearest to Nvoid nearestFibonacci(int num){ // Base Case if (num == 0) { cout << 0; return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (abs(third - num) >= abs(second - num)) ? second : third; // Print the result cout << ans;} // Driver Codeint main(){ int N = 17; nearestFibonacci(N); return 0;}
// Java program for the above approachclass GFG{ // Function to find the Fibonacci// number which is nearest to Nstatic void nearestFibonacci(int num){ // Base Case if (num == 0) { System.out.print(0); return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (Math.abs(third - num) >= Math.abs(second - num)) ? second : third; // Print the result System.out.print(ans);} // Driver Codepublic static void main (String[] args){ int N = 17; nearestFibonacci(N);}} // This code is contributed by AnkThon
# Python3 program for the above approach # Function to find the Fibonacci# number which is nearest to Ndef nearestFibonacci(num): # Base Case if (num == 0): print(0) return # Initialize the first & second # terms of the Fibonacci series first = 0 second = 1 # Store the third term third = first + second # Iterate until the third term # is less than or equal to num while (third <= num): # Update the first first = second # Update the second second = third # Update the third third = first + second # Store the Fibonacci number # having smaller difference with N if (abs(third - num) >= abs(second - num)): ans = second else: ans = third # Print the result print(ans) # Driver Codeif __name__ == '__main__': N = 17 nearestFibonacci(N) # This code is contributed by SURENDRA_GANGWAR
// C# program for the above approachusing System; class GFG{ // Function to find the Fibonacci// number which is nearest to Nstatic void nearestFibonacci(int num){ // Base Case if (num == 0) { Console.Write(0); return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (Math.Abs(third - num) >= Math.Abs(second - num)) ? second : third; // Print the result Console.Write(ans);} // Driver Codepublic static void Main(string[] args){ int N = 17; nearestFibonacci(N);}} // This code is contributed by sanjoy_62
<script>// Javascript program for the above approach // Function to find the Fibonacci// number which is nearest to Nfunction nearestFibonacci(num){ // Base Case if (num == 0) { document.write(0); return; } // Initialize the first & second // terms of the Fibonacci series let first = 0, second = 1; // Store the third term let third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N let ans = (Math.abs(third - num) >= Math.abs(second - num)) ? second : third; // Print the result document.write(ans);} // Driver Code let N = 17; nearestFibonacci(N); // This code is contributed by subhammahato348.</script>
13
Time Complexity: O(log N)Auxiliary Space: O(1)
SURENDRA_GANGWAR
ankthon
sanjoy_62
subhammahato348
Fibonacci
Numbers
Mathematical
Mathematical
Fibonacci
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Algorithm to solve Rubik's Cube
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Modulo Operator (%) in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Program for factorial of a number
Program to find sum of elements in a given array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 225,
"s": 28,
"text": "Given a positive integer N, the task is to find the nearest Fibonacci number to the given integer N. If there are two Fibonacci Numbers having same difference from N, then print the smaller value."
},
{
"code": null,
"e": 235,
"s": 225,
"text": "Examples:"
},
{
"code": null,
"e": 309,
"s": 235,
"text": "Input: N = 20Output: 21Explanation: Nearest Fibonacci number to 20 is 21."
},
{
"code": null,
"e": 333,
"s": 309,
"text": "Input: N = 17Output: 13"
},
{
"code": null,
"e": 388,
"s": 333,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 436,
"s": 388,
"text": "If N is equal to 0, then print 0 as the result."
},
{
"code": null,
"e": 512,
"s": 436,
"text": "Initialize a variable, say ans, to store the Fibonacci Number nearest to N."
},
{
"code": null,
"e": 632,
"s": 512,
"text": "Initialize two variables, say First as 0, and Second as 1, to store the first and second terms of the Fibonacci Series."
},
{
"code": null,
"e": 692,
"s": 632,
"text": "Store the sum of First and Second in a variable, say Third."
},
{
"code": null,
"e": 884,
"s": 692,
"text": "Iterate until the value of Third is at most N and perform the following steps: Update the value of First to Second and Second to Third.Store the sum of First and Second in the variable Third."
},
{
"code": null,
"e": 941,
"s": 884,
"text": "Update the value of First to Second and Second to Third."
},
{
"code": null,
"e": 998,
"s": 941,
"text": "Store the sum of First and Second in the variable Third."
},
{
"code": null,
"e": 1118,
"s": 998,
"text": "If the absolute difference of Second and N is at most the value of Third and N, then update the value of ans as Second."
},
{
"code": null,
"e": 1163,
"s": 1118,
"text": "Otherwise, update the value of ans as Third."
},
{
"code": null,
"e": 1235,
"s": 1163,
"text": "After completing the above steps, print the value of ans as the result."
},
{
"code": null,
"e": 1286,
"s": 1235,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1290,
"s": 1286,
"text": "C++"
},
{
"code": null,
"e": 1295,
"s": 1290,
"text": "Java"
},
{
"code": null,
"e": 1303,
"s": 1295,
"text": "Python3"
},
{
"code": null,
"e": 1306,
"s": 1303,
"text": "C#"
},
{
"code": null,
"e": 1317,
"s": 1306,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the Fibonacci// number which is nearest to Nvoid nearestFibonacci(int num){ // Base Case if (num == 0) { cout << 0; return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (abs(third - num) >= abs(second - num)) ? second : third; // Print the result cout << ans;} // Driver Codeint main(){ int N = 17; nearestFibonacci(N); return 0;}",
"e": 2308,
"s": 1317,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to find the Fibonacci// number which is nearest to Nstatic void nearestFibonacci(int num){ // Base Case if (num == 0) { System.out.print(0); return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (Math.abs(third - num) >= Math.abs(second - num)) ? second : third; // Print the result System.out.print(ans);} // Driver Codepublic static void main (String[] args){ int N = 17; nearestFibonacci(N);}} // This code is contributed by AnkThon",
"e": 3366,
"s": 2308,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the Fibonacci# number which is nearest to Ndef nearestFibonacci(num): # Base Case if (num == 0): print(0) return # Initialize the first & second # terms of the Fibonacci series first = 0 second = 1 # Store the third term third = first + second # Iterate until the third term # is less than or equal to num while (third <= num): # Update the first first = second # Update the second second = third # Update the third third = first + second # Store the Fibonacci number # having smaller difference with N if (abs(third - num) >= abs(second - num)): ans = second else: ans = third # Print the result print(ans) # Driver Codeif __name__ == '__main__': N = 17 nearestFibonacci(N) # This code is contributed by SURENDRA_GANGWAR",
"e": 4314,
"s": 3366,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the Fibonacci// number which is nearest to Nstatic void nearestFibonacci(int num){ // Base Case if (num == 0) { Console.Write(0); return; } // Initialize the first & second // terms of the Fibonacci series int first = 0, second = 1; // Store the third term int third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N int ans = (Math.Abs(third - num) >= Math.Abs(second - num)) ? second : third; // Print the result Console.Write(ans);} // Driver Codepublic static void Main(string[] args){ int N = 17; nearestFibonacci(N);}} // This code is contributed by sanjoy_62",
"e": 5382,
"s": 4314,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to find the Fibonacci// number which is nearest to Nfunction nearestFibonacci(num){ // Base Case if (num == 0) { document.write(0); return; } // Initialize the first & second // terms of the Fibonacci series let first = 0, second = 1; // Store the third term let third = first + second; // Iterate until the third term // is less than or equal to num while (third <= num) { // Update the first first = second; // Update the second second = third; // Update the third third = first + second; } // Store the Fibonacci number // having smaller difference with N let ans = (Math.abs(third - num) >= Math.abs(second - num)) ? second : third; // Print the result document.write(ans);} // Driver Code let N = 17; nearestFibonacci(N); // This code is contributed by subhammahato348.</script>",
"e": 6400,
"s": 5382,
"text": null
},
{
"code": null,
"e": 6403,
"s": 6400,
"text": "13"
},
{
"code": null,
"e": 6452,
"s": 6405,
"text": "Time Complexity: O(log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6469,
"s": 6452,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 6477,
"s": 6469,
"text": "ankthon"
},
{
"code": null,
"e": 6487,
"s": 6477,
"text": "sanjoy_62"
},
{
"code": null,
"e": 6503,
"s": 6487,
"text": "subhammahato348"
},
{
"code": null,
"e": 6513,
"s": 6503,
"text": "Fibonacci"
},
{
"code": null,
"e": 6521,
"s": 6513,
"text": "Numbers"
},
{
"code": null,
"e": 6534,
"s": 6521,
"text": "Mathematical"
},
{
"code": null,
"e": 6547,
"s": 6534,
"text": "Mathematical"
},
{
"code": null,
"e": 6557,
"s": 6547,
"text": "Fibonacci"
},
{
"code": null,
"e": 6565,
"s": 6557,
"text": "Numbers"
},
{
"code": null,
"e": 6663,
"s": 6565,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6687,
"s": 6663,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 6708,
"s": 6687,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 6722,
"s": 6708,
"text": "Prime Numbers"
},
{
"code": null,
"e": 6754,
"s": 6722,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 6791,
"s": 6754,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 6834,
"s": 6791,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 6877,
"s": 6834,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 6904,
"s": 6877,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 6938,
"s": 6904,
"text": "Program for factorial of a number"
}
] |
Iterate over characters of a string in C++
|
24 Nov, 2020
Given a string str of length N, the task is to traverse the string and print all the characters of the given string.
Examples:
Input: str = “GeeksforGeeks”Output: G e e k s f o r G e e k s
Input: str = “Coder”Output: C o d e r
Naive Approach: The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using variable i and print the value of str[i].
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the characters of the stringvoid TraverseString(string &str, int N){ // Traverse the string for (int i = 0; i < N; i++) { // Print current character cout<< str[i]<< " "; } } // Driver Codeint main(){ string str = "GeeksforGeeks"; // Stores length of the string int N = str.length(); TraverseString(str, N);}
G e e k s f o r G e e k s
Time Complexity: O(N)Auxiliary Space: O(1)
Auto keyword – based Approach: The string can be traversed using auto iterator.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){ // Traverse the string for (auto &ch : str) { // Print current character cout<< ch<< " "; }}// Driver Codeint main(){ string str = "GeeksforGeeks"; // Stores length of the string int N = str.length(); TraverseString(str, N);}
G e e k s f o r G e e k s
Time Complexity: O(N)Auxiliary Space: O(1)
Iterator – based Approach: The string can be traversed using iterator.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){ // Stores address of // a character of str string:: iterator it; // Traverse the string for (it = str.begin(); it != str.end(); it++) { // Print current character cout<< *it<< " "; }} // Driver Codeint main(){ string str = "GeeksforGeeks"; // Stores length of the string int N = str.length(); TraverseString(str, N);}
G e e k s f o r G e e k s
Time Complexity: O(N)Auxiliary Space: O(1)
cpp-iterator
cpp-string
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Nov, 2020"
},
{
"code": null,
"e": 145,
"s": 28,
"text": "Given a string str of length N, the task is to traverse the string and print all the characters of the given string."
},
{
"code": null,
"e": 155,
"s": 145,
"text": "Examples:"
},
{
"code": null,
"e": 217,
"s": 155,
"text": "Input: str = “GeeksforGeeks”Output: G e e k s f o r G e e k s"
},
{
"code": null,
"e": 255,
"s": 217,
"text": "Input: str = “Coder”Output: C o d e r"
},
{
"code": null,
"e": 453,
"s": 255,
"text": "Naive Approach: The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using variable i and print the value of str[i]."
},
{
"code": null,
"e": 504,
"s": 453,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 508,
"s": 504,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the characters of the stringvoid TraverseString(string &str, int N){ // Traverse the string for (int i = 0; i < N; i++) { // Print current character cout<< str[i]<< \" \"; } } // Driver Codeint main(){ string str = \"GeeksforGeeks\"; // Stores length of the string int N = str.length(); TraverseString(str, N);}",
"e": 1011,
"s": 508,
"text": null
},
{
"code": null,
"e": 1038,
"s": 1011,
"text": "G e e k s f o r G e e k s\n"
},
{
"code": null,
"e": 1081,
"s": 1038,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1161,
"s": 1081,
"text": "Auto keyword – based Approach: The string can be traversed using auto iterator."
},
{
"code": null,
"e": 1212,
"s": 1161,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1216,
"s": 1212,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){ // Traverse the string for (auto &ch : str) { // Print current character cout<< ch<< \" \"; }}// Driver Codeint main(){ string str = \"GeeksforGeeks\"; // Stores length of the string int N = str.length(); TraverseString(str, N);}",
"e": 1693,
"s": 1216,
"text": null
},
{
"code": null,
"e": 1720,
"s": 1693,
"text": "G e e k s f o r G e e k s\n"
},
{
"code": null,
"e": 1763,
"s": 1720,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1834,
"s": 1763,
"text": "Iterator – based Approach: The string can be traversed using iterator."
},
{
"code": null,
"e": 1885,
"s": 1834,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1889,
"s": 1885,
"text": "C++"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to traverse the string and// print the elements of the stringvoid TraverseString(string &str, int N){ // Stores address of // a character of str string:: iterator it; // Traverse the string for (it = str.begin(); it != str.end(); it++) { // Print current character cout<< *it<< \" \"; }} // Driver Codeint main(){ string str = \"GeeksforGeeks\"; // Stores length of the string int N = str.length(); TraverseString(str, N);}",
"e": 2521,
"s": 1889,
"text": null
},
{
"code": null,
"e": 2548,
"s": 2521,
"text": "G e e k s f o r G e e k s\n"
},
{
"code": null,
"e": 2591,
"s": 2548,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2604,
"s": 2591,
"text": "cpp-iterator"
},
{
"code": null,
"e": 2615,
"s": 2604,
"text": "cpp-string"
},
{
"code": null,
"e": 2619,
"s": 2615,
"text": "C++"
},
{
"code": null,
"e": 2627,
"s": 2619,
"text": "Strings"
},
{
"code": null,
"e": 2635,
"s": 2627,
"text": "Strings"
},
{
"code": null,
"e": 2639,
"s": 2635,
"text": "CPP"
}
] |
VLAN Trunking Protocol (VTP)
|
15 Jun, 2022
To carry traffic of a VLAN, it must be first configured on the switch. Suppose, if user wants to send a frame from source to destination and the shortest path between them contains 1000 switches. To process a frame of any VLAN, VLANs should be configured first so, have to configure the same VLANs on all the 1000 switches manually. It will not be possible for the administrator to do that. Here comes VTP to the rescue.
VLAN Trunking Protocol (VTP) – VTP is CISCO proprietary protocol used to maintain consistency throughout the network or user can say that synchronizing the VLAN information in same VTP domain. VTP allows you to add, delete and rename VLANs which is then propagated to other switches in the VTP domain. VTP advertisements can be sent over 802.1Q, and ISL trunks.
Requirements – There are some requirements for VTP to communicate VLAN information between switches. These are:
The VTP version must be same on the switches user wants to configureVTP domain name must be same on the switchesOne of the switches must be a serverAuthentication should match if applied
The VTP version must be same on the switches user wants to configure
VTP domain name must be same on the switches
One of the switches must be a server
Authentication should match if applied
VTP modes – There are 3 modes:
Server – The switches are set to this mode by default. This mode allows you to create, add and delete VLANs. The changes you want to make should be done in this mode. Any changes that is done on this mode(on a particular switch) will be advertised to all the switches that are in same VTP domain. In this mode, the configuration are saved in NVRAM.
Configuration – User will first make the switch VTP server
Switch# config terminal
Switch(config)#vtp mode server
Now, User has to make a VTP domain assign a password for authentication.
Switch(config)#vtp domain geeksforgeeks
Switch(config)#vtp password hardwork
User can verify the configuration by:
Switch(config)#do should vtp password
Switch(config)#do show vtp
Client – In this mode, the switches receives the updates and can also forward the updates to other switches(which are in same VTP domain). The updates received here is not saved in NVRAM so all the configuration will be deleted if the switch is reset or reloaded i.e the switches will only learn and pass the VTP summary advertisements to the other switches.
Configuration – As the switches are set to server mode by default, therefore user can change it to client mode by:
Switch(config)#vtp mode client
Transparent – This mode only forwards the VTP summary advertisements through trunk link. The transparent mode switches can make their own local database which keep secret from other switches. The whole purpose of transparent mode is to forward the VTP summary advertisements but not to take part in the VLAN assignments.
Configuration – User can change the mode to transparent by
Switch(config)#vtp mode transparent
Configuration Revision Number – The configuration revision number is a 32-bit number that indicates the level of revision for a VTP packet. This configuration number is tracked by every switch in order to find that the received information is more recent than the current version. Everytime one modification is done on the VLANs by the server switch, the configuration revision number increases by one. The client mode devices receives it and check if the configuration revision number that they received are latest or not by comparing it’s own configuration number by the number received. If the configuration number is greater than their own number then the devices update their configuration and pass it to other clients of the same VTP domain. If the configuration number is same then the devices just pass it to other clients of the same VTP domain. User can check the configuration revision number by:
switch(config)#do show vtp status
abhishekpal97854368
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 450,
"s": 28,
"text": "To carry traffic of a VLAN, it must be first configured on the switch. Suppose, if user wants to send a frame from source to destination and the shortest path between them contains 1000 switches. To process a frame of any VLAN, VLANs should be configured first so, have to configure the same VLANs on all the 1000 switches manually. It will not be possible for the administrator to do that. Here comes VTP to the rescue. "
},
{
"code": null,
"e": 813,
"s": 450,
"text": "VLAN Trunking Protocol (VTP) – VTP is CISCO proprietary protocol used to maintain consistency throughout the network or user can say that synchronizing the VLAN information in same VTP domain. VTP allows you to add, delete and rename VLANs which is then propagated to other switches in the VTP domain. VTP advertisements can be sent over 802.1Q, and ISL trunks. "
},
{
"code": null,
"e": 925,
"s": 813,
"text": "Requirements – There are some requirements for VTP to communicate VLAN information between switches. These are:"
},
{
"code": null,
"e": 1112,
"s": 925,
"text": "The VTP version must be same on the switches user wants to configureVTP domain name must be same on the switchesOne of the switches must be a serverAuthentication should match if applied"
},
{
"code": null,
"e": 1181,
"s": 1112,
"text": "The VTP version must be same on the switches user wants to configure"
},
{
"code": null,
"e": 1226,
"s": 1181,
"text": "VTP domain name must be same on the switches"
},
{
"code": null,
"e": 1263,
"s": 1226,
"text": "One of the switches must be a server"
},
{
"code": null,
"e": 1302,
"s": 1263,
"text": "Authentication should match if applied"
},
{
"code": null,
"e": 1333,
"s": 1302,
"text": "VTP modes – There are 3 modes:"
},
{
"code": null,
"e": 1683,
"s": 1333,
"text": "Server – The switches are set to this mode by default. This mode allows you to create, add and delete VLANs. The changes you want to make should be done in this mode. Any changes that is done on this mode(on a particular switch) will be advertised to all the switches that are in same VTP domain. In this mode, the configuration are saved in NVRAM. "
},
{
"code": null,
"e": 1742,
"s": 1683,
"text": "Configuration – User will first make the switch VTP server"
},
{
"code": null,
"e": 1797,
"s": 1742,
"text": "Switch# config terminal\nSwitch(config)#vtp mode server"
},
{
"code": null,
"e": 1870,
"s": 1797,
"text": "Now, User has to make a VTP domain assign a password for authentication."
},
{
"code": null,
"e": 1947,
"s": 1870,
"text": "Switch(config)#vtp domain geeksforgeeks\nSwitch(config)#vtp password hardwork"
},
{
"code": null,
"e": 1985,
"s": 1947,
"text": "User can verify the configuration by:"
},
{
"code": null,
"e": 2052,
"s": 1985,
"text": "Switch(config)#do should vtp password \nSwitch(config)#do show vtp "
},
{
"code": null,
"e": 2412,
"s": 2052,
"text": "Client – In this mode, the switches receives the updates and can also forward the updates to other switches(which are in same VTP domain). The updates received here is not saved in NVRAM so all the configuration will be deleted if the switch is reset or reloaded i.e the switches will only learn and pass the VTP summary advertisements to the other switches. "
},
{
"code": null,
"e": 2527,
"s": 2412,
"text": "Configuration – As the switches are set to server mode by default, therefore user can change it to client mode by:"
},
{
"code": null,
"e": 2559,
"s": 2527,
"text": "Switch(config)#vtp mode client "
},
{
"code": null,
"e": 2881,
"s": 2559,
"text": "Transparent – This mode only forwards the VTP summary advertisements through trunk link. The transparent mode switches can make their own local database which keep secret from other switches. The whole purpose of transparent mode is to forward the VTP summary advertisements but not to take part in the VLAN assignments. "
},
{
"code": null,
"e": 2940,
"s": 2881,
"text": "Configuration – User can change the mode to transparent by"
},
{
"code": null,
"e": 2977,
"s": 2940,
"text": "Switch(config)#vtp mode transparent "
},
{
"code": null,
"e": 3885,
"s": 2977,
"text": "Configuration Revision Number – The configuration revision number is a 32-bit number that indicates the level of revision for a VTP packet. This configuration number is tracked by every switch in order to find that the received information is more recent than the current version. Everytime one modification is done on the VLANs by the server switch, the configuration revision number increases by one. The client mode devices receives it and check if the configuration revision number that they received are latest or not by comparing it’s own configuration number by the number received. If the configuration number is greater than their own number then the devices update their configuration and pass it to other clients of the same VTP domain. If the configuration number is same then the devices just pass it to other clients of the same VTP domain. User can check the configuration revision number by:"
},
{
"code": null,
"e": 3920,
"s": 3885,
"text": "switch(config)#do show vtp status "
},
{
"code": null,
"e": 3940,
"s": 3920,
"text": "abhishekpal97854368"
},
{
"code": null,
"e": 3958,
"s": 3940,
"text": "Computer Networks"
},
{
"code": null,
"e": 3976,
"s": 3958,
"text": "Computer Networks"
}
] |
Algorithms | Recursion | Question 5 - GeeksforGeeks
|
28 Jun, 2021
What does fun2() do in general?
int fun(int x, int y){ if (y == 0) return 0; return (x + fun(x, y-1));} int fun2(int a, int b){ if (b == 0) return 1; return fun(a, fun2(a, b-1));}
(A) x*y(B) x+x*y(C) xy(D) yxAnswer: (C)Explanation: The function multiplies x to itself y times which is xy.Quiz of this Question
Algorithms-Recursion
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Graph Traversals | Question 2
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 12
Algorithms | Graph Traversals | Question 1
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Analysis of Algorithms | Question 8
Algorithms | Sorting | Question 5
Algorithms | Sorting | Question 7
Algorithms | Sorting | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
|
[
{
"code": null,
"e": 25086,
"s": 25058,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25118,
"s": 25086,
"text": "What does fun2() do in general?"
},
{
"code": "int fun(int x, int y){ if (y == 0) return 0; return (x + fun(x, y-1));} int fun2(int a, int b){ if (b == 0) return 1; return fun(a, fun2(a, b-1));}",
"e": 25281,
"s": 25118,
"text": null
},
{
"code": null,
"e": 25411,
"s": 25281,
"text": "(A) x*y(B) x+x*y(C) xy(D) yxAnswer: (C)Explanation: The function multiplies x to itself y times which is xy.Quiz of this Question"
},
{
"code": null,
"e": 25432,
"s": 25411,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 25448,
"s": 25432,
"text": "Algorithms Quiz"
},
{
"code": null,
"e": 25546,
"s": 25448,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25589,
"s": 25546,
"text": "Algorithms | Graph Traversals | Question 2"
},
{
"code": null,
"e": 25633,
"s": 25589,
"text": "Algorithms | Graph Traversals | Question 12"
},
{
"code": null,
"e": 25677,
"s": 25633,
"text": "Algorithms | Graph Traversals | Question 12"
},
{
"code": null,
"e": 25720,
"s": 25677,
"text": "Algorithms | Graph Traversals | Question 1"
},
{
"code": null,
"e": 25770,
"s": 25720,
"text": "Algorithms | Analysis of Algorithms | Question 17"
},
{
"code": null,
"e": 25819,
"s": 25770,
"text": "Algorithms | Analysis of Algorithms | Question 8"
},
{
"code": null,
"e": 25853,
"s": 25819,
"text": "Algorithms | Sorting | Question 5"
},
{
"code": null,
"e": 25887,
"s": 25853,
"text": "Algorithms | Sorting | Question 7"
},
{
"code": null,
"e": 25921,
"s": 25887,
"text": "Algorithms | Sorting | Question 1"
}
] |
How to create circular progress bar using SVG ?
|
28 Jun, 2021
In this article, we will learn how to create a circular progress bar using SVG.
Let us begin with the HTML part. In the SVG circle, the cx and cy attributes define the x and y coordinates of the circle. If cx and cy are not taken to the circle’s center, it is set to (0,0). The r attribute defines the radius of the circle. Span is an inline character container used to mark up a part of a text. It can be easily styled by CSS. Span is much like an HTML div element, but div is a block-level element. The div block visually isolates a section of a document on the page and may contain other block-level components.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css" /> <title>Circle progress bar</title></head> <body> <div class="circle_box"> <div> <svg> <circle cx="100" cy="100" r="95" /> <circle cx="100" cy="100" r="95" /> </svg> <span>90%</span> </div> <strong>c++ developer</strong> </div> <div class="circle_box"> <div> <svg> <circle cx="100" cy="100" r="95" /> <circle cx="100" cy="100" r="95" /> </svg> <span>75%</span> </div> <strong>python developer</strong> </div> <div class="circle_box"> <div> <svg> <circle cx="100" cy="100" r="95" /> <circle cx="100" cy="100" r="95" /> </svg> <span>40%</span> </div> <strong>php developer</strong> </div></body> </html>
The CSS box-sizing allows us to include padding and border in an element’s total width and height. The CSS transform property gives a 2D or 3D transformation to an element. The property allows to rotate, move, etc. The overflow property helps to clip the content. The stroke-width is used for setting the width of the border on SVG shapes.
Nth-child matches every element that is the nth child of its parent. N can be a number, a keyword, or a formula. The stroke-dash-offset defines the location along an SVG path where the dash of a stroke will begin. The stroke-dash-array property is used for creating dashes in the stroke of SVG Shapes. The CSS calc() function performs calculations when specifying CSS property values. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
style.css
*,*:after,*:before{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box;}body{ font-family: arial; font-size: 16px; margin: 0; background: #122325; display: flex; align-items: center; justify-content: space-around; height: 100vh;} svg{ width: 200px; height: 200px; transform: rotate(-90deg); overflow: initial;} circle{ stroke-width:20px; fill:none; }circle:nth-child(1){ stroke: #fff }circle:nth-child(2){ stroke: #f00; position: relative; z-index: 1; }.circle_box:nth-child(1) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 90) / 100); stroke-position: inside;}.circle_box:nth-child(2) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 75) / 100); stroke: rgb(37, 224, 109); }.circle_box:nth-child(3) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 40) / 100); stroke: rgb(227, 241, 25); }.circle_box{ font-size: 36px; color: #fff; text-align: center;}.circle_box div{ position: relative;}.circle_box span{ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); color: #fff; font-size: 40px;}
Output: Now, as you can see in the output, we have created a beautiful progress chart, which will attract readers to read the progress of a person in a programming language.
CSS-Properties
HTML-Questions
HTML-SVG
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 108,
"s": 28,
"text": "In this article, we will learn how to create a circular progress bar using SVG."
},
{
"code": null,
"e": 643,
"s": 108,
"text": "Let us begin with the HTML part. In the SVG circle, the cx and cy attributes define the x and y coordinates of the circle. If cx and cy are not taken to the circle’s center, it is set to (0,0). The r attribute defines the radius of the circle. Span is an inline character container used to mark up a part of a text. It can be easily styled by CSS. Span is much like an HTML div element, but div is a block-level element. The div block visually isolates a section of a document on the page and may contain other block-level components."
},
{
"code": null,
"e": 648,
"s": 643,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"style.css\" /> <title>Circle progress bar</title></head> <body> <div class=\"circle_box\"> <div> <svg> <circle cx=\"100\" cy=\"100\" r=\"95\" /> <circle cx=\"100\" cy=\"100\" r=\"95\" /> </svg> <span>90%</span> </div> <strong>c++ developer</strong> </div> <div class=\"circle_box\"> <div> <svg> <circle cx=\"100\" cy=\"100\" r=\"95\" /> <circle cx=\"100\" cy=\"100\" r=\"95\" /> </svg> <span>75%</span> </div> <strong>python developer</strong> </div> <div class=\"circle_box\"> <div> <svg> <circle cx=\"100\" cy=\"100\" r=\"95\" /> <circle cx=\"100\" cy=\"100\" r=\"95\" /> </svg> <span>40%</span> </div> <strong>php developer</strong> </div></body> </html>",
"e": 1779,
"s": 648,
"text": null
},
{
"code": null,
"e": 2120,
"s": 1779,
"text": "The CSS box-sizing allows us to include padding and border in an element’s total width and height. The CSS transform property gives a 2D or 3D transformation to an element. The property allows to rotate, move, etc. The overflow property helps to clip the content. The stroke-width is used for setting the width of the border on SVG shapes. "
},
{
"code": null,
"e": 2662,
"s": 2120,
"text": "Nth-child matches every element that is the nth child of its parent. N can be a number, a keyword, or a formula. The stroke-dash-offset defines the location along an SVG path where the dash of a stroke will begin. The stroke-dash-array property is used for creating dashes in the stroke of SVG Shapes. The CSS calc() function performs calculations when specifying CSS property values. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values."
},
{
"code": null,
"e": 2672,
"s": 2662,
"text": "style.css"
},
{
"code": "*,*:after,*:before{ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box;}body{ font-family: arial; font-size: 16px; margin: 0; background: #122325; display: flex; align-items: center; justify-content: space-around; height: 100vh;} svg{ width: 200px; height: 200px; transform: rotate(-90deg); overflow: initial;} circle{ stroke-width:20px; fill:none; }circle:nth-child(1){ stroke: #fff }circle:nth-child(2){ stroke: #f00; position: relative; z-index: 1; }.circle_box:nth-child(1) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 90) / 100); stroke-position: inside;}.circle_box:nth-child(2) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 75) / 100); stroke: rgb(37, 224, 109); }.circle_box:nth-child(3) circle:nth-child(2){ stroke-dashoffset:calc(100 * 6); stroke-dasharray:calc(100 * 6); stroke-dashoffset:calc((100 * 6) - ((100 * 6) * 40) / 100); stroke: rgb(227, 241, 25); }.circle_box{ font-size: 36px; color: #fff; text-align: center;}.circle_box div{ position: relative;}.circle_box span{ position: absolute; left: 50%; top:50%; transform: translate(-50%,-50%); color: #fff; font-size: 40px;}",
"e": 4148,
"s": 2672,
"text": null
},
{
"code": null,
"e": 4322,
"s": 4148,
"text": "Output: Now, as you can see in the output, we have created a beautiful progress chart, which will attract readers to read the progress of a person in a programming language."
},
{
"code": null,
"e": 4337,
"s": 4322,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4352,
"s": 4337,
"text": "HTML-Questions"
},
{
"code": null,
"e": 4361,
"s": 4352,
"text": "HTML-SVG"
},
{
"code": null,
"e": 4368,
"s": 4361,
"text": "Picked"
},
{
"code": null,
"e": 4372,
"s": 4368,
"text": "CSS"
},
{
"code": null,
"e": 4377,
"s": 4372,
"text": "HTML"
},
{
"code": null,
"e": 4394,
"s": 4377,
"text": "Web Technologies"
},
{
"code": null,
"e": 4399,
"s": 4394,
"text": "HTML"
}
] |
Difference Between keySet() and entrySet() Method in Java Map
|
02 Jun, 2022
Map Interface is present in Java.util package, which provides mainly three methods KeySet(),entrySet() and values(). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use these methods with all the classes implementing the map interface like TreeMap, HashMap, and LinkedHashMap.
keySet() Method:
The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
Syntax:
hash_map.keySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the keys of the hash map.
Java
// Java program demonstrating use of keySet() import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.stream.Stream; class GFG { public static void main(String[] args) { // making map of Integer keys and String values Map<Integer, String> map = new HashMap<>(); // adding the key-value pairs to map map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); // below are the different and simple ways out of // many to iterate over the keySet() // iterating the keySet() using iterator Iterator<Integer> itr = map.keySet().iterator(); while (itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(); // iterating the keySet() using for loop for (Integer key : map.keySet()) { System.out.print(key + " "); } System.out.println(); // iterating over the keySet() by converting the map // to the string System.out.println(map.keySet().toString()); }}
1 2 3
1 2 3
[1, 2, 3]
entrySet() Method:
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them.
Syntax:
hash_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the hash map.
Java
// Java program demonstrating use of entrySet() import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.stream.Stream; class GFG { public static void main(String[] args) { // making map of Integer keys and String values Map<Integer, String> map = new HashMap<>(); // adding the key-value pairs to map map.put(1, "Geeks"); map.put(2, "For"); map.put(3, "Geeks"); // below are the different and simple ways out of // many to iterate over the entrySet() // iterating the key value pair using for each loop for (Map.Entry<Integer, String> entry :map.entrySet()) { Integer key = (Integer)entry.getKey(); String value = entry.getValue(); System.out.println(key + "=" + value); } // iterating the key-value pairs using iterator Iterator<Map.Entry<Integer, String> > itr = map.entrySet().iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } // iterating the key-value pairs using Stream.of() // method Stream.of(map.entrySet().toArray()) .forEach(System.out::println); }}
1=Geeks
2=For
3=Geeks
1=Geeks
2=For
3=Geeks
1=Geeks
2=For
3=Geeks
Its syntax is -:
hashmap.keySet()
Its syntax is -:
hashmap.entrySet()
avijitpaul16july
mayank007rawa
Java-Collections
java-map
Picked
Technical Scripter 2020
Difference Between
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Compile-time and Run-time Polymorphism in Java
Similarities and Difference between Java and C++
Difference between DELETE and TRUNCATE
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 458,
"s": 52,
"text": "Map Interface is present in Java.util package, which provides mainly three methods KeySet(),entrySet() and values(). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use these methods with all the classes implementing the map interface like TreeMap, HashMap, and LinkedHashMap."
},
{
"code": null,
"e": 475,
"s": 458,
"text": "keySet() Method:"
},
{
"code": null,
"e": 703,
"s": 475,
"text": "The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them."
},
{
"code": null,
"e": 711,
"s": 703,
"text": "Syntax:"
},
{
"code": null,
"e": 729,
"s": 711,
"text": "hash_map.keySet()"
},
{
"code": null,
"e": 781,
"s": 729,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 853,
"s": 781,
"text": "Return Value: The method returns a set having the keys of the hash map."
},
{
"code": null,
"e": 858,
"s": 853,
"text": "Java"
},
{
"code": "// Java program demonstrating use of keySet() import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.stream.Stream; class GFG { public static void main(String[] args) { // making map of Integer keys and String values Map<Integer, String> map = new HashMap<>(); // adding the key-value pairs to map map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); // below are the different and simple ways out of // many to iterate over the keySet() // iterating the keySet() using iterator Iterator<Integer> itr = map.keySet().iterator(); while (itr.hasNext()) { System.out.print(itr.next() + \" \"); } System.out.println(); // iterating the keySet() using for loop for (Integer key : map.keySet()) { System.out.print(key + \" \"); } System.out.println(); // iterating over the keySet() by converting the map // to the string System.out.println(map.keySet().toString()); }}",
"e": 1963,
"s": 858,
"text": null
},
{
"code": null,
"e": 1987,
"s": 1963,
"text": "1 2 3 \n1 2 3 \n[1, 2, 3]"
},
{
"code": null,
"e": 2006,
"s": 1987,
"text": "entrySet() Method:"
},
{
"code": null,
"e": 2243,
"s": 2006,
"text": "The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map or we can create a new set and store the map elements into them."
},
{
"code": null,
"e": 2251,
"s": 2243,
"text": "Syntax:"
},
{
"code": null,
"e": 2271,
"s": 2251,
"text": "hash_map.entrySet()"
},
{
"code": null,
"e": 2323,
"s": 2271,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 2400,
"s": 2323,
"text": "Return Value: The method returns a set having same elements as the hash map."
},
{
"code": null,
"e": 2405,
"s": 2400,
"text": "Java"
},
{
"code": "// Java program demonstrating use of entrySet() import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.stream.Stream; class GFG { public static void main(String[] args) { // making map of Integer keys and String values Map<Integer, String> map = new HashMap<>(); // adding the key-value pairs to map map.put(1, \"Geeks\"); map.put(2, \"For\"); map.put(3, \"Geeks\"); // below are the different and simple ways out of // many to iterate over the entrySet() // iterating the key value pair using for each loop for (Map.Entry<Integer, String> entry :map.entrySet()) { Integer key = (Integer)entry.getKey(); String value = entry.getValue(); System.out.println(key + \"=\" + value); } // iterating the key-value pairs using iterator Iterator<Map.Entry<Integer, String> > itr = map.entrySet().iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } // iterating the key-value pairs using Stream.of() // method Stream.of(map.entrySet().toArray()) .forEach(System.out::println); }}",
"e": 3649,
"s": 2405,
"text": null
},
{
"code": null,
"e": 3715,
"s": 3649,
"text": "1=Geeks\n2=For\n3=Geeks\n1=Geeks\n2=For\n3=Geeks\n1=Geeks\n2=For\n3=Geeks"
},
{
"code": null,
"e": 3732,
"s": 3715,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3749,
"s": 3732,
"text": "hashmap.keySet()"
},
{
"code": null,
"e": 3766,
"s": 3749,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 3785,
"s": 3766,
"text": "hashmap.entrySet()"
},
{
"code": null,
"e": 3802,
"s": 3785,
"text": "avijitpaul16july"
},
{
"code": null,
"e": 3816,
"s": 3802,
"text": "mayank007rawa"
},
{
"code": null,
"e": 3833,
"s": 3816,
"text": "Java-Collections"
},
{
"code": null,
"e": 3842,
"s": 3833,
"text": "java-map"
},
{
"code": null,
"e": 3849,
"s": 3842,
"text": "Picked"
},
{
"code": null,
"e": 3873,
"s": 3849,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3892,
"s": 3873,
"text": "Difference Between"
},
{
"code": null,
"e": 3897,
"s": 3892,
"text": "Java"
},
{
"code": null,
"e": 3916,
"s": 3897,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3921,
"s": 3916,
"text": "Java"
},
{
"code": null,
"e": 3938,
"s": 3921,
"text": "Java-Collections"
},
{
"code": null,
"e": 4036,
"s": 3938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4097,
"s": 4036,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4165,
"s": 4097,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 4231,
"s": 4165,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 4280,
"s": 4231,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 4319,
"s": 4280,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 4334,
"s": 4319,
"text": "Arrays in Java"
},
{
"code": null,
"e": 4378,
"s": 4334,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 4414,
"s": 4378,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 4439,
"s": 4414,
"text": "Reverse a string in Java"
}
] |
Skew Heap
|
03 Feb, 2021
A skew heap (or self – adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied :
The general heap order must be there (root is minimum and same is recursively true for subtrees), but balanced property (all levels must be full except the last) is not required.Main operation in Skew Heaps is Merge. We can implement other operations like insert, extractMin(), etc using Merge only.
The general heap order must be there (root is minimum and same is recursively true for subtrees), but balanced property (all levels must be full except the last) is not required.
Main operation in Skew Heaps is Merge. We can implement other operations like insert, extractMin(), etc using Merge only.
Example : 1. Consider the skew heap 1 to be
2. The second heap to be considered
4. And we obtain the final merged tree as
Recursive Merge Process : merge(h1, h2)
Let h1 and h2 be the two min skew heaps to be merged. Let h1’s root be smaller than h2’s root (If not smaller, we can swap to get the same).We swap h1->left and h1->right.h1->left = merge(h2, h1->left)
Let h1 and h2 be the two min skew heaps to be merged. Let h1’s root be smaller than h2’s root (If not smaller, we can swap to get the same).
We swap h1->left and h1->right.
h1->left = merge(h2, h1->left)
Examples :
Let h1 be
10
/ \
20 30
/ /
40 50
Let h2 be
15
/ \
25 35
/ \
45 55
After swapping h1->left and h1->right, we get
10
/ \
30 20
/ /
50 40
Now we recursively Merge
30
/ AND
50
15
/ \
25 35
/ \
45 55
After recursive merge, we get (Please do it
using pen and paper).
15
/ \
30 25
/ \ / \
35 50 45 55
We make this merged tree as left of original
h1 and we get following result.
10
/ \
15 20
/ \ /
30 25 40
/ \ / \
35 40 45 55
For visualization : https://www.cs.usfca.edu/~galles/JavascriptVisual/LeftistHeap.html
CPP
// CPP program to implement Skew Heap// operations.#include <bits/stdc++.h>using namespace std; struct SkewHeap{ int key; SkewHeap* right; SkewHeap* left; // constructor to make a new // node of heap SkewHeap() { key = 0; right = NULL; left = NULL; } // the special merge function that's // used in most of the other operations // also SkewHeap* merge(SkewHeap* h1, SkewHeap* h2) { // If one of the heaps is empty if (h1 == NULL) return h2; if (h2 == NULL) return h1; // Make sure that h1 has smaller // key. if (h1->key > h2->key) swap(h1, h2); // Swap h1->left and h1->right swap(h1->left, h1->right); // Merge h2 and h1->left and make // merged tree as left of h1. h1->left = merge(h2, h1->left); return h1; } // function to construct heap using // values in the array SkewHeap* construct(SkewHeap* root, int heap[], int n) { SkewHeap* temp; for (int i = 0; i < n; i++) { temp = new SkewHeap; temp->key = heap[i]; root = merge(root, temp); } return root; } // function to print the Skew Heap, // as it is in form of a tree so we use // tree traversal algorithms void inorder(SkewHeap* root) { if (root == NULL) return; else { inorder(root->left); cout << root->key << " "; inorder(root->right); } return; }}; // Driver Codeint main(){ // Construct two heaps SkewHeap heap, *temp1 = NULL, *temp2 = NULL; /* 5 / \ / \ 10 12 */ int heap1[] = { 12, 5, 10 }; /* 3 / \ / \ 7 8 / / 14 */ int heap2[] = { 3, 7, 8, 14 }; int n1 = sizeof(heap1) / sizeof(heap1[0]); int n2 = sizeof(heap2) / sizeof(heap2[0]); temp1 = heap.construct(temp1, heap1, n1); temp2 = heap.construct(temp2, heap2, n2); // Merge two heaps temp1 = heap.merge(temp1, temp2); /* 3 / \ / \ 5 7 / \ / 8 10 14 / 12 */ cout << "Merged Heap is: " << endl; heap.inorder(temp1);}
The heap obtained after merging is:
12 8 5 10 3 14 7
Akanksha_Rai
immanuelidun10
Advanced Data Structure
Heap
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 418,
"s": 52,
"text": "A skew heap (or self – adjusting heap) is a heap data structure implemented as a binary tree. Skew heaps are advantageous because of their ability to merge more quickly than binary heaps. In contrast with binary heaps, there are no structural constraints, so there is no guarantee that the height of the tree is logarithmic. Only two conditions must be satisfied : "
},
{
"code": null,
"e": 718,
"s": 418,
"text": "The general heap order must be there (root is minimum and same is recursively true for subtrees), but balanced property (all levels must be full except the last) is not required.Main operation in Skew Heaps is Merge. We can implement other operations like insert, extractMin(), etc using Merge only."
},
{
"code": null,
"e": 897,
"s": 718,
"text": "The general heap order must be there (root is minimum and same is recursively true for subtrees), but balanced property (all levels must be full except the last) is not required."
},
{
"code": null,
"e": 1019,
"s": 897,
"text": "Main operation in Skew Heaps is Merge. We can implement other operations like insert, extractMin(), etc using Merge only."
},
{
"code": null,
"e": 1065,
"s": 1019,
"text": "Example : 1. Consider the skew heap 1 to be "
},
{
"code": null,
"e": 1102,
"s": 1065,
"text": "2. The second heap to be considered "
},
{
"code": null,
"e": 1146,
"s": 1102,
"text": "4. And we obtain the final merged tree as "
},
{
"code": null,
"e": 1187,
"s": 1146,
"text": "Recursive Merge Process : merge(h1, h2) "
},
{
"code": null,
"e": 1389,
"s": 1187,
"text": "Let h1 and h2 be the two min skew heaps to be merged. Let h1’s root be smaller than h2’s root (If not smaller, we can swap to get the same).We swap h1->left and h1->right.h1->left = merge(h2, h1->left)"
},
{
"code": null,
"e": 1530,
"s": 1389,
"text": "Let h1 and h2 be the two min skew heaps to be merged. Let h1’s root be smaller than h2’s root (If not smaller, we can swap to get the same)."
},
{
"code": null,
"e": 1562,
"s": 1530,
"text": "We swap h1->left and h1->right."
},
{
"code": null,
"e": 1593,
"s": 1562,
"text": "h1->left = merge(h2, h1->left)"
},
{
"code": null,
"e": 1605,
"s": 1593,
"text": "Examples : "
},
{
"code": null,
"e": 2322,
"s": 1605,
"text": "Let h1 be\n 10\n / \\\n 20 30\n / /\n40 50\n\nLet h2 be\n 15\n / \\\n 25 35\n / \\\n45 55\n\nAfter swapping h1->left and h1->right, we get\n 10\n / \\\n 30 20\n / /\n50 40\n\nNow we recursively Merge\n 30\n / AND \n 50\n\n 15\n / \\\n 25 35\n / \\\n45 55\nAfter recursive merge, we get (Please do it \nusing pen and paper).\n 15\n / \\\n 30 25\n / \\ / \\\n35 50 45 55\n\nWe make this merged tree as left of original\nh1 and we get following result.\n 10\n / \\\n 15 20\n / \\ / \n 30 25 40 \n / \\ / \\\n35 40 45 55"
},
{
"code": null,
"e": 2410,
"s": 2322,
"text": "For visualization : https://www.cs.usfca.edu/~galles/JavascriptVisual/LeftistHeap.html "
},
{
"code": null,
"e": 2414,
"s": 2410,
"text": "CPP"
},
{
"code": "// CPP program to implement Skew Heap// operations.#include <bits/stdc++.h>using namespace std; struct SkewHeap{ int key; SkewHeap* right; SkewHeap* left; // constructor to make a new // node of heap SkewHeap() { key = 0; right = NULL; left = NULL; } // the special merge function that's // used in most of the other operations // also SkewHeap* merge(SkewHeap* h1, SkewHeap* h2) { // If one of the heaps is empty if (h1 == NULL) return h2; if (h2 == NULL) return h1; // Make sure that h1 has smaller // key. if (h1->key > h2->key) swap(h1, h2); // Swap h1->left and h1->right swap(h1->left, h1->right); // Merge h2 and h1->left and make // merged tree as left of h1. h1->left = merge(h2, h1->left); return h1; } // function to construct heap using // values in the array SkewHeap* construct(SkewHeap* root, int heap[], int n) { SkewHeap* temp; for (int i = 0; i < n; i++) { temp = new SkewHeap; temp->key = heap[i]; root = merge(root, temp); } return root; } // function to print the Skew Heap, // as it is in form of a tree so we use // tree traversal algorithms void inorder(SkewHeap* root) { if (root == NULL) return; else { inorder(root->left); cout << root->key << \" \"; inorder(root->right); } return; }}; // Driver Codeint main(){ // Construct two heaps SkewHeap heap, *temp1 = NULL, *temp2 = NULL; /* 5 / \\ / \\ 10 12 */ int heap1[] = { 12, 5, 10 }; /* 3 / \\ / \\ 7 8 / / 14 */ int heap2[] = { 3, 7, 8, 14 }; int n1 = sizeof(heap1) / sizeof(heap1[0]); int n2 = sizeof(heap2) / sizeof(heap2[0]); temp1 = heap.construct(temp1, heap1, n1); temp2 = heap.construct(temp2, heap2, n2); // Merge two heaps temp1 = heap.merge(temp1, temp2); /* 3 / \\ / \\ 5 7 / \\ / 8 10 14 / 12 */ cout << \"Merged Heap is: \" << endl; heap.inorder(temp1);}",
"e": 4769,
"s": 2414,
"text": null
},
{
"code": null,
"e": 4829,
"s": 4769,
"text": "The heap obtained after merging is: \n12 8 5 10 3 14 7"
},
{
"code": null,
"e": 4844,
"s": 4831,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4859,
"s": 4844,
"text": "immanuelidun10"
},
{
"code": null,
"e": 4883,
"s": 4859,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 4888,
"s": 4883,
"text": "Heap"
},
{
"code": null,
"e": 4893,
"s": 4888,
"text": "Heap"
}
] |
VBScript Now Function
|
The Function Now returns the current system date and time.
Now()
<!DOCTYPE html>
<html>
<body>
<script language = "vbscript" type = "text/vbscript">
a = Now()
document.write("The Value of a : " & a)
</script>
</body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
The Value of a : 19/07/2013 3:04:09 PM
|
[
{
"code": null,
"e": 2273,
"s": 2214,
"text": "The Function Now returns the current system date and time."
},
{
"code": null,
"e": 2280,
"s": 2273,
"text": "Now()\n"
},
{
"code": null,
"e": 2484,
"s": 2280,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n a = Now()\n document.write(\"The Value of a : \" & a)\n \n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2605,
"s": 2484,
"text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −"
}
] |
Node.js Image Upload, Processing and Resizing using Sharp package
|
08 Oct, 2021
Often in our web applications, we need to store multiple forms and formats of images, in the form of a profile picture or an image for a product in an e-commerce prototype. In most of our cases, we need to store images compressed to multiple sizes, retaining the quality. For example, for a product at an e-commerce site, we would require storing 3 versions of a product image:
Thumbnail
Low resolution for previews, etc.
The original high resolution for the actual product.
Prerequisites:
Node.js basics
Routes handling in express.js
Modules used: sharp, Multer
According to the official npm documentation, The typical use case for sharp is to convert large images in common formats to smaller, web-friendly JPEG, PNG, and WebP images of varying dimensions.
Initialize npm in an empty directory to begin with the following command:
npm init -y
Install the required modules with the following command:
npm install express --save
npm install body-parser --save
npm install sharp --save
npm install multer --save
Multer setup:To upload files, we need to configure multer as a middleware to be passed. To set up multer, we need to add the following code to our application.
Note: For additional usage and to know more about uploads and multer, you can refer the official documentation at Multer
// Importing the moduleconst multer = require('multer'); // Setting up a middleware specifying the// destination for storing the imagesconst upload = multer({dest : './images'})
Since multer works with form-data, you need to ensure the upload is via a form with configuration as multipart/form-data.
Filename: app.js
// Importing the required modulesvar express = require('express');var bodyparser = require('body-parser');var fs = require('fs');var multer = require('multer');var sharp = require('sharp'); var upload = multer({dest : './images'}) // Initialize the express objectvar app = express(); // Use body-parser to parse incoming dataapp.use(bodyparser.urlencoded({extended : true})) // Use the upload middleware containing // our file configuration, with the name// of input file attribute as "avatar"// to the desired configuration. app.post('/upload', upload.single("avatar"), (req, res)=>{ fs.rename(req.file.path, './images/avatar.jpg', (err)=>{ console.log(err); }) return res.json("File Uploaded Successfully!");}); app.listen(3000, ()=>{ console.log("Server Running!")})
Steps to run above code:
Run app.js file using the following command:node app.jsAfter executing above command, you will see the following output:Server Running!Send a POST request to https://localhost:3000/upload using Postman. You need to pass “avatar” as KEY and picture as VALUE.After hitting the request, an image directory will be created with our desired image.
Run app.js file using the following command:node app.jsAfter executing above command, you will see the following output:Server Running!
node app.js
After executing above command, you will see the following output:
Server Running!
Send a POST request to https://localhost:3000/upload using Postman. You need to pass “avatar” as KEY and picture as VALUE.
After hitting the request, an image directory will be created with our desired image.
Processing Image using Sharp: We will be processing images via a sharp package. To create multiple instances with different properties, we use the following code:
// Configuring thumbnail imagesharp(__dirname + '/images/avatar.jpg').resize(200,200).jpeg({quality : 50}).toFile(__dirname + '/images/avatar_thumb.jpg'); // Configuring Preview Imagesharp(__dirname + '/images/avatar.jpg').resize(640,480).jpeg({quality : 80}).toFile(__dirname + '/images/avatar_preview.jpg');
So all things are set, final app.js will be as following:Filename: app.js
var express = require('express');var bodyparser = require('body-parser');var fs = require('fs');var multer = require('multer');var sharp = require('sharp'); var upload = multer({dest : './images'}) var app = express(); app.use(bodyparser.urlencoded({extended : true})) app.post('/upload', upload.single("avatar"), (req, res)=>{ fs.rename(req.file.path, './images/avatar.jpg', (err)=>{ console.log(err); }) sharp(__dirname + '/images/avatar.jpg').resize(200,200) .jpeg({quality : 50}).toFile(__dirname + '/images/avatar_thumb.jpg'); sharp(__dirname + '/images/avatar.jpg').resize(640,480) .jpeg({quality : 80}).toFile(__dirname + '/images/avatar_preview.jpg'); return res.json("File Uploaded Successfully!");}); app.listen(3000, ()=>{ console.log("Server Running!")})
Upon running the server and sending the same request as before, you will get your all uploaded images in the image directory with the desired configuration as shown below:
Additional Sharp Options: https://sharp.pixelplumbing.com/
Image-Processing
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 406,
"s": 28,
"text": "Often in our web applications, we need to store multiple forms and formats of images, in the form of a profile picture or an image for a product in an e-commerce prototype. In most of our cases, we need to store images compressed to multiple sizes, retaining the quality. For example, for a product at an e-commerce site, we would require storing 3 versions of a product image:"
},
{
"code": null,
"e": 416,
"s": 406,
"text": "Thumbnail"
},
{
"code": null,
"e": 450,
"s": 416,
"text": "Low resolution for previews, etc."
},
{
"code": null,
"e": 503,
"s": 450,
"text": "The original high resolution for the actual product."
},
{
"code": null,
"e": 518,
"s": 503,
"text": "Prerequisites:"
},
{
"code": null,
"e": 533,
"s": 518,
"text": "Node.js basics"
},
{
"code": null,
"e": 563,
"s": 533,
"text": "Routes handling in express.js"
},
{
"code": null,
"e": 591,
"s": 563,
"text": "Modules used: sharp, Multer"
},
{
"code": null,
"e": 787,
"s": 591,
"text": "According to the official npm documentation, The typical use case for sharp is to convert large images in common formats to smaller, web-friendly JPEG, PNG, and WebP images of varying dimensions."
},
{
"code": null,
"e": 861,
"s": 787,
"text": "Initialize npm in an empty directory to begin with the following command:"
},
{
"code": null,
"e": 873,
"s": 861,
"text": "npm init -y"
},
{
"code": null,
"e": 930,
"s": 873,
"text": "Install the required modules with the following command:"
},
{
"code": null,
"e": 1040,
"s": 930,
"text": "npm install express --save\nnpm install body-parser --save\nnpm install sharp --save\nnpm install multer --save\n"
},
{
"code": null,
"e": 1200,
"s": 1040,
"text": "Multer setup:To upload files, we need to configure multer as a middleware to be passed. To set up multer, we need to add the following code to our application."
},
{
"code": null,
"e": 1321,
"s": 1200,
"text": "Note: For additional usage and to know more about uploads and multer, you can refer the official documentation at Multer"
},
{
"code": "// Importing the moduleconst multer = require('multer'); // Setting up a middleware specifying the// destination for storing the imagesconst upload = multer({dest : './images'}) ",
"e": 1505,
"s": 1321,
"text": null
},
{
"code": null,
"e": 1627,
"s": 1505,
"text": "Since multer works with form-data, you need to ensure the upload is via a form with configuration as multipart/form-data."
},
{
"code": null,
"e": 1644,
"s": 1627,
"text": "Filename: app.js"
},
{
"code": "// Importing the required modulesvar express = require('express');var bodyparser = require('body-parser');var fs = require('fs');var multer = require('multer');var sharp = require('sharp'); var upload = multer({dest : './images'}) // Initialize the express objectvar app = express(); // Use body-parser to parse incoming dataapp.use(bodyparser.urlencoded({extended : true})) // Use the upload middleware containing // our file configuration, with the name// of input file attribute as \"avatar\"// to the desired configuration. app.post('/upload', upload.single(\"avatar\"), (req, res)=>{ fs.rename(req.file.path, './images/avatar.jpg', (err)=>{ console.log(err); }) return res.json(\"File Uploaded Successfully!\");}); app.listen(3000, ()=>{ console.log(\"Server Running!\")})",
"e": 2452,
"s": 1644,
"text": null
},
{
"code": null,
"e": 2477,
"s": 2452,
"text": "Steps to run above code:"
},
{
"code": null,
"e": 2820,
"s": 2477,
"text": "Run app.js file using the following command:node app.jsAfter executing above command, you will see the following output:Server Running!Send a POST request to https://localhost:3000/upload using Postman. You need to pass “avatar” as KEY and picture as VALUE.After hitting the request, an image directory will be created with our desired image."
},
{
"code": null,
"e": 2956,
"s": 2820,
"text": "Run app.js file using the following command:node app.jsAfter executing above command, you will see the following output:Server Running!"
},
{
"code": null,
"e": 2968,
"s": 2956,
"text": "node app.js"
},
{
"code": null,
"e": 3034,
"s": 2968,
"text": "After executing above command, you will see the following output:"
},
{
"code": null,
"e": 3050,
"s": 3034,
"text": "Server Running!"
},
{
"code": null,
"e": 3173,
"s": 3050,
"text": "Send a POST request to https://localhost:3000/upload using Postman. You need to pass “avatar” as KEY and picture as VALUE."
},
{
"code": null,
"e": 3259,
"s": 3173,
"text": "After hitting the request, an image directory will be created with our desired image."
},
{
"code": null,
"e": 3422,
"s": 3259,
"text": "Processing Image using Sharp: We will be processing images via a sharp package. To create multiple instances with different properties, we use the following code:"
},
{
"code": "// Configuring thumbnail imagesharp(__dirname + '/images/avatar.jpg').resize(200,200).jpeg({quality : 50}).toFile(__dirname + '/images/avatar_thumb.jpg'); // Configuring Preview Imagesharp(__dirname + '/images/avatar.jpg').resize(640,480).jpeg({quality : 80}).toFile(__dirname + '/images/avatar_preview.jpg');",
"e": 3749,
"s": 3422,
"text": null
},
{
"code": null,
"e": 3823,
"s": 3749,
"text": "So all things are set, final app.js will be as following:Filename: app.js"
},
{
"code": "var express = require('express');var bodyparser = require('body-parser');var fs = require('fs');var multer = require('multer');var sharp = require('sharp'); var upload = multer({dest : './images'}) var app = express(); app.use(bodyparser.urlencoded({extended : true})) app.post('/upload', upload.single(\"avatar\"), (req, res)=>{ fs.rename(req.file.path, './images/avatar.jpg', (err)=>{ console.log(err); }) sharp(__dirname + '/images/avatar.jpg').resize(200,200) .jpeg({quality : 50}).toFile(__dirname + '/images/avatar_thumb.jpg'); sharp(__dirname + '/images/avatar.jpg').resize(640,480) .jpeg({quality : 80}).toFile(__dirname + '/images/avatar_preview.jpg'); return res.json(\"File Uploaded Successfully!\");}); app.listen(3000, ()=>{ console.log(\"Server Running!\")})",
"e": 4656,
"s": 3823,
"text": null
},
{
"code": null,
"e": 4828,
"s": 4656,
"text": "Upon running the server and sending the same request as before, you will get your all uploaded images in the image directory with the desired configuration as shown below:"
},
{
"code": null,
"e": 4887,
"s": 4828,
"text": "Additional Sharp Options: https://sharp.pixelplumbing.com/"
},
{
"code": null,
"e": 4904,
"s": 4887,
"text": "Image-Processing"
},
{
"code": null,
"e": 4912,
"s": 4904,
"text": "Node.js"
},
{
"code": null,
"e": 4929,
"s": 4912,
"text": "Web Technologies"
},
{
"code": null,
"e": 5027,
"s": 4929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5081,
"s": 5027,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 5121,
"s": 5081,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 5153,
"s": 5121,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5188,
"s": 5153,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5258,
"s": 5188,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 5320,
"s": 5258,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5381,
"s": 5320,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5431,
"s": 5381,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5474,
"s": 5431,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Profil3 – Find Potential Profiles of a Person in Kali Linux
|
30 Jun, 2021
Profil3 is a free and open-source tool available on GitHub. This tool is used to find potential profiles of a person on different sites. This tool is based upon OSINT Technology, which means Open Source Intelligence technology. This tool allows its users to find potential profiles of a person on social network sites, websites, and web applications. This tool also finds the email address associated with that user’s id. The tool provides you with many features. This tool will give you an alert to the presence of a data leak for the found emails. This tool is written in python. You must have python installed in your Kali Linux in order to use the tool. The Profil3 interface is very similar to Metasploit 1 and Metasploit. Profil3 provides a command-line interface that you can run on Kali Linux. The interactive console provides a number of helpful features, such as command completion and contextual help.
Step 1: Open your Kali Linux operating system and install the tool using the following command.
git clone https://github.com/Rog3rSm1th/Profil3r.git
cd Profil3r/
python3 setup.py install
Step 2: The tool has been downloaded and installed successfully. Use the following command to run the tool.
python3 profil3r.py -h
The tool is running successfully. Now we will see an example of using the tool.
Example 1: Use the profil3r tool to find out all the internet information of the user.
python3 profil3r.py -p <user name>
Enter your username to scan.
You can see the tool has given all the publicly available information of the user. You can use the tool to scan your target username also.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
SED command in Linux | Set 2
nohup Command in Linux with Examples
chmod command in Linux with examples
Array Basics in Shell Scripting | Set 1
mv command in Linux with examples
Introduction to Linux Operating System
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 941,
"s": 28,
"text": "Profil3 is a free and open-source tool available on GitHub. This tool is used to find potential profiles of a person on different sites. This tool is based upon OSINT Technology, which means Open Source Intelligence technology. This tool allows its users to find potential profiles of a person on social network sites, websites, and web applications. This tool also finds the email address associated with that user’s id. The tool provides you with many features. This tool will give you an alert to the presence of a data leak for the found emails. This tool is written in python. You must have python installed in your Kali Linux in order to use the tool. The Profil3 interface is very similar to Metasploit 1 and Metasploit. Profil3 provides a command-line interface that you can run on Kali Linux. The interactive console provides a number of helpful features, such as command completion and contextual help."
},
{
"code": null,
"e": 1037,
"s": 941,
"text": "Step 1: Open your Kali Linux operating system and install the tool using the following command."
},
{
"code": null,
"e": 1128,
"s": 1037,
"text": "git clone https://github.com/Rog3rSm1th/Profil3r.git\ncd Profil3r/\npython3 setup.py install"
},
{
"code": null,
"e": 1236,
"s": 1128,
"text": "Step 2: The tool has been downloaded and installed successfully. Use the following command to run the tool."
},
{
"code": null,
"e": 1259,
"s": 1236,
"text": "python3 profil3r.py -h"
},
{
"code": null,
"e": 1340,
"s": 1259,
"text": " The tool is running successfully. Now we will see an example of using the tool."
},
{
"code": null,
"e": 1427,
"s": 1340,
"text": "Example 1: Use the profil3r tool to find out all the internet information of the user."
},
{
"code": null,
"e": 1462,
"s": 1427,
"text": "python3 profil3r.py -p <user name>"
},
{
"code": null,
"e": 1491,
"s": 1462,
"text": "Enter your username to scan."
},
{
"code": null,
"e": 1631,
"s": 1491,
"text": "You can see the tool has given all the publicly available information of the user. You can use the tool to scan your target username also. "
},
{
"code": null,
"e": 1642,
"s": 1631,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1654,
"s": 1642,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1665,
"s": 1654,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1763,
"s": 1665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1798,
"s": 1763,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1824,
"s": 1798,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1861,
"s": 1824,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1890,
"s": 1861,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1927,
"s": 1890,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1964,
"s": 1927,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2004,
"s": 1964,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 2038,
"s": 2004,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 2077,
"s": 2038,
"text": "Introduction to Linux Operating System"
}
] |
Node.js MessageChannel.postMessage() Method
|
09 Jul, 2021
The MessagePort.postMessage() method is an inbuilt application programming interface of class Worker within worker_threads module which is used to send the message from one port to another.
Syntax:
const MessagePort.postMessage(value[, transferList])
Parameters: This method takes the value as a parameter which can contain any kind of object.
Return Value: This method sends the message from one port to another.
Example 1: Filename: index.js
Javascript
// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread moduleconst { MessageChannel, receiveMessageOnPort } = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Sending data to port 2// by using postMessage() methodport1.postMessage({ hello: 'world1' }); // Posting data in port 1// by using postMessage() methodport2.postMessage({ hello: 'world2' }); /// Display the resultconsole.log("received data in port1 : ");console.log(receiveMessageOnPort(port1)); console.log("received data in port2 : ");console.log(receiveMessageOnPort(port2)); // Closing the portsport1.close();port2.close();
Output:
received data in port1 :
{ message: { hello: 'world2' } }
received data in port2 :
{ message: { hello: 'world1' } }
Example 2: Filename: index.js
Javascript
// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread module const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Catching the event messageport2.on('message', (message) => console.log(message)); // Catching the event closeport2.on('close', () => console.log('closed!')); // Sending message to port2// by using postMessage() methodport1.postMessage('GFG'); // Closing port by using// close() methodport1.close();
Output:
GFG
closed!
Run the index.js file using the following command:
node index.js
Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist
sweetyty
kapoorsagar226
Node.js-Methods
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "The MessagePort.postMessage() method is an inbuilt application programming interface of class Worker within worker_threads module which is used to send the message from one port to another."
},
{
"code": null,
"e": 226,
"s": 218,
"text": "Syntax:"
},
{
"code": null,
"e": 279,
"s": 226,
"text": "const MessagePort.postMessage(value[, transferList])"
},
{
"code": null,
"e": 372,
"s": 279,
"text": "Parameters: This method takes the value as a parameter which can contain any kind of object."
},
{
"code": null,
"e": 442,
"s": 372,
"text": "Return Value: This method sends the message from one port to another."
},
{
"code": null,
"e": 472,
"s": 442,
"text": "Example 1: Filename: index.js"
},
{
"code": null,
"e": 483,
"s": 472,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread moduleconst { MessageChannel, receiveMessageOnPort } = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Sending data to port 2// by using postMessage() methodport1.postMessage({ hello: 'world1' }); // Posting data in port 1// by using postMessage() methodport2.postMessage({ hello: 'world2' }); /// Display the resultconsole.log(\"received data in port1 : \");console.log(receiveMessageOnPort(port1)); console.log(\"received data in port2 : \");console.log(receiveMessageOnPort(port2)); // Closing the portsport1.close();port2.close();",
"e": 1200,
"s": 483,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1324,
"s": 1208,
"text": "received data in port1 :\n{ message: { hello: 'world2' } }\nreceived data in port2 :\n{ message: { hello: 'world1' } }"
},
{
"code": null,
"e": 1354,
"s": 1324,
"text": "Example 2: Filename: index.js"
},
{
"code": null,
"e": 1365,
"s": 1354,
"text": "Javascript"
},
{
"code": "// Node.js program to demonstrate the// MessageChannel.postMessage() method // Importing worker_thread module const { MessageChannel, receiveMessageOnPort } = require('worker_threads'); // Creating and initializing the MessageChannelconst { port1, port2 } = new MessageChannel(); // Catching the event messageport2.on('message', (message) => console.log(message)); // Catching the event closeport2.on('close', () => console.log('closed!')); // Sending message to port2// by using postMessage() methodport1.postMessage('GFG'); // Closing port by using// close() methodport1.close();",
"e": 1954,
"s": 1365,
"text": null
},
{
"code": null,
"e": 1962,
"s": 1954,
"text": "Output:"
},
{
"code": null,
"e": 1974,
"s": 1962,
"text": "GFG\nclosed!"
},
{
"code": null,
"e": 2025,
"s": 1974,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 2039,
"s": 2025,
"text": "node index.js"
},
{
"code": null,
"e": 2167,
"s": 2039,
"text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist"
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "sweetyty"
},
{
"code": null,
"e": 2191,
"s": 2176,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2207,
"s": 2191,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Node.js"
},
{
"code": null,
"e": 2232,
"s": 2215,
"text": "Web Technologies"
}
] |
Program to find the Roots of Quadratic equation
|
12 May, 2022
Given a quadratic equation in the form ax2 + bx + c, find roots of it.
Examples :
Input : a = 1, b = -2, c = 1Output : Roots are real and same 1
Input : a = 1, b = 7, c = 12Output : Roots are real and different -3, -4
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Input : a = 1, b = 1, c = 1Output : Roots are complex -0.5 + i1.73205 -0.5 – i1.73205
Below is the direct formula for finding roots of the quadratic equation.
There are the following important cases.
If b*b < 4*a*c, then roots are complex
(not real).
For example roots of x2 + x + 1, roots are
-0.5 + i0.86603 and -0.5 - i0.86603
If b*b == 4*a*c, then roots are real
and both roots are same.
For example, roots of x2 - 2x + 1 are 1 and 1
If b*b > 4*a*c, then roots are real
and different.
For example, roots of x2 - 7x - 12 are 3 and 4
Below is the implementation of the above formula.
C
C++
Java
Python3
C#
PHP
Javascript
/* C program to find roots of a quadratic equation */#include <math.h>#include <stdio.h>#include <stdlib.h> // Prints roots of quadratic equation ax*2 + bx + xvoid findRoots(int a, int b, int c){ // If a is 0, then equation is not quadratic, but // linear if (a == 0) { printf("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { printf("Roots are real and different \n"); printf("%f\n%f", (double)(-b + sqrt_val) / (2 * a), (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { printf("Roots are real and same \n"); printf("%f", -(double)b / (2 * a)); } else // d < 0 { printf("Roots are complex \n"); printf("%f + i%f\n%f - i%f", -(double)b / (2 * a), sqrt_val/(2 * a), -(double)b / (2 * a), sqrt_val/(2 * a)); }} // Driver codeint main(){ int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); return 0;}
/* C++ program to find roots of a quadratic equation */#include <bits/stdc++.h>using namespace std; // Prints roots of quadratic equation ax*2 + bx + xvoid findRoots(int a, int b, int c){ // If a is 0, then equation is not quadratic, but // linear if (a == 0) { cout << "Invalid"; return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { cout << "Roots are real and different \n"; cout << (double)(-b + sqrt_val) / (2 * a) << "\n" << (double)(-b - sqrt_val) / (2 * a); } else if (d == 0) { cout << "Roots are real and same \n"; cout << -(double)b / (2 * a); } else // d < 0 { cout << "Roots are complex \n"; cout << -(double)b / (2 * a) << " + i" << sqrt_val / (2 * a) << "\n" << -(double)b / (2 * a) << " - i" << sqrt_val / (2 * a) ; }} // Driver codeint main(){ int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); return 0;}
// Java program to find roots// of a quadratic equation import java.io.*;import static java.lang.Math.*;class Quadratic { // Prints roots of quadratic // equation ax * 2 + bx + x static void findRoots(int a, int b, int c) { // If a is 0, then equation is not // quadratic, but linear if (a == 0) { System.out.println("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { System.out.println( "Roots are real and different \n"); System.out.println( (double)(-b + sqrt_val) / (2 * a) + "\n" + (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { System.out.println( "Roots are real and same \n"); System.out.println(-(double)b / (2 * a) + "\n" + -(double)b / (2 * a)); } else // d < 0 { System.out.println("Roots are complex \n"); System.out.println(-(double)b / (2 * a) + " + i" + sqrt_val / (2 * a) + "\n" + -(double)b / (2 * a) + " - i" + sqrt_val / (2 * a)) ; } } // Driver code public static void main(String args[]) { int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); }} // This code is contributed by Sumit Kumar.
# Python program to find roots# of a quadratic equationimport math # Prints roots of quadratic equation# ax*2 + bx + x def findRoots(a, b, c): # If a is 0, then equation is # not quadratic, but linear if a == 0: print("Invalid") return -1 d = b * b - 4 * a * c sqrt_val = math.sqrt(abs(d)) if d > 0: print("Roots are real and different ") print((-b + sqrt_val)/(2 * a)) print((-b - sqrt_val)/(2 * a)) elif d == 0: print("Roots are real and same") print(-b / (2*a)) else: # d<0 print("Roots are complex") print(- b / (2*a), " + i", sqrt_val/ (2 * a)) print(- b / (2*a), " - i", sqrt_val/ (2 * a)) # Driver Programa = 1b = -7c = 12 # Function callfindRoots(a, b, c) # This code is contributed by Sharad Bhardwaj.
// C# program to find roots// of a quadratic equationusing System; class Quadratic { // Prints roots of quadratic // equation ax * 2 + bx + x void findRoots(int a, int b, int c) { // If a is 0, then equation is // not quadratic, but linear if (a == 0) { Console.Write("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = Math.Abs(d); if (d > 0) { Console.Write( "Roots are real and different \n"); Console.Write( (double)(-b + sqrt_val) / (2 * a) + "\n" + (double)(-b - sqrt_val) / (2 * a)); } // d < 0 else { Console.Write("Roots are complex \n"); Console.Write(-(double)b / (2 * a) + " + i" + sqrt_val / (2 * a) + "\n" + -(double)b / (2 * a) + " - i" + sqrt_val / (2 * a) ); } } // Driver code public static void Main() { Quadratic obj = new Quadratic(); int a = 1, b = -7, c = 12; // Function call obj.findRoots(a, b, c); }} // This code is contributed by nitin mittal.
<?php// PHP program to find roots// of a quadratic equation // Prints roots of quadratic// equation ax*2 + bx + xfunction findRoots($a, $b, $c){ // If a is 0, then equation is // not quadratic, but linear if ($a == 0) { echo "Invalid"; return; } $d = $b * $b - 4 * $a * $c; $sqrt_val = sqrt(abs($d)); if ($d > 0) { echo "Roots are real and ". "different \n"; echo (-$b + $sqrt_val) / (2 * $a) , "\n", (-$b - $sqrt_val) / (2 * $a); } else if ($d == 0) { echo "Roots are real and same \n"; echo -$b / (2 * $a); } // d < 0 else { echo "Roots are complex \n"; echo -$b / (2 * $a) , " + i" , $sqrt_val / (2 * $a) , "\n" , -$b / (2 * $a), " - i", $sqrt_val / (2 * $a) ; }} // Driver code$a = 1; $b = -7 ;$c = 12; // Function callfindRoots($a, $b, $c); // This code is contributed// by nitin mittal.?>
<script> // JavaScript program to find roots// of a quadratic equation // Prints roots of quadratic // equation ax * 2 + bx + x function findRoots(a, b, c) { // If a is 0, then equation is not // quadratic, but linear if (a == 0) { document.write("Invalid"); return; } let d = b * b - 4 * a * c; let sqrt_val = Math.sqrt(Math.abs(d)); if (d > 0) { document.write( "Roots are real and different \n" + "<br/>"); document.write( (-b + sqrt_val) / (2 * a) + "<br/>" + (-b - sqrt_val) / (2 * a)); } else if (d == 0) { document.write( "Roots are real and same \n" + "<br/>"); document.write(-b / (2 * a) + "<br/>" + -b / (2 * a)) ; } else // d < 0 { document.write("Roots are complex \n"); document.write(-b / (2 * a) + " + i" + sqrt_val / (2 * a) + "<br/>" + -b / (2 * a) + " - i" + sqrt_val) / (2 * a) ; } } // Driver Code let a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); </script>
Roots are real and different
4.000000
3.000000
Time Complexity: O(log(D)), where D is the discriminant of the given quadratic equation.Auxiliary Space: O(1)
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or hare more information about the topic discussed above.
nitin mittal
RishabhPrabhu
mysumymysaim
chinmoy1997pal
rameshta
laphamkienanh19
harendrakumar123
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 125,
"s": 52,
"text": "Given a quadratic equation in the form ax2 + bx + c, find roots of it. "
},
{
"code": null,
"e": 136,
"s": 125,
"text": "Examples :"
},
{
"code": null,
"e": 214,
"s": 136,
"text": "Input : a = 1, b = -2, c = 1Output : Roots are real and same 1"
},
{
"code": null,
"e": 302,
"s": 214,
"text": "Input : a = 1, b = 7, c = 12Output : Roots are real and different -3, -4"
},
{
"code": null,
"e": 311,
"s": 302,
"text": "Chapters"
},
{
"code": null,
"e": 338,
"s": 311,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 388,
"s": 338,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 411,
"s": 388,
"text": "captions off, selected"
},
{
"code": null,
"e": 419,
"s": 411,
"text": "English"
},
{
"code": null,
"e": 443,
"s": 419,
"text": "This is a modal window."
},
{
"code": null,
"e": 512,
"s": 443,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 534,
"s": 512,
"text": "End of dialog window."
},
{
"code": null,
"e": 650,
"s": 534,
"text": "Input : a = 1, b = 1, c = 1Output : Roots are complex -0.5 + i1.73205 -0.5 – i1.73205 "
},
{
"code": null,
"e": 723,
"s": 650,
"text": "Below is the direct formula for finding roots of the quadratic equation."
},
{
"code": null,
"e": 765,
"s": 723,
"text": "There are the following important cases. "
},
{
"code": null,
"e": 1105,
"s": 765,
"text": "If b*b < 4*a*c, then roots are complex\n(not real).\nFor example roots of x2 + x + 1, roots are\n-0.5 + i0.86603 and -0.5 - i0.86603\n\nIf b*b == 4*a*c, then roots are real \nand both roots are same.\nFor example, roots of x2 - 2x + 1 are 1 and 1\n\nIf b*b > 4*a*c, then roots are real \nand different.\nFor example, roots of x2 - 7x - 12 are 3 and 4"
},
{
"code": null,
"e": 1155,
"s": 1105,
"text": "Below is the implementation of the above formula."
},
{
"code": null,
"e": 1157,
"s": 1155,
"text": "C"
},
{
"code": null,
"e": 1161,
"s": 1157,
"text": "C++"
},
{
"code": null,
"e": 1166,
"s": 1161,
"text": "Java"
},
{
"code": null,
"e": 1174,
"s": 1166,
"text": "Python3"
},
{
"code": null,
"e": 1177,
"s": 1174,
"text": "C#"
},
{
"code": null,
"e": 1181,
"s": 1177,
"text": "PHP"
},
{
"code": null,
"e": 1192,
"s": 1181,
"text": "Javascript"
},
{
"code": "/* C program to find roots of a quadratic equation */#include <math.h>#include <stdio.h>#include <stdlib.h> // Prints roots of quadratic equation ax*2 + bx + xvoid findRoots(int a, int b, int c){ // If a is 0, then equation is not quadratic, but // linear if (a == 0) { printf(\"Invalid\"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { printf(\"Roots are real and different \\n\"); printf(\"%f\\n%f\", (double)(-b + sqrt_val) / (2 * a), (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { printf(\"Roots are real and same \\n\"); printf(\"%f\", -(double)b / (2 * a)); } else // d < 0 { printf(\"Roots are complex \\n\"); printf(\"%f + i%f\\n%f - i%f\", -(double)b / (2 * a), sqrt_val/(2 * a), -(double)b / (2 * a), sqrt_val/(2 * a)); }} // Driver codeint main(){ int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); return 0;}",
"e": 2193,
"s": 1192,
"text": null
},
{
"code": "/* C++ program to find roots of a quadratic equation */#include <bits/stdc++.h>using namespace std; // Prints roots of quadratic equation ax*2 + bx + xvoid findRoots(int a, int b, int c){ // If a is 0, then equation is not quadratic, but // linear if (a == 0) { cout << \"Invalid\"; return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { cout << \"Roots are real and different \\n\"; cout << (double)(-b + sqrt_val) / (2 * a) << \"\\n\" << (double)(-b - sqrt_val) / (2 * a); } else if (d == 0) { cout << \"Roots are real and same \\n\"; cout << -(double)b / (2 * a); } else // d < 0 { cout << \"Roots are complex \\n\"; cout << -(double)b / (2 * a) << \" + i\" << sqrt_val / (2 * a) << \"\\n\" << -(double)b / (2 * a) << \" - i\" << sqrt_val / (2 * a) ; }} // Driver codeint main(){ int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); return 0;}",
"e": 3205,
"s": 2193,
"text": null
},
{
"code": "// Java program to find roots// of a quadratic equation import java.io.*;import static java.lang.Math.*;class Quadratic { // Prints roots of quadratic // equation ax * 2 + bx + x static void findRoots(int a, int b, int c) { // If a is 0, then equation is not // quadratic, but linear if (a == 0) { System.out.println(\"Invalid\"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d)); if (d > 0) { System.out.println( \"Roots are real and different \\n\"); System.out.println( (double)(-b + sqrt_val) / (2 * a) + \"\\n\" + (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { System.out.println( \"Roots are real and same \\n\"); System.out.println(-(double)b / (2 * a) + \"\\n\" + -(double)b / (2 * a)); } else // d < 0 { System.out.println(\"Roots are complex \\n\"); System.out.println(-(double)b / (2 * a) + \" + i\" + sqrt_val / (2 * a) + \"\\n\" + -(double)b / (2 * a) + \" - i\" + sqrt_val / (2 * a)) ; } } // Driver code public static void main(String args[]) { int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); }} // This code is contributed by Sumit Kumar.",
"e": 4705,
"s": 3205,
"text": null
},
{
"code": "# Python program to find roots# of a quadratic equationimport math # Prints roots of quadratic equation# ax*2 + bx + x def findRoots(a, b, c): # If a is 0, then equation is # not quadratic, but linear if a == 0: print(\"Invalid\") return -1 d = b * b - 4 * a * c sqrt_val = math.sqrt(abs(d)) if d > 0: print(\"Roots are real and different \") print((-b + sqrt_val)/(2 * a)) print((-b - sqrt_val)/(2 * a)) elif d == 0: print(\"Roots are real and same\") print(-b / (2*a)) else: # d<0 print(\"Roots are complex\") print(- b / (2*a), \" + i\", sqrt_val/ (2 * a)) print(- b / (2*a), \" - i\", sqrt_val/ (2 * a)) # Driver Programa = 1b = -7c = 12 # Function callfindRoots(a, b, c) # This code is contributed by Sharad Bhardwaj.",
"e": 5515,
"s": 4705,
"text": null
},
{
"code": "// C# program to find roots// of a quadratic equationusing System; class Quadratic { // Prints roots of quadratic // equation ax * 2 + bx + x void findRoots(int a, int b, int c) { // If a is 0, then equation is // not quadratic, but linear if (a == 0) { Console.Write(\"Invalid\"); return; } int d = b * b - 4 * a * c; double sqrt_val = Math.Abs(d); if (d > 0) { Console.Write( \"Roots are real and different \\n\"); Console.Write( (double)(-b + sqrt_val) / (2 * a) + \"\\n\" + (double)(-b - sqrt_val) / (2 * a)); } // d < 0 else { Console.Write(\"Roots are complex \\n\"); Console.Write(-(double)b / (2 * a) + \" + i\" + sqrt_val / (2 * a) + \"\\n\" + -(double)b / (2 * a) + \" - i\" + sqrt_val / (2 * a) ); } } // Driver code public static void Main() { Quadratic obj = new Quadratic(); int a = 1, b = -7, c = 12; // Function call obj.findRoots(a, b, c); }} // This code is contributed by nitin mittal.",
"e": 6737,
"s": 5515,
"text": null
},
{
"code": "<?php// PHP program to find roots// of a quadratic equation // Prints roots of quadratic// equation ax*2 + bx + xfunction findRoots($a, $b, $c){ // If a is 0, then equation is // not quadratic, but linear if ($a == 0) { echo \"Invalid\"; return; } $d = $b * $b - 4 * $a * $c; $sqrt_val = sqrt(abs($d)); if ($d > 0) { echo \"Roots are real and \". \"different \\n\"; echo (-$b + $sqrt_val) / (2 * $a) , \"\\n\", (-$b - $sqrt_val) / (2 * $a); } else if ($d == 0) { echo \"Roots are real and same \\n\"; echo -$b / (2 * $a); } // d < 0 else { echo \"Roots are complex \\n\"; echo -$b / (2 * $a) , \" + i\" , $sqrt_val / (2 * $a) , \"\\n\" , -$b / (2 * $a), \" - i\", $sqrt_val / (2 * $a) ; }} // Driver code$a = 1; $b = -7 ;$c = 12; // Function callfindRoots($a, $b, $c); // This code is contributed// by nitin mittal.?>",
"e": 7718,
"s": 6737,
"text": null
},
{
"code": "<script> // JavaScript program to find roots// of a quadratic equation // Prints roots of quadratic // equation ax * 2 + bx + x function findRoots(a, b, c) { // If a is 0, then equation is not // quadratic, but linear if (a == 0) { document.write(\"Invalid\"); return; } let d = b * b - 4 * a * c; let sqrt_val = Math.sqrt(Math.abs(d)); if (d > 0) { document.write( \"Roots are real and different \\n\" + \"<br/>\"); document.write( (-b + sqrt_val) / (2 * a) + \"<br/>\" + (-b - sqrt_val) / (2 * a)); } else if (d == 0) { document.write( \"Roots are real and same \\n\" + \"<br/>\"); document.write(-b / (2 * a) + \"<br/>\" + -b / (2 * a)) ; } else // d < 0 { document.write(\"Roots are complex \\n\"); document.write(-b / (2 * a) + \" + i\" + sqrt_val / (2 * a) + \"<br/>\" + -b / (2 * a) + \" - i\" + sqrt_val) / (2 * a) ; } } // Driver Code let a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); </script>",
"e": 9029,
"s": 7718,
"text": null
},
{
"code": null,
"e": 9077,
"s": 9029,
"text": "Roots are real and different \n4.000000\n3.000000"
},
{
"code": null,
"e": 9187,
"s": 9077,
"text": "Time Complexity: O(log(D)), where D is the discriminant of the given quadratic equation.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9346,
"s": 9187,
"text": "This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or hare more information about the topic discussed above. "
},
{
"code": null,
"e": 9359,
"s": 9346,
"text": "nitin mittal"
},
{
"code": null,
"e": 9373,
"s": 9359,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 9386,
"s": 9373,
"text": "mysumymysaim"
},
{
"code": null,
"e": 9401,
"s": 9386,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 9410,
"s": 9401,
"text": "rameshta"
},
{
"code": null,
"e": 9426,
"s": 9410,
"text": "laphamkienanh19"
},
{
"code": null,
"e": 9443,
"s": 9426,
"text": "harendrakumar123"
},
{
"code": null,
"e": 9456,
"s": 9443,
"text": "Mathematical"
},
{
"code": null,
"e": 9469,
"s": 9456,
"text": "Mathematical"
}
] |
Program to find LCM of two numbers
|
22 Jun, 2022
LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers.
For example, LCM of 15 and 20 is 60, and LCM of 5 and 7 is 35.
A simple solution is to find all prime factors of both numbers, then find union of all factors present in both numbers. Finally, return the product of elements in union.
An efficient solution is based on the below formula for LCM of two numbers ‘a’ and ‘b’.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
a x b = LCM(a, b) * GCD (a, b)
LCM(a, b) = (a x b) / GCD(a, b)
We have discussed function to find GCD of two numbers. Using GCD, we can find LCM.
Below is the implementation of the above idea:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find LCM of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and blong long gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return LCM of two numberslong long lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Driver program to test above functionint main(){ int a = 15, b = 20; cout <<"LCM of " << a << " and " << b << " is " << lcm(a, b); return 0;}
// C program to find LCM of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return LCM of two numbersint lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Driver program to test above functionint main(){ int a = 15, b = 20; printf("LCM of %d and %d is %d ", a, b, lcm(a, b)); return 0;}
// Java program to find LCM of two numbers.class Test{ // Recursive method to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Driver method public static void main(String[] args) { int a = 15, b = 20; System.out.println("LCM of " + a + " and " + b + " is " + lcm(a, b)); }}
# Python program to find LCM of two numbers # Recursive function to return gcd of a and bdef gcd(a,b): if a == 0: return b return gcd(b % a, a) # Function to return LCM of two numbersdef lcm(a,b): return (a / gcd(a,b))* b # Driver program to test above functiona = 15b = 20print('LCM of', a, 'and', b, 'is', lcm(a, b)) # This code is contributed by Danish Raza
// C# program to find LCM// of two numbers.using System;class GFG { // Recursive method to // return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to return // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Driver method public static void Main() { int a = 15, b = 20; Console.WriteLine("LCM of " + a + " and " + b + " is " + lcm(a, b)); }} // This code is contributed by anuj_67.
<?php// PHP program to find LCM of two numbers // Recursive function to// return gcd of a and bfunction gcd( $a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to return LCM// of two numbersfunction lcm( $a, $b){ return ($a / gcd($a, $b)) * $b;} // Driver Code $a = 15; $b = 20; echo "LCM of ",$a, " and " ,$b, " is ", lcm($a, $b); // This code is contributed by anuj_67.?>
<script> // Javascript program to find LCM of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){if (b == 0) return a;return gcd(b, a % b);} // Function to return LCM of two numbersfunction lcm(a, b){ return (a / gcd(a, b)) * b;} // Driver program to test above function let a = 15, b = 20; document.write("LCM of " + a + " and " + b + " is " + lcm(a, b)); // This code is contributed by Mayank Tyagi </script>
LCM of 15 and 20 is 60
Time Complexity: O(log(min(a,b))
Auxiliary Space: O(log(min(a,b))
https://youtu.be/anSfYgbo694
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vt_m
SoumikMondal
DeepakMangla1
jayonet19
mayanktyagi1709
mayur_patil
mk420464
subhammahato348
souravmahato348
codewithrathi
GCD-LCM
SAP Labs
Mathematical
School Programming
SAP Labs
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 157,
"s": 52,
"text": "LCM (Least Common Multiple) of two numbers is the smallest number which can be divided by both numbers. "
},
{
"code": null,
"e": 220,
"s": 157,
"text": "For example, LCM of 15 and 20 is 60, and LCM of 5 and 7 is 35."
},
{
"code": null,
"e": 390,
"s": 220,
"text": "A simple solution is to find all prime factors of both numbers, then find union of all factors present in both numbers. Finally, return the product of elements in union."
},
{
"code": null,
"e": 479,
"s": 390,
"text": "An efficient solution is based on the below formula for LCM of two numbers ‘a’ and ‘b’. "
},
{
"code": null,
"e": 488,
"s": 479,
"text": "Chapters"
},
{
"code": null,
"e": 515,
"s": 488,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 565,
"s": 515,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 588,
"s": 565,
"text": "captions off, selected"
},
{
"code": null,
"e": 596,
"s": 588,
"text": "English"
},
{
"code": null,
"e": 620,
"s": 596,
"text": "This is a modal window."
},
{
"code": null,
"e": 689,
"s": 620,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 711,
"s": 689,
"text": "End of dialog window."
},
{
"code": null,
"e": 781,
"s": 711,
"text": " a x b = LCM(a, b) * GCD (a, b)\n\n LCM(a, b) = (a x b) / GCD(a, b)"
},
{
"code": null,
"e": 865,
"s": 781,
"text": "We have discussed function to find GCD of two numbers. Using GCD, we can find LCM. "
},
{
"code": null,
"e": 912,
"s": 865,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 916,
"s": 912,
"text": "C++"
},
{
"code": null,
"e": 918,
"s": 916,
"text": "C"
},
{
"code": null,
"e": 923,
"s": 918,
"text": "Java"
},
{
"code": null,
"e": 931,
"s": 923,
"text": "Python3"
},
{
"code": null,
"e": 934,
"s": 931,
"text": "C#"
},
{
"code": null,
"e": 938,
"s": 934,
"text": "PHP"
},
{
"code": null,
"e": 949,
"s": 938,
"text": "Javascript"
},
{
"code": "// C++ program to find LCM of two numbers#include <iostream>using namespace std; // Recursive function to return gcd of a and blong long gcd(long long int a, long long int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to return LCM of two numberslong long lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Driver program to test above functionint main(){ int a = 15, b = 20; cout <<\"LCM of \" << a << \" and \" << b << \" is \" << lcm(a, b); return 0;}",
"e": 1439,
"s": 949,
"text": null
},
{
"code": "// C program to find LCM of two numbers#include <stdio.h> // Recursive function to return gcd of a and bint gcd(int a, int b){ if (a == 0) return b; return gcd(b % a, a);} // Function to return LCM of two numbersint lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Driver program to test above functionint main(){ int a = 15, b = 20; printf(\"LCM of %d and %d is %d \", a, b, lcm(a, b)); return 0;}",
"e": 1863,
"s": 1439,
"text": null
},
{
"code": "// Java program to find LCM of two numbers.class Test{ // Recursive method to return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to return LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Driver method public static void main(String[] args) { int a = 15, b = 20; System.out.println(\"LCM of \" + a + \" and \" + b + \" is \" + lcm(a, b)); }}",
"e": 2430,
"s": 1863,
"text": null
},
{
"code": "# Python program to find LCM of two numbers # Recursive function to return gcd of a and bdef gcd(a,b): if a == 0: return b return gcd(b % a, a) # Function to return LCM of two numbersdef lcm(a,b): return (a / gcd(a,b))* b # Driver program to test above functiona = 15b = 20print('LCM of', a, 'and', b, 'is', lcm(a, b)) # This code is contributed by Danish Raza",
"e": 2807,
"s": 2430,
"text": null
},
{
"code": "// C# program to find LCM// of two numbers.using System;class GFG { // Recursive method to // return gcd of a and b static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // method to return // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Driver method public static void Main() { int a = 15, b = 20; Console.WriteLine(\"LCM of \" + a + \" and \" + b + \" is \" + lcm(a, b)); }} // This code is contributed by anuj_67.",
"e": 3391,
"s": 2807,
"text": null
},
{
"code": "<?php// PHP program to find LCM of two numbers // Recursive function to// return gcd of a and bfunction gcd( $a, $b){ if ($a == 0) return $b; return gcd($b % $a, $a);} // Function to return LCM// of two numbersfunction lcm( $a, $b){ return ($a / gcd($a, $b)) * $b;} // Driver Code $a = 15; $b = 20; echo \"LCM of \",$a, \" and \" ,$b, \" is \", lcm($a, $b); // This code is contributed by anuj_67.?>",
"e": 3821,
"s": 3391,
"text": null
},
{
"code": "<script> // Javascript program to find LCM of two numbers // Recursive function to return gcd of a and bfunction gcd(a, b){if (b == 0) return a;return gcd(b, a % b);} // Function to return LCM of two numbersfunction lcm(a, b){ return (a / gcd(a, b)) * b;} // Driver program to test above function let a = 15, b = 20; document.write(\"LCM of \" + a + \" and \" + b + \" is \" + lcm(a, b)); // This code is contributed by Mayank Tyagi </script>",
"e": 4280,
"s": 3821,
"text": null
},
{
"code": null,
"e": 4303,
"s": 4280,
"text": "LCM of 15 and 20 is 60"
},
{
"code": null,
"e": 4336,
"s": 4303,
"text": "Time Complexity: O(log(min(a,b))"
},
{
"code": null,
"e": 4369,
"s": 4336,
"text": "Auxiliary Space: O(log(min(a,b))"
},
{
"code": null,
"e": 4398,
"s": 4369,
"text": "https://youtu.be/anSfYgbo694"
},
{
"code": null,
"e": 4522,
"s": 4398,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 4527,
"s": 4522,
"text": "vt_m"
},
{
"code": null,
"e": 4540,
"s": 4527,
"text": "SoumikMondal"
},
{
"code": null,
"e": 4554,
"s": 4540,
"text": "DeepakMangla1"
},
{
"code": null,
"e": 4564,
"s": 4554,
"text": "jayonet19"
},
{
"code": null,
"e": 4580,
"s": 4564,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 4592,
"s": 4580,
"text": "mayur_patil"
},
{
"code": null,
"e": 4601,
"s": 4592,
"text": "mk420464"
},
{
"code": null,
"e": 4617,
"s": 4601,
"text": "subhammahato348"
},
{
"code": null,
"e": 4633,
"s": 4617,
"text": "souravmahato348"
},
{
"code": null,
"e": 4647,
"s": 4633,
"text": "codewithrathi"
},
{
"code": null,
"e": 4655,
"s": 4647,
"text": "GCD-LCM"
},
{
"code": null,
"e": 4664,
"s": 4655,
"text": "SAP Labs"
},
{
"code": null,
"e": 4677,
"s": 4664,
"text": "Mathematical"
},
{
"code": null,
"e": 4696,
"s": 4677,
"text": "School Programming"
},
{
"code": null,
"e": 4705,
"s": 4696,
"text": "SAP Labs"
},
{
"code": null,
"e": 4718,
"s": 4705,
"text": "Mathematical"
},
{
"code": null,
"e": 4816,
"s": 4718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4846,
"s": 4816,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4889,
"s": 4846,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4949,
"s": 4889,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4964,
"s": 4949,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4988,
"s": 4964,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5006,
"s": 4988,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5031,
"s": 5006,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5047,
"s": 5031,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5070,
"s": 5047,
"text": "Introduction To PYTHON"
}
] |
JLink | Java Linker
|
18 Nov, 2021
In a single sentence, we can say that Jlink is used to create our own customized small JRE(Java RunTime Environment). JLink is the Java’s new command line tool(available in JDK_HOME/bin) which allows us to link sets of only required modules (and their dependencies) to create runtime environment (our own JRE). Usually, we use the default JRE for running our programs which are provided by the Oracle Corporation, but if we want our own JRE like geeks jre then we can go for JLINK.
Suppose you have written a small program for adding two numbers. Now it’s a very basic program in java. We can run our program with default JRE.
Java
public class Practice { public static void main(String[] args) { System.out.println(10 + 5); }}
To run this program, it will use a Practice.class file, a String.class file, a System.class file and an Object.class file( as every class in java is a child class of Object class). So we will need mostly three to four classes to run this program.
We can easily run this program with the default JRE, but the JRE provided by Oracle corporation contains 4300+ predefined .class files. When we run this program and we are using the default JRE then we need to maintain all the 4300+ classes on our machine and hence memory is wasted(size of JRE9 is 204mb). To run a 4kb program what is the use of maintaining a 204mb sized JRE. So, on the Clients machine there is a lot of memory wasted. So, a customized JRE is best which will only contain these four classes on the clients machine. And a customized JRE is best when you are using a specific number of classes in the program.So, the biggest use or advantage of customized JRE is that we can create a small JRE by using only the needed modules. Hence, Jlink’s main intention is to avoid shipping everything and also to run on very small devices with little memory. JLink also has a list of plugins that will help optimize our solutions.Syntax:
jlink [options] –module-path modulepath –add-modules module [, module...]
Example of JLink using a module based application:
module demoModule
{
// keeping it empty
}
Practice.java
package packTest public class Practice {
public static void main(String[] args)
{
System.out.println("JLINK DEMO");
}
}
To compile a module based application:
javac --module-source-path src -d com -m -demoModule
Now to run this program we need only two modules one is the demoModule and the other is java.base module ( contains String class, Object class, and System class). Using this two modules we can create our own customized JRE. So add java.base module in src directory. Now we can create our own JRE by using the following JLink command:
jlink --module-path src --add-modules demoModule, java.base --output demojre
Now our own jre is created. Now go to your created jre bin folder like demmojre/bin Now to run:- java -m demoModule/packTest.PracticeOutput:
JLINK DEMO
To know the size of our own customized jre, we can check it properties.There are a number of plugins available for JLink. Some of them are: –
exclude-files
class-for-name
include-locales
vm
system-modules
and many more...........
simmytarika5
Articles
GBlog
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
SQL | DROP, TRUNCATE
Difference Between Object And Class
Implementation of LinkedList in Javascript
DSA Sheet by Love Babbar
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
Practice for cracking any coding interview
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 537,
"s": 54,
"text": "In a single sentence, we can say that Jlink is used to create our own customized small JRE(Java RunTime Environment). JLink is the Java’s new command line tool(available in JDK_HOME/bin) which allows us to link sets of only required modules (and their dependencies) to create runtime environment (our own JRE). Usually, we use the default JRE for running our programs which are provided by the Oracle Corporation, but if we want our own JRE like geeks jre then we can go for JLINK. "
},
{
"code": null,
"e": 684,
"s": 537,
"text": "Suppose you have written a small program for adding two numbers. Now it’s a very basic program in java. We can run our program with default JRE. "
},
{
"code": null,
"e": 689,
"s": 684,
"text": "Java"
},
{
"code": "public class Practice { public static void main(String[] args) { System.out.println(10 + 5); }}",
"e": 801,
"s": 689,
"text": null
},
{
"code": null,
"e": 1049,
"s": 801,
"text": "To run this program, it will use a Practice.class file, a String.class file, a System.class file and an Object.class file( as every class in java is a child class of Object class). So we will need mostly three to four classes to run this program. "
},
{
"code": null,
"e": 1995,
"s": 1049,
"text": "We can easily run this program with the default JRE, but the JRE provided by Oracle corporation contains 4300+ predefined .class files. When we run this program and we are using the default JRE then we need to maintain all the 4300+ classes on our machine and hence memory is wasted(size of JRE9 is 204mb). To run a 4kb program what is the use of maintaining a 204mb sized JRE. So, on the Clients machine there is a lot of memory wasted. So, a customized JRE is best which will only contain these four classes on the clients machine. And a customized JRE is best when you are using a specific number of classes in the program.So, the biggest use or advantage of customized JRE is that we can create a small JRE by using only the needed modules. Hence, Jlink’s main intention is to avoid shipping everything and also to run on very small devices with little memory. JLink also has a list of plugins that will help optimize our solutions.Syntax: "
},
{
"code": null,
"e": 2069,
"s": 1995,
"text": "jlink [options] –module-path modulepath –add-modules module [, module...]"
},
{
"code": null,
"e": 2125,
"s": 2073,
"text": "Example of JLink using a module based application: "
},
{
"code": null,
"e": 2173,
"s": 2125,
"text": "\nmodule demoModule\n{\n // keeping it empty\n}\n"
},
{
"code": null,
"e": 2187,
"s": 2173,
"text": "Practice.java"
},
{
"code": null,
"e": 2329,
"s": 2187,
"text": "\npackage packTest public class Practice {\n public static void main(String[] args)\n {\n System.out.println(\"JLINK DEMO\");\n }\n}\n"
},
{
"code": null,
"e": 2370,
"s": 2329,
"text": "To compile a module based application: "
},
{
"code": null,
"e": 2423,
"s": 2370,
"text": "javac --module-source-path src -d com -m -demoModule"
},
{
"code": null,
"e": 2759,
"s": 2423,
"text": "Now to run this program we need only two modules one is the demoModule and the other is java.base module ( contains String class, Object class, and System class). Using this two modules we can create our own customized JRE. So add java.base module in src directory. Now we can create our own JRE by using the following JLink command: "
},
{
"code": null,
"e": 2836,
"s": 2759,
"text": "jlink --module-path src --add-modules demoModule, java.base --output demojre"
},
{
"code": null,
"e": 2981,
"s": 2838,
"text": "Now our own jre is created. Now go to your created jre bin folder like demmojre/bin Now to run:- java -m demoModule/packTest.PracticeOutput: "
},
{
"code": null,
"e": 2992,
"s": 2981,
"text": "JLINK DEMO"
},
{
"code": null,
"e": 3136,
"s": 2992,
"text": "To know the size of our own customized jre, we can check it properties.There are a number of plugins available for JLink. Some of them are: – "
},
{
"code": null,
"e": 3150,
"s": 3136,
"text": "exclude-files"
},
{
"code": null,
"e": 3165,
"s": 3150,
"text": "class-for-name"
},
{
"code": null,
"e": 3181,
"s": 3165,
"text": "include-locales"
},
{
"code": null,
"e": 3184,
"s": 3181,
"text": "vm"
},
{
"code": null,
"e": 3199,
"s": 3184,
"text": "system-modules"
},
{
"code": null,
"e": 3224,
"s": 3199,
"text": "and many more..........."
},
{
"code": null,
"e": 3239,
"s": 3226,
"text": "simmytarika5"
},
{
"code": null,
"e": 3248,
"s": 3239,
"text": "Articles"
},
{
"code": null,
"e": 3254,
"s": 3248,
"text": "GBlog"
},
{
"code": null,
"e": 3259,
"s": 3254,
"text": "Java"
},
{
"code": null,
"e": 3264,
"s": 3259,
"text": "Java"
},
{
"code": null,
"e": 3362,
"s": 3264,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3388,
"s": 3362,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3435,
"s": 3388,
"text": "Time complexities of different data structures"
},
{
"code": null,
"e": 3456,
"s": 3435,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 3492,
"s": 3456,
"text": "Difference Between Object And Class"
},
{
"code": null,
"e": 3535,
"s": 3492,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 3560,
"s": 3535,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 3634,
"s": 3560,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 3689,
"s": 3634,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 3726,
"s": 3689,
"text": "Geek Streak - 24 Days POTD Challenge"
}
] |
Program to check if a number is Positive, Negative, Odd, Even, Zero
|
09 May, 2022
Prerequisite : Loops in Python To check whether a number is positive, negative, odd, even or zero. This problem is solved using if...elif...else and nested if...else statement.
Approach :
A number is positive if it is greater than zero. We check this in the expression of if.
If it is False, the number will either be zero or negative.
This is also tested in subsequent expression.
In case of odd and even A number is even if it is perfectly divisible by 2.
When the number is divided by 2, we use the remainder operator % to compute the remainder.If the remainder is not zero, the number is odd.
When the number is divided by 2, we use the remainder operator % to compute the remainder.
If the remainder is not zero, the number is odd.
Examples:
Input : 10
Output :
Positive number
10 is Even
Input : 0
Output : 0 is Even
Python
# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using if...elif...elsenum = 10if num > 0: print("Positive number")elif num == 0: print("Zero")else: print("Negative number") # Checking for odd and evenif (num % 2) == 0: print("{0} is Even".format(num))else: print("{0} is Odd".format(num))
Output:
Positive number
10 is Even
Python
# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using Nested ifnum = 20if num >= 0: if num == 0: print("Zero") else: print("Positive number")else: print("Negative number") # Checking for odd and evenif (num % 2) == 0: print("{0} is Even".format(num))else: print("{0} is Odd".format(num))
Output:
Positive number
20 is Even
simmytarika5
Python
School Programming
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()
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 May, 2022"
},
{
"code": null,
"e": 231,
"s": 53,
"text": "Prerequisite : Loops in Python To check whether a number is positive, negative, odd, even or zero. This problem is solved using if...elif...else and nested if...else statement. "
},
{
"code": null,
"e": 243,
"s": 231,
"text": "Approach : "
},
{
"code": null,
"e": 331,
"s": 243,
"text": "A number is positive if it is greater than zero. We check this in the expression of if."
},
{
"code": null,
"e": 391,
"s": 331,
"text": "If it is False, the number will either be zero or negative."
},
{
"code": null,
"e": 437,
"s": 391,
"text": "This is also tested in subsequent expression."
},
{
"code": null,
"e": 513,
"s": 437,
"text": "In case of odd and even A number is even if it is perfectly divisible by 2."
},
{
"code": null,
"e": 653,
"s": 513,
"text": " When the number is divided by 2, we use the remainder operator % to compute the remainder.If the remainder is not zero, the number is odd."
},
{
"code": null,
"e": 744,
"s": 653,
"text": "When the number is divided by 2, we use the remainder operator % to compute the remainder."
},
{
"code": null,
"e": 793,
"s": 744,
"text": "If the remainder is not zero, the number is odd."
},
{
"code": null,
"e": 803,
"s": 793,
"text": "Examples:"
},
{
"code": null,
"e": 850,
"s": 803,
"text": "Input : 10\nOutput :\nPositive number\n10 is Even"
},
{
"code": null,
"e": 879,
"s": 850,
"text": "Input : 0\nOutput : 0 is Even"
},
{
"code": null,
"e": 886,
"s": 879,
"text": "Python"
},
{
"code": "# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using if...elif...elsenum = 10if num > 0: print(\"Positive number\")elif num == 0: print(\"Zero\")else: print(\"Negative number\") # Checking for odd and evenif (num % 2) == 0: print(\"{0} is Even\".format(num))else: print(\"{0} is Odd\".format(num))",
"e": 1213,
"s": 886,
"text": null
},
{
"code": null,
"e": 1248,
"s": 1213,
"text": "Output:\nPositive number\n10 is Even"
},
{
"code": null,
"e": 1255,
"s": 1248,
"text": "Python"
},
{
"code": "# Python Code to check if a number is# Positive, Negative, Odd, Even, Zero# Using Nested ifnum = 20if num >= 0: if num == 0: print(\"Zero\") else: print(\"Positive number\")else: print(\"Negative number\") # Checking for odd and evenif (num % 2) == 0: print(\"{0} is Even\".format(num))else: print(\"{0} is Odd\".format(num))",
"e": 1593,
"s": 1255,
"text": null
},
{
"code": null,
"e": 1628,
"s": 1593,
"text": "Output:\nPositive number\n20 is Even"
},
{
"code": null,
"e": 1641,
"s": 1628,
"text": "simmytarika5"
},
{
"code": null,
"e": 1648,
"s": 1641,
"text": "Python"
},
{
"code": null,
"e": 1667,
"s": 1648,
"text": "School Programming"
},
{
"code": null,
"e": 1765,
"s": 1667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1783,
"s": 1765,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1825,
"s": 1783,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1847,
"s": 1825,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1882,
"s": 1847,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1908,
"s": 1882,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1926,
"s": 1908,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1951,
"s": 1926,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 1967,
"s": 1951,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 1990,
"s": 1967,
"text": "Introduction To PYTHON"
}
] |
Python pass Statement
|
24 Aug, 2021
The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored.
The pass statement is generally used as a placeholder i.e. when the user does not know what code to write. So user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute. So user can simply place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using pass statement user avoids this error.
Syntax:
pass
Example 1: Pass statement can be used in empty functions
Python3
def geekFunction: pass
Example 2: pass statement can also be used in empty class
Python3
class geekClass: pass
Example 3: pass statement can be used in for loop when user doesn’t know what to code inside the loop
Python3
n = 10for i in range(n): # pass can be used as placeholder # when code is to added later pass
Example 4: pass statement can be used with conditional statements
Python3
a = 10b = 20 if(a<b): passelse: print("b<a")
Example 5: lets take another example in which the pass statement get executed when the condition is true
Python3
li =['a', 'b', 'c', 'd'] for i in li: if(i =='a'): pass else: print(i)
Output:
b
c
d
nusk3r
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 213,
"s": 53,
"text": "The pass statement is a null statement. But the difference between pass and comment is that comment is ignored by the interpreter whereas pass is not ignored. "
},
{
"code": null,
"e": 621,
"s": 213,
"text": "The pass statement is generally used as a placeholder i.e. when the user does not know what code to write. So user simply places pass at that line. Sometimes, pass is used when the user doesn’t want any code to execute. So user can simply place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if statements. So using pass statement user avoids this error."
},
{
"code": null,
"e": 629,
"s": 621,
"text": "Syntax:"
},
{
"code": null,
"e": 634,
"s": 629,
"text": "pass"
},
{
"code": null,
"e": 691,
"s": 634,
"text": "Example 1: Pass statement can be used in empty functions"
},
{
"code": null,
"e": 699,
"s": 691,
"text": "Python3"
},
{
"code": "def geekFunction: pass",
"e": 723,
"s": 699,
"text": null
},
{
"code": null,
"e": 781,
"s": 723,
"text": "Example 2: pass statement can also be used in empty class"
},
{
"code": null,
"e": 789,
"s": 781,
"text": "Python3"
},
{
"code": "class geekClass: pass",
"e": 812,
"s": 789,
"text": null
},
{
"code": null,
"e": 914,
"s": 812,
"text": "Example 3: pass statement can be used in for loop when user doesn’t know what to code inside the loop"
},
{
"code": null,
"e": 922,
"s": 914,
"text": "Python3"
},
{
"code": "n = 10for i in range(n): # pass can be used as placeholder # when code is to added later pass",
"e": 1022,
"s": 922,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1022,
"text": "Example 4: pass statement can be used with conditional statements "
},
{
"code": null,
"e": 1097,
"s": 1089,
"text": "Python3"
},
{
"code": "a = 10b = 20 if(a<b): passelse: print(\"b<a\")",
"e": 1144,
"s": 1097,
"text": null
},
{
"code": null,
"e": 1250,
"s": 1144,
"text": "Example 5: lets take another example in which the pass statement get executed when the condition is true "
},
{
"code": null,
"e": 1258,
"s": 1250,
"text": "Python3"
},
{
"code": "li =['a', 'b', 'c', 'd'] for i in li: if(i =='a'): pass else: print(i)",
"e": 1349,
"s": 1258,
"text": null
},
{
"code": null,
"e": 1357,
"s": 1349,
"text": "Output:"
},
{
"code": null,
"e": 1363,
"s": 1357,
"text": "b\nc\nd"
},
{
"code": null,
"e": 1370,
"s": 1363,
"text": "nusk3r"
},
{
"code": null,
"e": 1384,
"s": 1370,
"text": "python-basics"
},
{
"code": null,
"e": 1391,
"s": 1384,
"text": "Python"
}
] |
How to convert timestamp to time ago in PHP ?
|
10 Jan, 2019
Given a time and the task is to convert timestamp to time ago. The time ago format removes the problem of different time zones conversions. Given below is a function to do the time conversions. In this function, taking the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format. To make this function, need to define some rules which determine the year, month, date, minutes etc from the remaining date after subtraction.
Example 1:
<?php// PHP program to convert timestamp// to time ago function time_Ago($time) { // Calculate difference between current // time and given timestamp in seconds $diff = time() - $time; // Time difference in seconds $sec = $diff; // Convert time difference in minutes $min = round($diff / 60 ); // Convert time difference in hours $hrs = round($diff / 3600); // Convert time difference in days $days = round($diff / 86400 ); // Convert time difference in weeks $weeks = round($diff / 604800); // Convert time difference in months $mnths = round($diff / 2600640 ); // Convert time difference in years $yrs = round($diff / 31207680 ); // Check for seconds if($sec <= 60) { echo "$sec seconds ago"; } // Check for minutes else if($min <= 60) { if($min==1) { echo "one minute ago"; } else { echo "$min minutes ago"; } } // Check for hours else if($hrs <= 24) { if($hrs == 1) { echo "an hour ago"; } else { echo "$hrs hours ago"; } } // Check for days else if($days <= 7) { if($days == 1) { echo "Yesterday"; } else { echo "$days days ago"; } } // Check for weeks else if($weeks <= 4.3) { if($weeks == 1) { echo "a week ago"; } else { echo "$weeks weeks ago"; } } // Check for months else if($mnths <= 12) { if($mnths == 1) { echo "a month ago"; } else { echo "$mnths months ago"; } } // Check for years else { if($yrs == 1) { echo "one year ago"; } else { echo "$yrs years ago"; } }} // Initialize current time$curr_time = "2013-07-10 09:09:09"; // The strtotime() function converts// English textual date-time// description to a UNIX timestamp.$time_ago = strtotime($curr_time); // Display the time agoecho time_Ago($time_ago) . "\n"; // Initialize current time$curr_time="2019-01-05 09:09:09"; // The strtotime() function converts// English textual date-time// description to a UNIX timestamp.$time_ago =strtotime($curr_time); // Display the time agoecho time_Ago($time_ago);?>
6 years ago
5 days ago
Example 2:
<?php// PHP program to convert timestamp// to time ago function to_time_ago( $time ) { // Calculate difference between current // time and given timestamp in seconds $diff = time() - $time; if( $diff < 1 ) { return 'less than 1 second ago'; } $time_rules = array ( 12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second' ); foreach( $time_rules as $secs => $str ) { $div = $diff / $secs; if( $div >= 1 ) { $t = round( $div ); return $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago'; } }} // to_time_ago() function callecho to_time_ago( time() - 5); ?>
5 seconds ago
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jan, 2019"
},
{
"code": null,
"e": 504,
"s": 28,
"text": "Given a time and the task is to convert timestamp to time ago. The time ago format removes the problem of different time zones conversions. Given below is a function to do the time conversions. In this function, taking the timestamp as an input and then subtract it from the current timestamp to convert it into the time ago format. To make this function, need to define some rules which determine the year, month, date, minutes etc from the remaining date after subtraction."
},
{
"code": null,
"e": 515,
"s": 504,
"text": "Example 1:"
},
{
"code": "<?php// PHP program to convert timestamp// to time ago function time_Ago($time) { // Calculate difference between current // time and given timestamp in seconds $diff = time() - $time; // Time difference in seconds $sec = $diff; // Convert time difference in minutes $min = round($diff / 60 ); // Convert time difference in hours $hrs = round($diff / 3600); // Convert time difference in days $days = round($diff / 86400 ); // Convert time difference in weeks $weeks = round($diff / 604800); // Convert time difference in months $mnths = round($diff / 2600640 ); // Convert time difference in years $yrs = round($diff / 31207680 ); // Check for seconds if($sec <= 60) { echo \"$sec seconds ago\"; } // Check for minutes else if($min <= 60) { if($min==1) { echo \"one minute ago\"; } else { echo \"$min minutes ago\"; } } // Check for hours else if($hrs <= 24) { if($hrs == 1) { echo \"an hour ago\"; } else { echo \"$hrs hours ago\"; } } // Check for days else if($days <= 7) { if($days == 1) { echo \"Yesterday\"; } else { echo \"$days days ago\"; } } // Check for weeks else if($weeks <= 4.3) { if($weeks == 1) { echo \"a week ago\"; } else { echo \"$weeks weeks ago\"; } } // Check for months else if($mnths <= 12) { if($mnths == 1) { echo \"a month ago\"; } else { echo \"$mnths months ago\"; } } // Check for years else { if($yrs == 1) { echo \"one year ago\"; } else { echo \"$yrs years ago\"; } }} // Initialize current time$curr_time = \"2013-07-10 09:09:09\"; // The strtotime() function converts// English textual date-time// description to a UNIX timestamp.$time_ago = strtotime($curr_time); // Display the time agoecho time_Ago($time_ago) . \"\\n\"; // Initialize current time$curr_time=\"2019-01-05 09:09:09\"; // The strtotime() function converts// English textual date-time// description to a UNIX timestamp.$time_ago =strtotime($curr_time); // Display the time agoecho time_Ago($time_ago);?>",
"e": 2939,
"s": 515,
"text": null
},
{
"code": null,
"e": 2963,
"s": 2939,
"text": "6 years ago\n5 days ago\n"
},
{
"code": null,
"e": 2974,
"s": 2963,
"text": "Example 2:"
},
{
"code": "<?php// PHP program to convert timestamp// to time ago function to_time_ago( $time ) { // Calculate difference between current // time and given timestamp in seconds $diff = time() - $time; if( $diff < 1 ) { return 'less than 1 second ago'; } $time_rules = array ( 12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute', 1 => 'second' ); foreach( $time_rules as $secs => $str ) { $div = $diff / $secs; if( $div >= 1 ) { $t = round( $div ); return $t . ' ' . $str . ( $t > 1 ? 's' : '' ) . ' ago'; } }} // to_time_ago() function callecho to_time_ago( time() - 5); ?>",
"e": 3933,
"s": 2974,
"text": null
},
{
"code": null,
"e": 3948,
"s": 3933,
"text": "5 seconds ago\n"
},
{
"code": null,
"e": 3955,
"s": 3948,
"text": "Picked"
},
{
"code": null,
"e": 3979,
"s": 3955,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3983,
"s": 3979,
"text": "PHP"
},
{
"code": null,
"e": 3996,
"s": 3983,
"text": "PHP Programs"
},
{
"code": null,
"e": 4015,
"s": 3996,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4032,
"s": 4015,
"text": "Web Technologies"
},
{
"code": null,
"e": 4036,
"s": 4032,
"text": "PHP"
},
{
"code": null,
"e": 4134,
"s": 4036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4216,
"s": 4134,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 4261,
"s": 4216,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 4312,
"s": 4261,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 4342,
"s": 4312,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 4365,
"s": 4342,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 4417,
"s": 4365,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 4499,
"s": 4417,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 4522,
"s": 4499,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 4564,
"s": 4522,
"text": "How to create admin login page using PHP?"
}
] |
Python – Get Last N characters of a string
|
24 Feb, 2021
Given a string and an integer N, the task is to write a python program to print the last N characters of the string.
Example:
Input: Geeks For Geeks!; N = 4
Output: eks!
Explanation: The given string is Geeks For Geeks! and the last 4 characters is eks!.
Input: PYTHON; N=1
Output: N
Explanation: The given string is PYTHON and the last character is N.
Method 1: Using a loop to get to the last N characters of the given string.
Python3
# get inputStr = "Geeks For Geeks!"N = 4 # print the stringprint(Str) # iterate loopwhile(N > 0): # print character print(Str[-N], end='') # decrement the value of N N = N-1
Output:
Geeks For Geeks!
eks!
Method 2: Using list slicing to print the last n characters of the given string.
Python
# get inputStr = "Geeks For Geeks!"N = 4 # print the stringprint(Str) # get length of stringlength = len(Str) # create a new string of last N charactersStr2 = Str[length - N:] # print Last N charactersprint(Str2)
Output:
Geeks For Geeks!
eks!
Python string-programs
Technical Scripter 2020
Python
Python Programs
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": "\n24 Feb, 2021"
},
{
"code": null,
"e": 170,
"s": 52,
"text": "Given a string and an integer N, the task is to write a python program to print the last N characters of the string. "
},
{
"code": null,
"e": 179,
"s": 170,
"text": "Example:"
},
{
"code": null,
"e": 210,
"s": 179,
"text": "Input: Geeks For Geeks!; N = 4"
},
{
"code": null,
"e": 223,
"s": 210,
"text": "Output: eks!"
},
{
"code": null,
"e": 308,
"s": 223,
"text": "Explanation: The given string is Geeks For Geeks! and the last 4 characters is eks!."
},
{
"code": null,
"e": 327,
"s": 308,
"text": "Input: PYTHON; N=1"
},
{
"code": null,
"e": 337,
"s": 327,
"text": "Output: N"
},
{
"code": null,
"e": 406,
"s": 337,
"text": "Explanation: The given string is PYTHON and the last character is N."
},
{
"code": null,
"e": 483,
"s": 406,
"text": "Method 1: Using a loop to get to the last N characters of the given string. "
},
{
"code": null,
"e": 491,
"s": 483,
"text": "Python3"
},
{
"code": "# get inputStr = \"Geeks For Geeks!\"N = 4 # print the stringprint(Str) # iterate loopwhile(N > 0): # print character print(Str[-N], end='') # decrement the value of N N = N-1",
"e": 681,
"s": 491,
"text": null
},
{
"code": null,
"e": 689,
"s": 681,
"text": "Output:"
},
{
"code": null,
"e": 711,
"s": 689,
"text": "Geeks For Geeks!\neks!"
},
{
"code": null,
"e": 793,
"s": 711,
"text": "Method 2: Using list slicing to print the last n characters of the given string. "
},
{
"code": null,
"e": 800,
"s": 793,
"text": "Python"
},
{
"code": "# get inputStr = \"Geeks For Geeks!\"N = 4 # print the stringprint(Str) # get length of stringlength = len(Str) # create a new string of last N charactersStr2 = Str[length - N:] # print Last N charactersprint(Str2)",
"e": 1017,
"s": 800,
"text": null
},
{
"code": null,
"e": 1025,
"s": 1017,
"text": "Output:"
},
{
"code": null,
"e": 1047,
"s": 1025,
"text": "Geeks For Geeks!\neks!"
},
{
"code": null,
"e": 1070,
"s": 1047,
"text": "Python string-programs"
},
{
"code": null,
"e": 1094,
"s": 1070,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1101,
"s": 1094,
"text": "Python"
},
{
"code": null,
"e": 1117,
"s": 1101,
"text": "Python Programs"
},
{
"code": null,
"e": 1136,
"s": 1117,
"text": "Technical Scripter"
}
] |
Python | Similarity metrics of strings
|
12 Mar, 2019
This particular utility is quite in demand nowadays due to the similarity computation requirements in many fields of Computer Science such as Machine Learning, A.I and web development domains, hence techniques to compute similarity between any given containers can be quite useful. Let’s discuss certain ways in which this can be done.
Method #1 : Using Naive Approach(sum() + zip())We can perform this particular task using the naive approach, using sum and zip functions we can formulate a utility function that can compute the similarity of both the strings.
# Python3 code to demonstrate # similarity between strings# using naive method (sum() + zip()) # Utility function to compute similaritydef similar(str1, str2): str1 = str1 + ' ' * (len(str2) - len(str1)) str2 = str2 + ' ' * (len(str1) - len(str2)) return sum(1 if i == j else 0 for i, j in zip(str1, str2)) / float(len(str1)) # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks4geeks' # using naive method (sum() + zip())# similarity between stringsres = similar(test_string1, test_string2) # printing the resultprint ("The similarity between 2 strings is : " + str(res))
The similarity between 2 strings is : 0.38461538461538464
Method #2 : Using SequenceMatcher.ratio()There’s an inbuilt method, that helps to perform this particular task and is recommended to achieve this particular task as it doesn’t require custom approach but uses built in constructs to perform task more efficiently.
# Python3 code to demonstrate # similarity between strings# using SequenceMatcher.ratio()from difflib import SequenceMatcher # Utility function to compute similaritydef similar(str1, str2): return SequenceMatcher(None, str1, str2).ratio() # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks' # using SequenceMatcher.ratio()# similarity between stringsres = similar(test_string1, test_string2) # printing the resultprint ("The similarity between 2 strings is : " + str(res))
The similarity between 2 strings is : 0.5555555555555556
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2019"
},
{
"code": null,
"e": 364,
"s": 28,
"text": "This particular utility is quite in demand nowadays due to the similarity computation requirements in many fields of Computer Science such as Machine Learning, A.I and web development domains, hence techniques to compute similarity between any given containers can be quite useful. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 590,
"s": 364,
"text": "Method #1 : Using Naive Approach(sum() + zip())We can perform this particular task using the naive approach, using sum and zip functions we can formulate a utility function that can compute the similarity of both the strings."
},
{
"code": "# Python3 code to demonstrate # similarity between strings# using naive method (sum() + zip()) # Utility function to compute similaritydef similar(str1, str2): str1 = str1 + ' ' * (len(str2) - len(str1)) str2 = str2 + ' ' * (len(str1) - len(str2)) return sum(1 if i == j else 0 for i, j in zip(str1, str2)) / float(len(str1)) # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks4geeks' # using naive method (sum() + zip())# similarity between stringsres = similar(test_string1, test_string2) # printing the resultprint (\"The similarity between 2 strings is : \" + str(res))",
"e": 1212,
"s": 590,
"text": null
},
{
"code": null,
"e": 1271,
"s": 1212,
"text": "The similarity between 2 strings is : 0.38461538461538464\n"
},
{
"code": null,
"e": 1536,
"s": 1273,
"text": "Method #2 : Using SequenceMatcher.ratio()There’s an inbuilt method, that helps to perform this particular task and is recommended to achieve this particular task as it doesn’t require custom approach but uses built in constructs to perform task more efficiently."
},
{
"code": "# Python3 code to demonstrate # similarity between strings# using SequenceMatcher.ratio()from difflib import SequenceMatcher # Utility function to compute similaritydef similar(str1, str2): return SequenceMatcher(None, str1, str2).ratio() # Initializing stringstest_string1 = 'Geeksforgeeks'test_string2 = 'Geeks' # using SequenceMatcher.ratio()# similarity between stringsres = similar(test_string1, test_string2) # printing the resultprint (\"The similarity between 2 strings is : \" + str(res))",
"e": 2039,
"s": 1536,
"text": null
},
{
"code": null,
"e": 2098,
"s": 2039,
"text": "The similarity between 2 strings is : 0.5555555555555556\n"
},
{
"code": null,
"e": 2121,
"s": 2098,
"text": "Python string-programs"
},
{
"code": null,
"e": 2128,
"s": 2121,
"text": "Python"
},
{
"code": null,
"e": 2144,
"s": 2128,
"text": "Python Programs"
},
{
"code": null,
"e": 2242,
"s": 2144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2274,
"s": 2242,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2301,
"s": 2274,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2322,
"s": 2301,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2345,
"s": 2322,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2401,
"s": 2345,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2423,
"s": 2401,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2462,
"s": 2423,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2500,
"s": 2462,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2537,
"s": 2500,
"text": "Python Program for Fibonacci numbers"
}
] |
How to add custom fonts in Kivy – Python?
|
24 Feb, 2021
Prerequisites: Kivy Tutorial
Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also. It is an open-source Python library for the rapid development of multi-touch applications. Its graphic engine is built over OpenGL, and it supports fast graphics pipeline.
In this article, we will develop a GUI window using kivy framework of Python, and we will add a button on this window and we will add our own font style on this button’s text. For this task you should have a custom font style, don’t worry if you don’t have yours you can download from this link here you will get ample of font styles you can also download and unzip them. After unzipping you will get files in .ttf format keep those files because they are holding the actual font styles.
Step-by-step approach:
Basic Approach for using the custom font in kivy application:
Import button
Import kivyApp
Import labelbase
Import builder
Create App class
Return layout
Run an instance of the class
Implementation:
Python3
# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import App # importing labelbase which which # register our custom font for applicationfrom kivy.core.text import LabelBasefrom kivy.lang import Builder # this is the main class which will# render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string(""" # adding our buttonButton: # text which will appear on first button text:"first button" # specifying the fontstyle name that we # have registered in main.py file font_name:"Lemonada" font_size:65 """) # registering our new custom fontstyleLabelBase.register(name='Lemonada', fn_regular='Lemonada-VariableFont_wght.ttf') # running the applicationuiApp().run()
Output:
Python-kivy
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 83,
"s": 54,
"text": "Prerequisites: Kivy Tutorial"
},
{
"code": null,
"e": 492,
"s": 83,
"text": "Kivy is a platform-independent GUI tool in Python. It can run on Android, IOS, Linux and Windows, etc. This is the only GUI library from python which can independently run on the android device even we can use it on Raspberry pi also. It is an open-source Python library for the rapid development of multi-touch applications. Its graphic engine is built over OpenGL, and it supports fast graphics pipeline. "
},
{
"code": null,
"e": 980,
"s": 492,
"text": "In this article, we will develop a GUI window using kivy framework of Python, and we will add a button on this window and we will add our own font style on this button’s text. For this task you should have a custom font style, don’t worry if you don’t have yours you can download from this link here you will get ample of font styles you can also download and unzip them. After unzipping you will get files in .ttf format keep those files because they are holding the actual font styles."
},
{
"code": null,
"e": 1003,
"s": 980,
"text": "Step-by-step approach:"
},
{
"code": null,
"e": 1065,
"s": 1003,
"text": "Basic Approach for using the custom font in kivy application:"
},
{
"code": null,
"e": 1079,
"s": 1065,
"text": "Import button"
},
{
"code": null,
"e": 1094,
"s": 1079,
"text": "Import kivyApp"
},
{
"code": null,
"e": 1111,
"s": 1094,
"text": "Import labelbase"
},
{
"code": null,
"e": 1126,
"s": 1111,
"text": "Import builder"
},
{
"code": null,
"e": 1143,
"s": 1126,
"text": "Create App class"
},
{
"code": null,
"e": 1157,
"s": 1143,
"text": "Return layout"
},
{
"code": null,
"e": 1186,
"s": 1157,
"text": "Run an instance of the class"
},
{
"code": null,
"e": 1202,
"s": 1186,
"text": "Implementation:"
},
{
"code": null,
"e": 1210,
"s": 1202,
"text": "Python3"
},
{
"code": "# importing button widget from kivy frameworkfrom kivy.uix.button import Buttonfrom kivy.app import App # importing labelbase which which # register our custom font for applicationfrom kivy.core.text import LabelBasefrom kivy.lang import Builder # this is the main class which will# render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string(\"\"\" # adding our buttonButton: # text which will appear on first button text:\"first button\" # specifying the fontstyle name that we # have registered in main.py file font_name:\"Lemonada\" font_size:65 \"\"\") # registering our new custom fontstyleLabelBase.register(name='Lemonada', fn_regular='Lemonada-VariableFont_wght.ttf') # running the applicationuiApp().run()",
"e": 2089,
"s": 1210,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2089,
"text": "Output:"
},
{
"code": null,
"e": 2109,
"s": 2097,
"text": "Python-kivy"
},
{
"code": null,
"e": 2133,
"s": 2109,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2140,
"s": 2133,
"text": "Python"
},
{
"code": null,
"e": 2159,
"s": 2140,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2257,
"s": 2159,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2299,
"s": 2257,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2321,
"s": 2299,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2347,
"s": 2321,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2379,
"s": 2347,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2408,
"s": 2379,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2435,
"s": 2408,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2471,
"s": 2435,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2502,
"s": 2471,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2539,
"s": 2502,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Find if given matrix is Toeplitz or not
|
04 Jul, 2022
Given a square matrix, find if it’s a Toeplitz matrix or not. A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are same.In general, any n×n matrix mat[][] is a Toeplitz matrix if every cell mat[i][j] is same as mat[i-1][j-1], mat[i+1][j+1], mat[i-2][j-2], mat[i+2][j+2], .. for every cell mat[i][j] and all the valid cells mat[i+k][j+k] or mat[i-k][j-k]
Examples :
Input: mat[N][N] = {{ 6, 7, 8},
{ 4, 6, 7},
{ 1, 4, 6}},
Output : True;
Values in all diagonals are same.
Input: mat[N][N] = {{ 6, 7, 8, 9 },
{ 4, 6, 7, 8 },
{ 1, 4, 6, 7 },
{ 0, 1, 4, 6 }};
Output : True;
Input: mat[N][N] = {{ 6, 3, 8},
{ 4, 9, 7},
{ 1, 4, 6}},
Output : False;
The idea is very simple. For each element of first row and first column(or last row and last column) in the matrix, we check if descending diagonal starting from that element have same values or not. If we found any diagonal having different values, we return false.
Below is the implementation of the above code:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check whether given matrix// is a Toeplitz matrix or not#include <iostream>using namespace std;#define N 5#define M 4 // Function to check if all elements present in// descending diagonal starting from position// (i, j) in the matrix are all same or notbool checkDiagonal(int mat[N][M], int i, int j){ int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true;} // Function to check whether given matrix is a// Toeplitz matrix or notbool isToeplitz(int mat[N][M]){ // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true;} // Driver codeint main(){ int mat[N][M] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) cout << "Matrix is a Toeplitz "; else cout << "Matrix is not a Toeplitz "; return 0;}
// Java program to check whether given matrix// is a Toeplitz matrix or notimport java.io.*; class GFG{ public static int N = 5; public static int M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static boolean checkDiagonal(int mat[][], int i, int j) { int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not static boolean isToeplitz(int mat[][]) { // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } // Driver code public static void main(String[] args) { int mat[][] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) System.out.println("Matrix is a Toeplitz "); else System.out.println("Matrix is not a Toeplitz "); }} // This code is contributed by Pramod Kumar
# Python3 program to check whether given# matrix is a Toeplitz matrix or notN = 5M = 4 # Function to check if all elements present in# descending diagonal starting from position# (i, j) in the matrix are all same or not def checkDiagonal(mat, i, j): res = mat[i][j] i += 1 j += 1 while (i < N and j < M): # mismatch found if (mat[i][j] != res): return False i += 1 j += 1 # we only reach here when all elements # in given diagonal are same return True # Function to check whether given# matrix is a Toeplitz matrix or not def isToeplitz(mat): # do for each element in first row for j in range(M): # check descending diagonal starting from # position (0, j) in the matrix if not(checkDiagonal(mat, 0, j)): return False # do for each element in first column for i in range(1, N): # check descending diagonal starting # from position (i, 0) in the matrix if not(checkDiagonal(mat, i, 0)): return False return True # Driver Codeif __name__ == "__main__": mat = [[6, 7, 8, 9], [4, 6, 7, 8], [1, 4, 6, 7], [0, 1, 4, 6], [2, 0, 1, 4]] # Function call if(isToeplitz(mat)): print("Matrix is a Toeplitz") else: print("Matrix is not a Toeplitz") # This code is contributed by Jasmine K Grewal
// C# program to check whether given matrix// is a Toeplitz matrix or notusing System; class GFG { public static int N = 5; public static int M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static bool checkDiagonal(int[, ] mat, int i, int j) { int res = mat[i, j]; while (++i < N && ++j < M) { // mismatch found if (mat[i, j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not static bool isToeplitz(int[, ] mat) { // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } // Driver code public static void Main() { int[, ] mat = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) Console.WriteLine("Matrix is a Toeplitz "); else Console.WriteLine("Matrix is not a Toeplitz "); }} // This code is contributed by KRV.
<?php// PHP program to check whether// given matrix is a Toeplitz// matrix or not // Function to check if all// elements present in descending// diagonal starting from position// (i, j) in the matrix are all// same or notfunction checkDiagonal($mat, $i, $j){ $N = 5; $M = 4; $res = $mat[$i][$j]; while (++$i < $N && ++$j < $M) { // mismatch found if ($mat[$i][$j] != $res) return false; } // we only reach here when // all elements in given // diagonal are same return true;} // Function to check whether// given matrix is a// Toeplitz matrix or notfunction isToeplitz($mat){ $N = 5; $M = 4; // do for each element in first row for ($i = 0; $i < $M; $i++) { // check descending diagonal // starting from position // (0, j) in the matrix if (!checkDiagonal($mat, 0, $i)) return false; } // do for each element // in first column for ($i = 1; $i < $N; $i++) { // check descending diagonal // starting from position // (i, 0) in the matrix if (!checkDiagonal($mat, $i, 0)) return false; } // we only reach here when // each descending diagonal // from left to right is same return true;} // Driver code$mat = array(array( 6, 7, 8, 9 ), array( 4, 6, 7, 8 ), array( 1, 4, 6, 7 ), array( 0, 1, 4, 6 ), array( 2, 0, 1, 4 )); // Function callif (isToeplitz($mat)) echo "Matrix is a Toeplitz ";else echo "Matrix is not a Toeplitz "; // This code is contributed// by nitin mittal.?>
<script> // Javascript program to check whether given matrix // is a Toeplitz matrix or not let N = 5; let M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not function checkDiagonal(mat, i, j) { let res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not function isToeplitz(mat) { // do for each element in first row for (let i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (let i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } let mat = [ [ 6, 7, 8, 9 ], [ 4, 6, 7, 8 ], [ 1, 4, 6, 7 ], [ 0, 1, 4, 6 ], [ 2, 0, 1, 4 ] ]; // Function call if (isToeplitz(mat)) document.write("Matrix is a Toeplitz "); else document.write("Matrix is not a Toeplitz "); </script>
Matrix is a Toeplitz
The time complexity of this solution would be O(n2) as we are traversing each element in the matrix once only.Auxiliary Space: O(1)
Hashing based approach:
Consider an element at index (i, j) of matrix of dimension (m, n). For the matrix to be diagonal-constant, all the elements in the diagonal must be same. Consider the diagonal containing this (i, j) element. The other elements in this diagonal will have their index of the form (i+k, j+k) or (i-k, j-k). Notice that whatever x-value and y-value of these indexes are, their difference is always the same. i.e. (i+k)-(j+k) == (i-k)-(j-k) == i-j.
The diagram below gives a better visualization of this idea. Consider the diagonal coloured yellow. The difference between x-value and y-value of any index on this diagonal is 2 (2-0, 3-1, 4-2, 5-3). Same can be observed for all body diagonals.
Index of a Toeplitz matrix
For red-coloured diagonal, difference is 3. For green-coloured diagonal, difference is 0. For orange-coloured diagonal, difference is -2 and so on...
The idea is to exploit the fact that for a Toeplitz matrix, these individual index differences for particular diagonals will be unique. And since it is a constant-diagonal matrix, for all these unique keys, there should be unique values same as any element on that diagonal. So, we create a HashMap to store these (key, value) pairs. At any moment if we encounter a value, that is different from it’s corresponding stored key value, we return false.
Below is the implementation of the above code:
C++
Java
Python3
C#
Javascript
// C++ program to check whether given// matrix is a Toeplitz matrix or not#include <bits/stdc++.h>using namespace std; bool isToeplitz(vector<vector<int>> matrix){ // row = number of rows // col = number of columns int row = matrix.size(); int col = matrix[0].size(); // HashMap to store key,value pairs map<int, int> Map; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (Map[key]) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (Map[key] != matrix[i][j]) return false; } // Else we put key,value pair in hashmap else { Map[i - j] = matrix[i][j]; } } } return true;} // Driver codeint main(){ vector<vector<int>> matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? "Yes" : "No"; cout << result; return 0;} // This code is contributed by divyesh072019
// JAVA program to check whether given matrix// is a Toeplitz matrix or not import java.util.*; class GFG { static boolean isToeplitz(int[][] matrix) { // row = number of rows // col = number of columns int row = matrix.length; int col = matrix[0].length; // HashMap to store key,value pairs HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { int key = i - j; // if key value exists in the hashmap, if (map.containsKey(key)) { // we check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map.get(key) != matrix[i][j]) return false; } // else we put key,value pair in hashmap else { map.put(i - j, matrix[i][j]); } } } return true; } // Driver Code public static void main(String[] args) { int[][] matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call String result = (isToeplitz(matrix)) ? "Yes" : "No"; System.out.println(result); }}
# Python3 program to check whether given matrix# is a Toeplitz matrix or not def isToeplitz(matrix): # row = number of rows # col = number of columns row = len(matrix) col = len(matrix[0]) # dictionary to store key,value pairs map = {} for i in range(row): for j in range(col): key = i-j # if key value exists in the map, if (key in map): # we check whether the current value stored # in this key matches to element at current # index or not. If not, return false if (map[key] != matrix[i][j]): return False # else we put key,value pair in map else: map[key] = matrix[i][j] return True # Driver Codeif __name__ == "__main__": matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]] # Function call if (isToeplitz(matrix)): print("Yes") else: print("No")
// C# program to check whether given// matrix is a Toeplitz matrix or notusing System;using System.Collections.Generic; class GFG{ static bool isToeplitz(int[,] matrix){ // row = number of rows // col = number of columns int row = matrix.GetLength(0); int col = matrix.GetLength(1); // HashMap to store key,value pairs Dictionary<int, int> map = new Dictionary<int, int>(); for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (map.ContainsKey(key)) { // We check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map[key] != matrix[i, j]) return false; } // Else we put key,value pair in hashmap else { map.Add(i - j, matrix[i, j]); } } } return true;} // Driver code static void Main(){ int[,] matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? "Yes" : "No"; Console.WriteLine(result);}} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program to check whether given // matrix is a Toeplitz matrix or not function isToeplitz(matrix) { // row = number of rows // col = number of columns let row = matrix.length; let col = matrix[0].length; // HashMap to store key,value pairs let map = new Map(); for(let i = 0; i < row; i++) { for(let j = 0; j < col; j++) { let key = i - j; // If key value exists in the hashmap, if (map.has(key)) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (map.get(key) != matrix[i][j]) return false; } // Else we put key,value pair in hashmap else { map.set(i - j, matrix[i][j]); } } } return true; } // Driver code let matrix = [ [ 12, 23, -32 ], [ -20, 12, 23 ], [ 56, -20, 12 ], [38, 56, -20 ] ]; // Function call let result = (isToeplitz(matrix)) ? "Yes" : "No"; document.write(result); </script>
Yes
Time Complexity: O(mn), where m is number of rows and n is number of columns.Space Complexity: O(m+n), because at worst case, if a matrix is Toeplitz, we have store exactly (m+n-1) key, value pairs. (In first row we have n distinct keys and then for next each m-1 rows, we keep adding one unique key to the map.
This article is contributed by Aarti_Rathi and Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
KRV
nitin mittal
jigyansu
divyeshrabadiya07
divyesh072019
mukesh07
vaibhavrabadiya3
surindertarika1234
shaheeneallamaiqbal
codewithmini
hardikkoriintern
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
The Celebrity Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Count all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 510,
"s": 52,
"text": "Given a square matrix, find if it’s a Toeplitz matrix or not. A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are same.In general, any n×n matrix mat[][] is a Toeplitz matrix if every cell mat[i][j] is same as mat[i-1][j-1], mat[i+1][j+1], mat[i-2][j-2], mat[i+2][j+2], .. for every cell mat[i][j] and all the valid cells mat[i+k][j+k] or mat[i-k][j-k] "
},
{
"code": null,
"e": 522,
"s": 510,
"text": "Examples : "
},
{
"code": null,
"e": 943,
"s": 522,
"text": "Input: mat[N][N] = {{ 6, 7, 8},\n { 4, 6, 7},\n { 1, 4, 6}},\nOutput : True;\nValues in all diagonals are same.\n\nInput: mat[N][N] = {{ 6, 7, 8, 9 },\n { 4, 6, 7, 8 },\n { 1, 4, 6, 7 },\n { 0, 1, 4, 6 }};\nOutput : True;\n\nInput: mat[N][N] = {{ 6, 3, 8},\n { 4, 9, 7},\n { 1, 4, 6}},\nOutput : False;"
},
{
"code": null,
"e": 1210,
"s": 943,
"text": "The idea is very simple. For each element of first row and first column(or last row and last column) in the matrix, we check if descending diagonal starting from that element have same values or not. If we found any diagonal having different values, we return false."
},
{
"code": null,
"e": 1257,
"s": 1210,
"text": "Below is the implementation of the above code:"
},
{
"code": null,
"e": 1261,
"s": 1257,
"text": "C++"
},
{
"code": null,
"e": 1266,
"s": 1261,
"text": "Java"
},
{
"code": null,
"e": 1274,
"s": 1266,
"text": "Python3"
},
{
"code": null,
"e": 1277,
"s": 1274,
"text": "C#"
},
{
"code": null,
"e": 1281,
"s": 1277,
"text": "PHP"
},
{
"code": null,
"e": 1292,
"s": 1281,
"text": "Javascript"
},
{
"code": "// C++ program to check whether given matrix// is a Toeplitz matrix or not#include <iostream>using namespace std;#define N 5#define M 4 // Function to check if all elements present in// descending diagonal starting from position// (i, j) in the matrix are all same or notbool checkDiagonal(int mat[N][M], int i, int j){ int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true;} // Function to check whether given matrix is a// Toeplitz matrix or notbool isToeplitz(int mat[N][M]){ // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true;} // Driver codeint main(){ int mat[N][M] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) cout << \"Matrix is a Toeplitz \"; else cout << \"Matrix is not a Toeplitz \"; return 0;}",
"e": 2893,
"s": 1292,
"text": null
},
{
"code": "// Java program to check whether given matrix// is a Toeplitz matrix or notimport java.io.*; class GFG{ public static int N = 5; public static int M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static boolean checkDiagonal(int mat[][], int i, int j) { int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not static boolean isToeplitz(int mat[][]) { // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } // Driver code public static void main(String[] args) { int mat[][] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) System.out.println(\"Matrix is a Toeplitz \"); else System.out.println(\"Matrix is not a Toeplitz \"); }} // This code is contributed by Pramod Kumar",
"e": 4823,
"s": 2893,
"text": null
},
{
"code": "# Python3 program to check whether given# matrix is a Toeplitz matrix or notN = 5M = 4 # Function to check if all elements present in# descending diagonal starting from position# (i, j) in the matrix are all same or not def checkDiagonal(mat, i, j): res = mat[i][j] i += 1 j += 1 while (i < N and j < M): # mismatch found if (mat[i][j] != res): return False i += 1 j += 1 # we only reach here when all elements # in given diagonal are same return True # Function to check whether given# matrix is a Toeplitz matrix or not def isToeplitz(mat): # do for each element in first row for j in range(M): # check descending diagonal starting from # position (0, j) in the matrix if not(checkDiagonal(mat, 0, j)): return False # do for each element in first column for i in range(1, N): # check descending diagonal starting # from position (i, 0) in the matrix if not(checkDiagonal(mat, i, 0)): return False return True # Driver Codeif __name__ == \"__main__\": mat = [[6, 7, 8, 9], [4, 6, 7, 8], [1, 4, 6, 7], [0, 1, 4, 6], [2, 0, 1, 4]] # Function call if(isToeplitz(mat)): print(\"Matrix is a Toeplitz\") else: print(\"Matrix is not a Toeplitz\") # This code is contributed by Jasmine K Grewal",
"e": 6224,
"s": 4823,
"text": null
},
{
"code": "// C# program to check whether given matrix// is a Toeplitz matrix or notusing System; class GFG { public static int N = 5; public static int M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static bool checkDiagonal(int[, ] mat, int i, int j) { int res = mat[i, j]; while (++i < N && ++j < M) { // mismatch found if (mat[i, j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not static bool isToeplitz(int[, ] mat) { // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } // Driver code public static void Main() { int[, ] mat = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) Console.WriteLine(\"Matrix is a Toeplitz \"); else Console.WriteLine(\"Matrix is not a Toeplitz \"); }} // This code is contributed by KRV.",
"e": 8105,
"s": 6224,
"text": null
},
{
"code": "<?php// PHP program to check whether// given matrix is a Toeplitz// matrix or not // Function to check if all// elements present in descending// diagonal starting from position// (i, j) in the matrix are all// same or notfunction checkDiagonal($mat, $i, $j){ $N = 5; $M = 4; $res = $mat[$i][$j]; while (++$i < $N && ++$j < $M) { // mismatch found if ($mat[$i][$j] != $res) return false; } // we only reach here when // all elements in given // diagonal are same return true;} // Function to check whether// given matrix is a// Toeplitz matrix or notfunction isToeplitz($mat){ $N = 5; $M = 4; // do for each element in first row for ($i = 0; $i < $M; $i++) { // check descending diagonal // starting from position // (0, j) in the matrix if (!checkDiagonal($mat, 0, $i)) return false; } // do for each element // in first column for ($i = 1; $i < $N; $i++) { // check descending diagonal // starting from position // (i, 0) in the matrix if (!checkDiagonal($mat, $i, 0)) return false; } // we only reach here when // each descending diagonal // from left to right is same return true;} // Driver code$mat = array(array( 6, 7, 8, 9 ), array( 4, 6, 7, 8 ), array( 1, 4, 6, 7 ), array( 0, 1, 4, 6 ), array( 2, 0, 1, 4 )); // Function callif (isToeplitz($mat)) echo \"Matrix is a Toeplitz \";else echo \"Matrix is not a Toeplitz \"; // This code is contributed// by nitin mittal.?>",
"e": 9707,
"s": 8105,
"text": null
},
{
"code": "<script> // Javascript program to check whether given matrix // is a Toeplitz matrix or not let N = 5; let M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not function checkDiagonal(mat, i, j) { let res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not function isToeplitz(mat) { // do for each element in first row for (let i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (let i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } let mat = [ [ 6, 7, 8, 9 ], [ 4, 6, 7, 8 ], [ 1, 4, 6, 7 ], [ 0, 1, 4, 6 ], [ 2, 0, 1, 4 ] ]; // Function call if (isToeplitz(mat)) document.write(\"Matrix is a Toeplitz \"); else document.write(\"Matrix is not a Toeplitz \"); </script>",
"e": 11413,
"s": 9707,
"text": null
},
{
"code": null,
"e": 11435,
"s": 11413,
"text": "Matrix is a Toeplitz "
},
{
"code": null,
"e": 11567,
"s": 11435,
"text": "The time complexity of this solution would be O(n2) as we are traversing each element in the matrix once only.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11592,
"s": 11567,
"text": "Hashing based approach: "
},
{
"code": null,
"e": 12037,
"s": 11592,
"text": "Consider an element at index (i, j) of matrix of dimension (m, n). For the matrix to be diagonal-constant, all the elements in the diagonal must be same. Consider the diagonal containing this (i, j) element. The other elements in this diagonal will have their index of the form (i+k, j+k) or (i-k, j-k). Notice that whatever x-value and y-value of these indexes are, their difference is always the same. i.e. (i+k)-(j+k) == (i-k)-(j-k) == i-j. "
},
{
"code": null,
"e": 12282,
"s": 12037,
"text": "The diagram below gives a better visualization of this idea. Consider the diagonal coloured yellow. The difference between x-value and y-value of any index on this diagonal is 2 (2-0, 3-1, 4-2, 5-3). Same can be observed for all body diagonals."
},
{
"code": null,
"e": 12309,
"s": 12282,
"text": "Index of a Toeplitz matrix"
},
{
"code": null,
"e": 12459,
"s": 12309,
"text": "For red-coloured diagonal, difference is 3. For green-coloured diagonal, difference is 0. For orange-coloured diagonal, difference is -2 and so on..."
},
{
"code": null,
"e": 12910,
"s": 12459,
"text": "The idea is to exploit the fact that for a Toeplitz matrix, these individual index differences for particular diagonals will be unique. And since it is a constant-diagonal matrix, for all these unique keys, there should be unique values same as any element on that diagonal. So, we create a HashMap to store these (key, value) pairs. At any moment if we encounter a value, that is different from it’s corresponding stored key value, we return false. "
},
{
"code": null,
"e": 12957,
"s": 12910,
"text": "Below is the implementation of the above code:"
},
{
"code": null,
"e": 12961,
"s": 12957,
"text": "C++"
},
{
"code": null,
"e": 12966,
"s": 12961,
"text": "Java"
},
{
"code": null,
"e": 12974,
"s": 12966,
"text": "Python3"
},
{
"code": null,
"e": 12977,
"s": 12974,
"text": "C#"
},
{
"code": null,
"e": 12988,
"s": 12977,
"text": "Javascript"
},
{
"code": "// C++ program to check whether given// matrix is a Toeplitz matrix or not#include <bits/stdc++.h>using namespace std; bool isToeplitz(vector<vector<int>> matrix){ // row = number of rows // col = number of columns int row = matrix.size(); int col = matrix[0].size(); // HashMap to store key,value pairs map<int, int> Map; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (Map[key]) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (Map[key] != matrix[i][j]) return false; } // Else we put key,value pair in hashmap else { Map[i - j] = matrix[i][j]; } } } return true;} // Driver codeint main(){ vector<vector<int>> matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? \"Yes\" : \"No\"; cout << result; return 0;} // This code is contributed by divyesh072019",
"e": 14456,
"s": 12988,
"text": null
},
{
"code": "// JAVA program to check whether given matrix// is a Toeplitz matrix or not import java.util.*; class GFG { static boolean isToeplitz(int[][] matrix) { // row = number of rows // col = number of columns int row = matrix.length; int col = matrix[0].length; // HashMap to store key,value pairs HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { int key = i - j; // if key value exists in the hashmap, if (map.containsKey(key)) { // we check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map.get(key) != matrix[i][j]) return false; } // else we put key,value pair in hashmap else { map.put(i - j, matrix[i][j]); } } } return true; } // Driver Code public static void main(String[] args) { int[][] matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call String result = (isToeplitz(matrix)) ? \"Yes\" : \"No\"; System.out.println(result); }}",
"e": 15994,
"s": 14456,
"text": null
},
{
"code": "# Python3 program to check whether given matrix# is a Toeplitz matrix or not def isToeplitz(matrix): # row = number of rows # col = number of columns row = len(matrix) col = len(matrix[0]) # dictionary to store key,value pairs map = {} for i in range(row): for j in range(col): key = i-j # if key value exists in the map, if (key in map): # we check whether the current value stored # in this key matches to element at current # index or not. If not, return false if (map[key] != matrix[i][j]): return False # else we put key,value pair in map else: map[key] = matrix[i][j] return True # Driver Codeif __name__ == \"__main__\": matrix = [[12, 23, -32], [-20, 12, 23], [56, -20, 12], [38, 56, -20]] # Function call if (isToeplitz(matrix)): print(\"Yes\") else: print(\"No\")",
"e": 17026,
"s": 15994,
"text": null
},
{
"code": "// C# program to check whether given// matrix is a Toeplitz matrix or notusing System;using System.Collections.Generic; class GFG{ static bool isToeplitz(int[,] matrix){ // row = number of rows // col = number of columns int row = matrix.GetLength(0); int col = matrix.GetLength(1); // HashMap to store key,value pairs Dictionary<int, int> map = new Dictionary<int, int>(); for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (map.ContainsKey(key)) { // We check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map[key] != matrix[i, j]) return false; } // Else we put key,value pair in hashmap else { map.Add(i - j, matrix[i, j]); } } } return true;} // Driver code static void Main(){ int[,] matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? \"Yes\" : \"No\"; Console.WriteLine(result);}} // This code is contributed by divyeshrabadiya07",
"e": 18625,
"s": 17026,
"text": null
},
{
"code": "<script> // JavaScript program to check whether given // matrix is a Toeplitz matrix or not function isToeplitz(matrix) { // row = number of rows // col = number of columns let row = matrix.length; let col = matrix[0].length; // HashMap to store key,value pairs let map = new Map(); for(let i = 0; i < row; i++) { for(let j = 0; j < col; j++) { let key = i - j; // If key value exists in the hashmap, if (map.has(key)) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (map.get(key) != matrix[i][j]) return false; } // Else we put key,value pair in hashmap else { map.set(i - j, matrix[i][j]); } } } return true; } // Driver code let matrix = [ [ 12, 23, -32 ], [ -20, 12, 23 ], [ 56, -20, 12 ], [38, 56, -20 ] ]; // Function call let result = (isToeplitz(matrix)) ? \"Yes\" : \"No\"; document.write(result); </script>",
"e": 20031,
"s": 18625,
"text": null
},
{
"code": null,
"e": 20035,
"s": 20031,
"text": "Yes"
},
{
"code": null,
"e": 20347,
"s": 20035,
"text": "Time Complexity: O(mn), where m is number of rows and n is number of columns.Space Complexity: O(m+n), because at worst case, if a matrix is Toeplitz, we have store exactly (m+n-1) key, value pairs. (In first row we have n distinct keys and then for next each m-1 rows, we keep adding one unique key to the map."
},
{
"code": null,
"e": 20658,
"s": 20347,
"text": "This article is contributed by Aarti_Rathi and Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 20662,
"s": 20658,
"text": "KRV"
},
{
"code": null,
"e": 20675,
"s": 20662,
"text": "nitin mittal"
},
{
"code": null,
"e": 20684,
"s": 20675,
"text": "jigyansu"
},
{
"code": null,
"e": 20702,
"s": 20684,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 20716,
"s": 20702,
"text": "divyesh072019"
},
{
"code": null,
"e": 20725,
"s": 20716,
"text": "mukesh07"
},
{
"code": null,
"e": 20742,
"s": 20725,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 20761,
"s": 20742,
"text": "surindertarika1234"
},
{
"code": null,
"e": 20781,
"s": 20761,
"text": "shaheeneallamaiqbal"
},
{
"code": null,
"e": 20794,
"s": 20781,
"text": "codewithmini"
},
{
"code": null,
"e": 20811,
"s": 20794,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 20818,
"s": 20811,
"text": "Matrix"
},
{
"code": null,
"e": 20825,
"s": 20818,
"text": "Matrix"
},
{
"code": null,
"e": 20923,
"s": 20825,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20958,
"s": 20923,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 21002,
"s": 20958,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 21033,
"s": 21002,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 21057,
"s": 21033,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 21104,
"s": 21057,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 21126,
"s": 21104,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 21208,
"s": 21126,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 21279,
"s": 21208,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 21317,
"s": 21279,
"text": "Unique paths in a Grid with Obstacles"
}
] |
CSS | backdrop-filter Property
|
18 Nov, 2019
The CSS backdrop-filter property is used to apply effects to the area behind an element. This is unlike the filter property where it applies the effect to the whole element. It can be used to eliminate the use of an extra element to style the background separately.
Syntax:
backdrop-filter: blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | none | initial | inherit
Property Values:
blur(): It is used to apply a Gaussian blur to the image. The default value of this function is 0 which applies no blur effect.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: blur(5px); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: blur(5px); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
brightness(): It is used to make the image lighter or darker. A value over 100% will brighten the image and a value below it will darken the image. If the brightness becomes 0%, it will completely black the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
contrast(): It is used to set the contrast of the image. The original image is at 100% contrast. If the contrast is below 0%, it will completely black the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
drop-shadow(): It is used to apply a drop shadow effect to the element. It accepts the horizontal and vertical shadow amounts along with the spread and color values.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
grayscale(): It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
hue-rotate(): It is used to apply a hue rotation to the image. The function value denotes the number of degrees around the color circle that the image circle would be adjusted. The default value is 0 which represents the original image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
invert(): It is used to invert the image. The default value is 0% which represents the original image and 100% will make the image completely inverted.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
opacity(): It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent and a value of 100% indicates the original image which is completely opaque.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
saturate(): It is used to set the saturation of the element. The default value is 100% which indicates the original image. A 0% value would indicate a completely unsaturated image and more than 100% would indicate a super-saturated image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
sepia(): It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
none: It is the default value and does not apply any effect to the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: none; padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: none; padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
initial: It is used to set this property to its default value.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: initial; padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:
Example:
<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: initial; padding: 2px; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class="container"> <div class="foreground"> This text is not affected by backdrop-filter. </div> </div></body> </html>
Output:
inherit: It inherits the property from its parent element.
Supported Browsers: The browsers supported by backdrop-filter property are listed below:
Google Chrome 76.0
Edge 17.0
Safari 9.0
Opera 34.0
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it 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": "\n18 Nov, 2019"
},
{
"code": null,
"e": 294,
"s": 28,
"text": "The CSS backdrop-filter property is used to apply effects to the area behind an element. This is unlike the filter property where it applies the effect to the whole element. It can be used to eliminate the use of an extra element to style the background separately."
},
{
"code": null,
"e": 302,
"s": 294,
"text": "Syntax:"
},
{
"code": null,
"e": 472,
"s": 302,
"text": "backdrop-filter: blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-rotate() | invert() | opacity() | saturate() | sepia() | none | initial | inherit"
},
{
"code": null,
"e": 489,
"s": 472,
"text": "Property Values:"
},
{
"code": null,
"e": 1423,
"s": 489,
"text": "blur(): It is used to apply a Gaussian blur to the image. The default value of this function is 0 which applies no blur effect.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: blur(5px); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 1432,
"s": 1423,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: blur(5px); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 2224,
"s": 1432,
"text": null
},
{
"code": null,
"e": 2232,
"s": 2224,
"text": "Output:"
},
{
"code": null,
"e": 3267,
"s": 2232,
"text": "brightness(): It is used to make the image lighter or darker. A value over 100% will brighten the image and a value below it will darken the image. If the brightness becomes 0%, it will completely black the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 3276,
"s": 3267,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: brightness(25%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 4083,
"s": 3276,
"text": null
},
{
"code": null,
"e": 4091,
"s": 4083,
"text": "Output:"
},
{
"code": null,
"e": 5068,
"s": 4091,
"text": "contrast(): It is used to set the contrast of the image. The original image is at 100% contrast. If the contrast is below 0%, it will completely black the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 5077,
"s": 5068,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: contrast(20%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 5878,
"s": 5077,
"text": null
},
{
"code": null,
"e": 5886,
"s": 5878,
"text": "Output:"
},
{
"code": null,
"e": 6884,
"s": 5886,
"text": "drop-shadow(): It is used to apply a drop shadow effect to the element. It accepts the horizontal and vertical shadow amounts along with the spread and color values.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 6893,
"s": 6884,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: drop-shadow(20px 10px red); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 7711,
"s": 6893,
"text": null
},
{
"code": null,
"e": 7719,
"s": 7711,
"text": "Output:"
},
{
"code": null,
"e": 8722,
"s": 7719,
"text": "grayscale(): It is used to convert the colors of the image into black and white. A value of 0% indicates the original image and 100% will indicate a completely black and white image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 8731,
"s": 8722,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: grayscale(75%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 9537,
"s": 8731,
"text": null
},
{
"code": null,
"e": 9545,
"s": 9537,
"text": "Output:"
},
{
"code": null,
"e": 10606,
"s": 9545,
"text": "hue-rotate(): It is used to apply a hue rotation to the image. The function value denotes the number of degrees around the color circle that the image circle would be adjusted. The default value is 0 which represents the original image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 10615,
"s": 10606,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: hue-rotate(180deg); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 11425,
"s": 10615,
"text": null
},
{
"code": null,
"e": 11433,
"s": 11425,
"text": "Output:"
},
{
"code": null,
"e": 12403,
"s": 11433,
"text": "invert(): It is used to invert the image. The default value is 0% which represents the original image and 100% will make the image completely inverted.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 12412,
"s": 12403,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: invert(100%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 13216,
"s": 12412,
"text": null
},
{
"code": null,
"e": 13224,
"s": 13216,
"text": "Output:"
},
{
"code": null,
"e": 14255,
"s": 13224,
"text": "opacity(): It is used to set the opacity of the image. The default value is 0% which indicates that the image is completely transparent and a value of 100% indicates the original image which is completely opaque.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 14264,
"s": 14255,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: opacity(50%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 15068,
"s": 14264,
"text": null
},
{
"code": null,
"e": 15076,
"s": 15068,
"text": "Output:"
},
{
"code": null,
"e": 16134,
"s": 15076,
"text": "saturate(): It is used to set the saturation of the element. The default value is 100% which indicates the original image. A 0% value would indicate a completely unsaturated image and more than 100% would indicate a super-saturated image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 16143,
"s": 16134,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: saturate(50%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 16948,
"s": 16143,
"text": null
},
{
"code": null,
"e": 16956,
"s": 16948,
"text": "Output:"
},
{
"code": null,
"e": 17933,
"s": 16956,
"text": "sepia(): It is used to convert the image to sepia giving it a warmer appearance. A 0% value represents the original image and 100% represents a completely sepia image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 17942,
"s": 17933,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: sepia(100%); padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 18737,
"s": 17942,
"text": null
},
{
"code": null,
"e": 18745,
"s": 18737,
"text": "Output:"
},
{
"code": null,
"e": 19629,
"s": 18745,
"text": "none: It is the default value and does not apply any effect to the image.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: none; padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 19638,
"s": 19629,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: none; padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 20434,
"s": 19638,
"text": null
},
{
"code": null,
"e": 20442,
"s": 20434,
"text": "Output:"
},
{
"code": null,
"e": 21318,
"s": 20442,
"text": "initial: It is used to set this property to its default value.Example:<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: initial; padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>Output:"
},
{
"code": null,
"e": 21327,
"s": 21318,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>CSS | backdrop-filter</title> <style> .container { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\"); background-size: cover; display: flex; align-items: center; justify-content: center; height: 100px; width: 360px; } .foreground { backdrop-filter: initial; padding: 2px; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | backdrop-filter</b> <div class=\"container\"> <div class=\"foreground\"> This text is not affected by backdrop-filter. </div> </div></body> </html>",
"e": 22126,
"s": 21327,
"text": null
},
{
"code": null,
"e": 22134,
"s": 22126,
"text": "Output:"
},
{
"code": null,
"e": 22193,
"s": 22134,
"text": "inherit: It inherits the property from its parent element."
},
{
"code": null,
"e": 22282,
"s": 22193,
"text": "Supported Browsers: The browsers supported by backdrop-filter property are listed below:"
},
{
"code": null,
"e": 22301,
"s": 22282,
"text": "Google Chrome 76.0"
},
{
"code": null,
"e": 22311,
"s": 22301,
"text": "Edge 17.0"
},
{
"code": null,
"e": 22322,
"s": 22311,
"text": "Safari 9.0"
},
{
"code": null,
"e": 22333,
"s": 22322,
"text": "Opera 34.0"
},
{
"code": null,
"e": 22348,
"s": 22333,
"text": "CSS-Properties"
},
{
"code": null,
"e": 22352,
"s": 22348,
"text": "CSS"
},
{
"code": null,
"e": 22369,
"s": 22352,
"text": "Web Technologies"
},
{
"code": null,
"e": 22467,
"s": 22369,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22504,
"s": 22467,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 22543,
"s": 22504,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 22582,
"s": 22543,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 22646,
"s": 22582,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 22707,
"s": 22646,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 22740,
"s": 22707,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 22801,
"s": 22740,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 22844,
"s": 22801,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 22916,
"s": 22844,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Python | Pandas DatetimeIndex.to_pydatetime()
|
29 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.to_pydatetime() function return DatetimeIndex as object ndarray of datetime.datetime objects. The function does not take any input value.
Syntax: DatetimeIndex.to_pydatetime()
Parameters : None
Return : ndarray
Example #1: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the DatetimeIndex to datetime.datetime objects.
# convert to datetime.datetime objects.didx.to_pydatetime()
Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object. Example #2: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects.
# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)
Output :
Now we want to convert the DatetimeIndex to datetime.datetime objects.
# convert to datetime.datetime objects.didx.to_pydatetime()
Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object.
Python pandas-datetimeIndex
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Dec, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 401,
"s": 242,
"text": "Pandas DatetimeIndex.to_pydatetime() function return DatetimeIndex as object ndarray of datetime.datetime objects. The function does not take any input value."
},
{
"code": null,
"e": 439,
"s": 401,
"text": "Syntax: DatetimeIndex.to_pydatetime()"
},
{
"code": null,
"e": 457,
"s": 439,
"text": "Parameters : None"
},
{
"code": null,
"e": 474,
"s": 457,
"text": "Return : ndarray"
},
{
"code": null,
"e": 606,
"s": 474,
"text": "Example #1: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5) # Print the DatetimeIndexprint(didx)",
"e": 834,
"s": 606,
"text": null
},
{
"code": null,
"e": 843,
"s": 834,
"text": "Output :"
},
{
"code": null,
"e": 914,
"s": 843,
"text": "Now we want to convert the DatetimeIndex to datetime.datetime objects."
},
{
"code": "# convert to datetime.datetime objects.didx.to_pydatetime()",
"e": 974,
"s": 914,
"text": null
},
{
"code": null,
"e": 1231,
"s": 974,
"text": "Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object. Example #2: Use DatetimeIndex.to_pydatetime() function to convert the DatetimeIndex as object ndarray of datetime.datetime objects."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5) # Print the DatetimeIndexprint(didx)",
"e": 1449,
"s": 1231,
"text": null
},
{
"code": null,
"e": 1458,
"s": 1449,
"text": "Output :"
},
{
"code": null,
"e": 1529,
"s": 1458,
"text": "Now we want to convert the DatetimeIndex to datetime.datetime objects."
},
{
"code": "# convert to datetime.datetime objects.didx.to_pydatetime()",
"e": 1589,
"s": 1529,
"text": null
},
{
"code": null,
"e": 1714,
"s": 1589,
"text": "Output :As we can see in the output, the function has converted the DatetimeIndex object to python datetime.datetime object."
},
{
"code": null,
"e": 1742,
"s": 1714,
"text": "Python pandas-datetimeIndex"
},
{
"code": null,
"e": 1756,
"s": 1742,
"text": "Python-pandas"
},
{
"code": null,
"e": 1763,
"s": 1756,
"text": "Python"
},
{
"code": null,
"e": 1861,
"s": 1763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1893,
"s": 1861,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1920,
"s": 1893,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1951,
"s": 1920,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1974,
"s": 1951,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1995,
"s": 1974,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2051,
"s": 1995,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2093,
"s": 2051,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2135,
"s": 2093,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2174,
"s": 2135,
"text": "Python | Get unique values from a list"
}
] |
How to create a frequency table for categorical data in R ?
|
30 Jun, 2021
In this article, we will see how to create a frequency table for categorical data in R Programming Language.
Method 1 : Using table() method
Tables in R are used for better organizing and summarizing the categorical variables. The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used for cross-tabulation and statistical analysis.
table (fac-vec, .. )
It can be converted to a data frame using as.data.frame() method which returns the output in the form of a tabular structure organized into two columns, the first one containing the input factor variable and second, the counts of the corresponding variables, designated by “Freq”.
as.data.frame(table)
In case, a single argument is specified the number of rows in the resultant data frame is equivalent to the number of unique levels of the factor. The rep() method is also used to repeat the first argument n number of times.
Code:
R
# creating a factor vectorvec <- factor(c(letters[1 : 12], letters[8 : 24], letters[4 : 6])) # replicate the vector 2 timesfac_vec <- rep(vec , 2) # generating frequency table of # the factor vectorfreq <- table(fac_vec)print ("Frequency DataFrame") # converting the table into dataframefreq_df <- as.data.frame(freq)print (freq_df)
Output:
[1] "Frequency DataFrame"
fac_vec Freq
1 a 2
2 b 2
3 c 2
4 d 4
5 e 4
6 f 4
7 g 2
8 h 4
9 i 4
10 j 4
11 k 4
12 l 4
13 m 2
14 n 2
15 o 2
16 p 2
17 q 2
18 r 2
19 s 2
20 t 2
21 u 2
22 v 2
23 w 2
24 x 2
The table() method can take multiple arguments as input, and as a result, a data frame of all the possible unique combinations is returned. Each value of the first argument is mapped with the second argument value, and the frequency of this combination is returned.
R
set.seed(1) # creating a dataframedata_frame = data.frame( "col1" = sample(1:2, 8, replace = TRUE) , "col2" = sample(letters[1:3], 8, replace = TRUE)) print ("Data Frame")print (data_frame) # generating frequency table of the# factor vectorfreq <- table(data_frame$col1, data_frame$col2)print ("Frequency DataFrame") # converting the table into dataframefreq_df <- as.data.frame(freq)print (freq_df)
Output:
[1] "Data Frame"
col1 col2
1 1 b
2 2 b
3 1 c
4 1 c
5 2 a
6 1 a
7 1 a
8 1 b
[1] "Frequency DataFrame"
Var1 Var2 Freq
1 1 a 2
2 2 a 1
3 1 b 2
4 2 b 1
5 1 c 2
6 2 c 0
The following program illustrates the concept of computing the frequency distribution over a large dataset and visualizing it:
R
library(data.table)library("ggplot2") # importing the datasetfile <- fread('ch11b.dat')print ("Dataset 5 rows")head(file) data <- as.data.frame(file)freq <- table(data$V5)print ("Frequency count of column V5")print (freq) # re-order levelscompute <- function(x) { freq <- table(x) factor(x, levels = names(sort(freq)))} # plotting the dataggplot(data, aes(x = compute(`V5`))) + geom_bar() + xlab("Gender")
Output:
[1] "Dataset 5 rows"
V1 V2 V3 V4 V5
1: 1 307 930 36.58 0
2: 2 307 940 36.73 0
3: 3 307 950 36.93 0
4: 4 307 1000 37.15 0
5: 5 307 1010 37.23 0
6: 6 307 1020 37.24 0
[1] "Frequency count of column V5"
0 1
38 62
Frequency distribution over column V5
Method 2: Using count() method
The “plyr” package is used for data manipulation and modification, which can be installed into the working space using :
install.packages("plyr")
count() method in the plyr package is used to keep a frequency count of the categorical variables encountered. The method call is equivalent to as.data.frame(table(x)). However, it does not include combinations with zero counts. This method is considered to be better than table() method because it is faster and returns the output in the form of data frame, with direct headings for rows and columns.
count( fac-vec, .. )
Code:
R
# importing required librarieslibrary("plyr") # creating a factor vectorvec <- factor(c(letters[1:12], letters[8:24], letters[4:6])) # replicate the vector 2 timesfac_vec <- rep(vec , 2) # generating frequency table of the # factor vectorfreq <- count(fac_vec)print ("Frequency DataFrame")print (freq)
Output
[1] "Frequency DataFrame"
x Freq
1 a 2
2 b 2
3 c 2
4 d 4
5 e 4
6 f 4
7 g 2
8 h 4
9 i 4
10 j 4
11 k 4
12 l 4
13 m 2
14 n 2
15 o 2
16 p 2
17 q 2
18 r 2
19 s 2
20 t 2
21 u 2
22 v 2
23 w 2
24 x 2
The following code snippet illustrates the usage of the table() method over very large datasets of the power of 105 elements divided into two categories Male and Female:
R
# creating a factor vectorfac_vec <- factor(sample(c("Male", "Female"), 100000 , replace = TRUE)) # generating frequency table of the factor vectorfreq <- count(fac_vec)print ("Frequency DataFrame") # converting the table into data framefreq_df <- as.data.frame(freq)print (freq_df)
Output:
[1] "Frequency DataFrame"
x freq
1 Female 49936
2 Male 50064
Picked
R-Factors
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": "\n30 Jun, 2021"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "In this article, we will see how to create a frequency table for categorical data in R Programming Language."
},
{
"code": null,
"e": 169,
"s": 137,
"text": "Method 1 : Using table() method"
},
{
"code": null,
"e": 730,
"s": 169,
"text": "Tables in R are used for better organizing and summarizing the categorical variables. The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used for cross-tabulation and statistical analysis."
},
{
"code": null,
"e": 751,
"s": 730,
"text": "table (fac-vec, .. )"
},
{
"code": null,
"e": 1033,
"s": 751,
"text": "It can be converted to a data frame using as.data.frame() method which returns the output in the form of a tabular structure organized into two columns, the first one containing the input factor variable and second, the counts of the corresponding variables, designated by “Freq”. "
},
{
"code": null,
"e": 1054,
"s": 1033,
"text": "as.data.frame(table)"
},
{
"code": null,
"e": 1280,
"s": 1054,
"text": "In case, a single argument is specified the number of rows in the resultant data frame is equivalent to the number of unique levels of the factor. The rep() method is also used to repeat the first argument n number of times. "
},
{
"code": null,
"e": 1286,
"s": 1280,
"text": "Code:"
},
{
"code": null,
"e": 1288,
"s": 1286,
"text": "R"
},
{
"code": "# creating a factor vectorvec <- factor(c(letters[1 : 12], letters[8 : 24], letters[4 : 6])) # replicate the vector 2 timesfac_vec <- rep(vec , 2) # generating frequency table of # the factor vectorfreq <- table(fac_vec)print (\"Frequency DataFrame\") # converting the table into dataframefreq_df <- as.data.frame(freq)print (freq_df)",
"e": 1655,
"s": 1288,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Output:"
},
{
"code": null,
"e": 2089,
"s": 1663,
"text": "[1] \"Frequency DataFrame\"\n fac_vec Freq\n1 a 2\n2 b 2\n3 c 2\n4 d 4\n5 e 4\n6 f 4\n7 g 2\n8 h 4\n9 i 4\n10 j 4\n11 k 4\n12 l 4\n13 m 2\n14 n 2\n15 o 2\n16 p 2\n17 q 2\n18 r 2\n19 s 2\n20 t 2\n21 u 2\n22 v 2\n23 w 2\n24 x 2"
},
{
"code": null,
"e": 2356,
"s": 2089,
"text": "The table() method can take multiple arguments as input, and as a result, a data frame of all the possible unique combinations is returned. Each value of the first argument is mapped with the second argument value, and the frequency of this combination is returned. "
},
{
"code": null,
"e": 2358,
"s": 2356,
"text": "R"
},
{
"code": "set.seed(1) # creating a dataframedata_frame = data.frame( \"col1\" = sample(1:2, 8, replace = TRUE) , \"col2\" = sample(letters[1:3], 8, replace = TRUE)) print (\"Data Frame\")print (data_frame) # generating frequency table of the# factor vectorfreq <- table(data_frame$col1, data_frame$col2)print (\"Frequency DataFrame\") # converting the table into dataframefreq_df <- as.data.frame(freq)print (freq_df)",
"e": 2773,
"s": 2358,
"text": null
},
{
"code": null,
"e": 2781,
"s": 2773,
"text": "Output:"
},
{
"code": null,
"e": 3051,
"s": 2781,
"text": "[1] \"Data Frame\"\n col1 col2\n1 1 b\n2 2 b\n3 1 c\n4 1 c\n5 2 a\n6 1 a\n7 1 a\n8 1 b\n[1] \"Frequency DataFrame\"\n Var1 Var2 Freq\n1 1 a 2\n2 2 a 1\n3 1 b 2\n4 2 b 1\n5 1 c 2\n6 2 c 0"
},
{
"code": null,
"e": 3178,
"s": 3051,
"text": "The following program illustrates the concept of computing the frequency distribution over a large dataset and visualizing it:"
},
{
"code": null,
"e": 3180,
"s": 3178,
"text": "R"
},
{
"code": "library(data.table)library(\"ggplot2\") # importing the datasetfile <- fread('ch11b.dat')print (\"Dataset 5 rows\")head(file) data <- as.data.frame(file)freq <- table(data$V5)print (\"Frequency count of column V5\")print (freq) # re-order levelscompute <- function(x) { freq <- table(x) factor(x, levels = names(sort(freq)))} # plotting the dataggplot(data, aes(x = compute(`V5`))) + geom_bar() + xlab(\"Gender\") ",
"e": 3595,
"s": 3180,
"text": null
},
{
"code": null,
"e": 3603,
"s": 3595,
"text": "Output:"
},
{
"code": null,
"e": 3847,
"s": 3603,
"text": "[1] \"Dataset 5 rows\" \nV1 V2 V3 V4 V5 \n1: 1 307 930 36.58 0 \n2: 2 307 940 36.73 0 \n3: 3 307 950 36.93 0 \n4: 4 307 1000 37.15 0 \n5: 5 307 1010 37.23 0 \n6: 6 307 1020 37.24 0 \n[1] \"Frequency count of column V5\" \n0 1 \n38 62 "
},
{
"code": null,
"e": 3885,
"s": 3847,
"text": "Frequency distribution over column V5"
},
{
"code": null,
"e": 3916,
"s": 3885,
"text": "Method 2: Using count() method"
},
{
"code": null,
"e": 4037,
"s": 3916,
"text": "The “plyr” package is used for data manipulation and modification, which can be installed into the working space using :"
},
{
"code": null,
"e": 4062,
"s": 4037,
"text": "install.packages(\"plyr\")"
},
{
"code": null,
"e": 4465,
"s": 4062,
"text": "count() method in the plyr package is used to keep a frequency count of the categorical variables encountered. The method call is equivalent to as.data.frame(table(x)). However, it does not include combinations with zero counts. This method is considered to be better than table() method because it is faster and returns the output in the form of data frame, with direct headings for rows and columns. "
},
{
"code": null,
"e": 4486,
"s": 4465,
"text": "count( fac-vec, .. )"
},
{
"code": null,
"e": 4492,
"s": 4486,
"text": "Code:"
},
{
"code": null,
"e": 4494,
"s": 4492,
"text": "R"
},
{
"code": "# importing required librarieslibrary(\"plyr\") # creating a factor vectorvec <- factor(c(letters[1:12], letters[8:24], letters[4:6])) # replicate the vector 2 timesfac_vec <- rep(vec , 2) # generating frequency table of the # factor vectorfreq <- count(fac_vec)print (\"Frequency DataFrame\")print (freq)",
"e": 4831,
"s": 4494,
"text": null
},
{
"code": null,
"e": 4838,
"s": 4831,
"text": "Output"
},
{
"code": null,
"e": 5264,
"s": 4838,
"text": "[1] \"Frequency DataFrame\"\n x Freq\n1 a 2\n2 b 2\n3 c 2\n4 d 4\n5 e 4\n6 f 4\n7 g 2\n8 h 4\n9 i 4\n10 j 4\n11 k 4\n12 l 4\n13 m 2\n14 n 2\n15 o 2\n16 p 2\n17 q 2\n18 r 2\n19 s 2\n20 t 2\n21 u 2\n22 v 2\n23 w 2\n24 x 2"
},
{
"code": null,
"e": 5435,
"s": 5264,
"text": "The following code snippet illustrates the usage of the table() method over very large datasets of the power of 105 elements divided into two categories Male and Female: "
},
{
"code": null,
"e": 5437,
"s": 5435,
"text": "R"
},
{
"code": "# creating a factor vectorfac_vec <- factor(sample(c(\"Male\", \"Female\"), 100000 , replace = TRUE)) # generating frequency table of the factor vectorfreq <- count(fac_vec)print (\"Frequency DataFrame\") # converting the table into data framefreq_df <- as.data.frame(freq)print (freq_df)",
"e": 5746,
"s": 5437,
"text": null
},
{
"code": null,
"e": 5754,
"s": 5746,
"text": "Output:"
},
{
"code": null,
"e": 5830,
"s": 5754,
"text": "[1] \"Frequency DataFrame\" \n x freq\n 1 Female 49936\n \n2 Male 50064"
},
{
"code": null,
"e": 5837,
"s": 5830,
"text": "Picked"
},
{
"code": null,
"e": 5847,
"s": 5837,
"text": "R-Factors"
},
{
"code": null,
"e": 5858,
"s": 5847,
"text": "R Language"
}
] |
Powershell - Format-List Cmdlet
|
Format-List cmdlet can be used to formats the output as a list of properties where a property appears on a new line.
In these examples, we're see the Format-List cmdlet in action.
In this example, first we've a file test.txt in D:\temp\test with content "Welcome to TutorialsPoint.Com" and test1.txt with content "Hello World!" and "Welcome to TutorialsPoint.Com" in two lines.
Get the file details in a variable.
$A = Get-ChildItem D:\temp\test\*.txt
Get the file details using Format-List cmdlet.
Format-List -InputObject $A
You can see following output in PowerShell console.
Directory: D:\temp\test
Name : test.txt
Length : 31
CreationTime : 4/4/2018 4:48:38 PM
LastWriteTime : 4/11/2018 4:40:15 PM
LastAccessTime : 4/4/2018 4:48:38 PM
VersionInfo : File: D:\temp\test\test.txt
InternalName:
OriginalFilename:
FileVersion:
FileDescription:
Product:
ProductVersion:
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language:
Name : test1.txt
Length : 44
CreationTime : 4/12/2018 6:54:48 PM
LastWriteTime : 4/12/2018 6:56:21 PM
LastAccessTime : 4/12/2018 6:54:48 PM
VersionInfo : File: D:\temp\test\test1.txt
InternalName:
OriginalFilename:
FileVersion:
FileDescription:
Product:
ProductVersion:
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language:
Get the list of services
Type the following command in PowerShell ISE Console
Get-Service | Format-List
You can see following output in PowerShell console.
Name : AdobeARMservice
DisplayName : Adobe Acrobat Update Service
Status : Running
DependentServices : {}
ServicesDependedOn : {}
CanPauseAndContinue : False
CanShutdown : False
CanStop : True
ServiceType : Win32OwnProcess
Name : AdobeFlashPlayerUpdateSvc
DisplayName : Adobe Flash Player Update Service
Status : Stopped
DependentServices : {}
ServicesDependedOn : {}
CanPauseAndContinue : False
CanShutdown : False
CanStop : False
ServiceType : Win32OwnProcess
...
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2151,
"s": 2034,
"text": "Format-List cmdlet can be used to formats the output as a list of properties where a property appears on a new line."
},
{
"code": null,
"e": 2214,
"s": 2151,
"text": "In these examples, we're see the Format-List cmdlet in action."
},
{
"code": null,
"e": 2412,
"s": 2214,
"text": "In this example, first we've a file test.txt in D:\\temp\\test with content \"Welcome to TutorialsPoint.Com\" and test1.txt with content \"Hello World!\" and \"Welcome to TutorialsPoint.Com\" in two lines."
},
{
"code": null,
"e": 2448,
"s": 2412,
"text": "Get the file details in a variable."
},
{
"code": null,
"e": 2486,
"s": 2448,
"text": "$A = Get-ChildItem D:\\temp\\test\\*.txt"
},
{
"code": null,
"e": 2533,
"s": 2486,
"text": "Get the file details using Format-List cmdlet."
},
{
"code": null,
"e": 2561,
"s": 2533,
"text": "Format-List -InputObject $A"
},
{
"code": null,
"e": 2613,
"s": 2561,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 4006,
"s": 2613,
"text": "Directory: D:\\temp\\test\n\nName : test.txt\nLength : 31\nCreationTime : 4/4/2018 4:48:38 PM\nLastWriteTime : 4/11/2018 4:40:15 PM\nLastAccessTime : 4/4/2018 4:48:38 PM\nVersionInfo : File: D:\\temp\\test\\test.txt\n InternalName: \n OriginalFilename: \n FileVersion: \n FileDescription: \n Product: \n ProductVersion: \n Debug: False\n Patched: False\n PreRelease: False\n PrivateBuild: False\n SpecialBuild: False\n Language: \n \n\nName : test1.txt\nLength : 44\nCreationTime : 4/12/2018 6:54:48 PM\nLastWriteTime : 4/12/2018 6:56:21 PM\nLastAccessTime : 4/12/2018 6:54:48 PM\nVersionInfo : File: D:\\temp\\test\\test1.txt\n InternalName: \n OriginalFilename: \n FileVersion: \n FileDescription: \n Product: \n ProductVersion: \n Debug: False\n Patched: False\n PreRelease: False\n PrivateBuild: False\n SpecialBuild: False\n Language: \n"
},
{
"code": null,
"e": 4031,
"s": 4006,
"text": "Get the list of services"
},
{
"code": null,
"e": 4084,
"s": 4031,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 4110,
"s": 4084,
"text": "Get-Service | Format-List"
},
{
"code": null,
"e": 4162,
"s": 4110,
"text": "You can see following output in PowerShell console."
},
{
"code": null,
"e": 4773,
"s": 4162,
"text": "Name : AdobeARMservice\nDisplayName : Adobe Acrobat Update Service\nStatus : Running\nDependentServices : {}\nServicesDependedOn : {}\nCanPauseAndContinue : False\nCanShutdown : False\nCanStop : True\nServiceType : Win32OwnProcess\n\nName : AdobeFlashPlayerUpdateSvc\nDisplayName : Adobe Flash Player Update Service\nStatus : Stopped\nDependentServices : {}\nServicesDependedOn : {}\nCanPauseAndContinue : False\nCanShutdown : False\nCanStop : False\nServiceType : Win32OwnProcess\n... \n"
},
{
"code": null,
"e": 4808,
"s": 4773,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4829,
"s": 4808,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 4864,
"s": 4829,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4877,
"s": 4864,
"text": " Vijay Saini"
},
{
"code": null,
"e": 4914,
"s": 4877,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 4926,
"s": 4914,
"text": " Fettah Ben"
},
{
"code": null,
"e": 4933,
"s": 4926,
"text": " Print"
},
{
"code": null,
"e": 4944,
"s": 4933,
"text": " Add Notes"
}
] |
K-means Clustering and Variants. The clustering problem is to group a... | by Arun Jagota | Towards Data Science
|
The clustering problem is to group a set of data points into clusters. Clusters should be internally tight. Clusters should also be well-separated.
Here is an example. Consider a geospatial map in which each pixel is green or yellow. A green pixel denotes a tree at that location. A yellow pixel denotes its absence. We’d like to cluster the trees into forests.
This is a representative example of a large class of clustering problems on geospatial data, at varying scales. For example, if we replace “green denoting a tree” with “red denoting a lit location”, we might hope to discover clusters of well-lit areas such as towns or neighborhoods.
In this post, we will cover the K-means clustering algorithm and its variants.
The K-means clustering algorithm requires fixing K, the number of clusters, in advance. This may seem like a serious limitation. In our example, how would we know the number of forests in advance?
That said, we can imagine some user interface that lets the user try out different values of K and see what forests get found? This interactive process might yet be useful.
The Algorithm
The K-means clustering algorithm works as follows. We are given the data set to be clustered, and a value of K. In our example, the data set would be the locations of the green pixels.
The algorithm initializes the K clusters (somehow). It then iteratively adjusts the clusters so long as they keep improving. We can stop the algorithm at any time. Or when the clusters stop changing (sufficiently).
How do we measure “clusters improving”? Let’s begin by noting that in K-means clustering clusters are represented by their means. (This explains the word “means” in the algorithm’s name.) In our trees example, a cluster’s mean is the associate forest’s center.
Next, we need the notion of how tight a cluster is. We will define a cluster’s width as the average distance of the cluster’s members from its mean. In our trees example, this is the average distance of a tree in a forest from the forest’s center. A rough proxy for the forest’s area.
A global measure of the tightness of the full set of clusters may then be defined as the sum of the widths of the clusters.
Next, let’s look at what happens inside an iteration. The algorithm tries to improve the current clustering. In two steps. First, it reassigns each data point to the cluster whose mean is closest to it. Next, it recomputes the cluster means from the updated assignments.
The intuition that an iteration (in which an assignment changes) improves the clustering is as follows. (This is not proof — just intuition!) In the first step, at least one data point got reassigned to a cluster whose center it is nearer to. This tends to reduce the width of one or both affected clusters. The second step, which recomputes the cluster means, often reduces the width further.
Example
Let’s illustrate this in the example below in which both effects come into play. We have 3 1D points to be clustered: 1, 5, and 6. Say the current clusters are {1, 5} and {6}. Their means are 3 and 6 respectively. In the next iteration 5 moves to the second cluster. This results in the clustering {1} and {5, 6} having means 1 and 5.5 respectively.
This shift is depicted below.
{1, 5}, {6} → {1}, {5, 6}
Let’s see how the cluster widths changed. The original clusters {1, 5} and {6} were 2 and 0 units wide respectively. The new clusters {1} and {5, 6} are 0 and 0.5 units wide respectively. So the summed widths reduced. That is, the overall clustering got tighter.
Finally, for completeness, let’s note that after the clusters have been initialized (before the iterations begin) their means need to be computed. This extra step is needed since step 1 of an iteration uses the means.
K-medians Clustering
Consider the 1D data 1, 100, 102, 200 and say K = 2. What should be the two clusters? Either {{1, 100, 102}, {200}} or {{1}, {100,102, 200}}. In the first case 1 is an outlier; in the second case 200. The mean of a cluster with an outlier is skewed towards the outlier.
In the presence of outliers, a sensible variant of K-means clustering involves just replacing ‘mean’ with ‘median’. Nothing else changes.
Consider {1, 100, 102}. The mean is 67.66 whereas the median is 100. This is graphically depicted below.
Soft K-means Clustering: The EM algorithm
K-means clustering is a special case of a powerful statistical algorithm called EM. We will describe EM in the context of K-means clustering, calling it EMC. For contrast, we will denote k-means clustering as KMC.
EMC models a cluster as a probability distribution over the data space. Think of this as specifying a cluster by a soft membership function.
Take our trees example. Imagine that we are okay with elliptical forests (of which circular ones are special cases). We might model such a cluster as a two-dimensional Gaussian whose mean models the cluster’s center. Its covariance matrix captures the parameters that describe the shape of the ellipse (the major and minor axes and the tilt).
Before going further, let’s note that when we say elliptical clusters, this is just an approximation for visual insights. A cluster doesn’t have a hard boundary. Much like a mountain doesn’t have a hard boundary separating it from the plains. Nonetheless, as with a mountain, the imagined boundary is useful.
As in K-means clustering, the number of clusters is fixed in advance.
The next key concept is the probability model that describes the process of generating clusters. We call such a model a generative one.
The EMC generative model is a mixture whose components are the K individual cluster models. This mixture is parametrized by a distribution of mixing probabilities over the K clusters.
The generation process works as follows. We repeat the following independently as long as we like.
Randomly sample a cluster, call it c, from C.Randomly sample a data point, call it x, from c’s distribution.
Randomly sample a cluster, call it c, from C.
Randomly sample a data point, call it x, from c’s distribution.
This results in a set of data points labeled with their cluster ids.
During the clustering process, the cluster ids of the data points are of course not known. The job of EMC is to find them.
In more detail, and a bit more generally, EMC’s aim is to learn the parameters of the various cluster models, together with the mixing probabilities, from the data. (We say “more generally” because this way we can also cluster new data that the algorithm hasn’t seen yet.)
The EMC algorithm’s steps
Just like K-means clustering, EMC works iteratively to improve the clustering. In fact, each iteration has the same two steps.
The two steps in an EMC iteration are more advanced versions of the corresponding steps in KMC. We’ll start by reviewing the KMC versions, then morph them into EMC ones. During the process, new ideas will emerge.
The first KMP step was to reassign the data points to the nearest clusters. The two words to focus on here are ‘reassign’ and ‘nearest’. Let’s look at ‘reassign’ first. As it turns out, first we have to abstract out a bit, to the word ‘assign’.
Cluster Assignments
In KMC, the cluster assigned to a data point at any given time is unique. In EMC, a data point’s membership is modeled as a probability distribution over the various clusters. Thus the datum potentially belongs to multiple clusters, to a varying degree. This is graphically depicted below.
The KMC version is a special case in which the distribution’s mass is concentrated on one cluster.
How do we compute this probability distribution at any point in time? Actually, we could do it even for the KMC. Whereas the EMC’s version will be more accurate, let’s start by describing one from the KMC as it is simpler and we are on familiar ground.
Consider a datum x. We can compute the distance of x to every cluster. Next, we turn distances into membership scores which we call cluster affinities. One way to do this is to define data point x’s affinity for a cluster c at distance d from x to be 1/(d+p). Here p is a tiny positive number to avoid divide-by-zero. Next, we sum up these affinities. Finally, we divide each affinity by this sum. This gives us the soft cluster memberships of x as a probability distribution.
What we described above is fine for illustrative purposes but probably not effective enough for actual use. Simply put, cluster affinities can get overly diluted. That is, a single data point may belong to way too many clusters. Such diffusion can get in the way of trying to find a good clustering.
This issue can be mitigated by using softmax instead. This involves surgery on only the step in going from distance to affinity. Specifically, the affinity of distance d is defined as e^-d. Thus affinity drops exponentially with distance. Now we normalize as before.
Using the softmax this way produces a k-means like behavior. Simply put softmax is a better approximation to max than the function that came before it.
Bayesian Cluster Assignments
Whereas the softmax approach described above can be effective in practice, a more elaborate approach is below. Let c denote a cluster and x a data point. By Bayes rule,
P(c|x) = P(x|c)*P(c)/sum_c’ P(x|c’)*P(c’)
At any given point in time, we have an estimate of P(c). At any given point in time, we can also estimate P(x|c) as cluster c’s current probability model is fully specified. If, as in our trees example, a cluster’s model was a two-dimensional Gaussian, fully specified just means that the cluster’s mean and covariance matrices have specific values.
Completing The First Step’s Description
So we have all the information to compute P(c|x). Note that this approach takes into account the cluster sizes as well. (Think of P(c) as proportional to c’s size.) So if two clusters were equally near a data point, the data point would favor the larger cluster.
The Second Step
The second step in KMC was to recompute the cluster means. In EMC, this generalizes to “reestimate the model parameters”. These include the parameters of the various cluster models as well as the mixing probabilities of the mixture model.
We’ll illustrate this step for the case in which the cluster models are two-dimensional Gaussians. This will immediately apply to our trees example.
Let’s start with reestimating a cluster’s mean. In KMC, this was just the mean of the data points in the cluster. In EMC, a data point can be in multiple clusters to a varying degree so this needs some generalization.
Fortunately, the generalization is intuitively easy to describe. In EMC a data point x contributes to the mean of cluster c with weight proportional to P(c|x). In more detail,
mean(c) = sum_x P(c|x)*x/ sum_x P(c|x)
Let’s illustrate this in the KMC special case. P(c|x) is 1 for c’s members and 0 for the rest. So mean(c) = sum_{x in c} x/sum_{x in c} 1 = sum_{x in c} x/cluster size(c) which is exactly what we had.
In summary, in KMC a data point contributes to the mean of its unique cluster. In EMC a data point contributes to the means of potentially multiple clusters, with strengths based on the involved cluster affinities.
The covariance matrix of a cluster may be estimated similarly, albeit the details are more involved.
The mixing probabilities are reestimated as follows.
P(c) = sum_x P(c|x)/sum_{x, c’} P(c’|x)
Think of P(c) as the sum of the weighted votes it receives divided by the sum of the weighted votes all clusters receive.
Example: A Mixture Of Two Gaussians
EMC is a complex algorithm. An example will help.
We will operate on a single dimension and set K = 2. We will model each cluster as a Gaussian.
The situation is graphically depicted below.
For numerical calculations let’s restrict the situation further. Let’s consider the same 3 data points 1, 5, and 6 and the same initial clusters {1, 5} and {6}. In EMC, we also need to initialize the model parameters. Let’s just estimate them from the initial clusters.
Let’s set the cluster posterior probabilities from the initial clustering. That is, as, in KMC, a datum determines its cluster uniquely. Next, we compute the cluster means to be 3 and 6 respectively. The cluster standard deviations are 2 and 0 respectively.
The second cluster’s standard deviation of 0 poses a slight problem. The resulting Gaussian is degenerate. We can’t use it.
We’ll patch this situation as follows. We will add n copies of 1, 5, and 6, where n >> 1. To these, we will add a few points sampled randomly from a Gaussian whose mean and standard deviation are the corresponding statistics of the sample 1, 5, and 6.
Now we will initialize the clusters from this expanded data. The reason for n >> 1 is because we want 1, 5, and 6 to remain the dominant numbers.
This may be interpreted as a Bayesian approach in which we have incorporated a prior that the standard deviations of all clusters must be positive. While we are at it, let’s tack on another sensible prior: that neither cluster is empty, i.e. its mixing probability is 0.
For illustration purposes let’s wish away the synthetic data we added. We will bring it in whenever it is relevant. That is, let’s start as before, with three points 1, 5, and 6, and the initial clustering {1, 5} and {6}.
We get the cluster means to be approximately 3 and 6 respectively. (This is because the synthetic data has some effect.) The cluster standard deviations are approximately 2 and positive respectively.
Next, we update the posterior probabilities of the two clusters. For visual convenience, we’ll use the distance versions of the update formulae.
The before and after depictions below will help illustrate the update process. First, let’s depict the data points.
x 1 5 6
Next, let’s see the probabilities of cluster 1 before the update. (P(2|x) is 1-P(1|x).)
x 1 5 6P(1|x) 1 1 0
Next, let’s see the updated probabilities of cluster 1 based on their distances.
x 1 5 6P(1|x) ~1 ~0 0
The bold-faced one changed the most. Effectively we softly moved data point 5 from cluster 1 to cluster 2.
Now each data point’s cluster probabilities are concentrated on one cluster. Plus nearby points (5 and 6) have high posteriors for the same cluster. So the clustering is in a happy state.
Summary
In this post, we described a well-known and classical algorithm for clustering known as K-means clustering. We also covered an advanced variant called soft k-means clustering and a robust variant that uses median instead of mean.
|
[
{
"code": null,
"e": 319,
"s": 171,
"text": "The clustering problem is to group a set of data points into clusters. Clusters should be internally tight. Clusters should also be well-separated."
},
{
"code": null,
"e": 533,
"s": 319,
"text": "Here is an example. Consider a geospatial map in which each pixel is green or yellow. A green pixel denotes a tree at that location. A yellow pixel denotes its absence. We’d like to cluster the trees into forests."
},
{
"code": null,
"e": 817,
"s": 533,
"text": "This is a representative example of a large class of clustering problems on geospatial data, at varying scales. For example, if we replace “green denoting a tree” with “red denoting a lit location”, we might hope to discover clusters of well-lit areas such as towns or neighborhoods."
},
{
"code": null,
"e": 896,
"s": 817,
"text": "In this post, we will cover the K-means clustering algorithm and its variants."
},
{
"code": null,
"e": 1093,
"s": 896,
"text": "The K-means clustering algorithm requires fixing K, the number of clusters, in advance. This may seem like a serious limitation. In our example, how would we know the number of forests in advance?"
},
{
"code": null,
"e": 1266,
"s": 1093,
"text": "That said, we can imagine some user interface that lets the user try out different values of K and see what forests get found? This interactive process might yet be useful."
},
{
"code": null,
"e": 1280,
"s": 1266,
"text": "The Algorithm"
},
{
"code": null,
"e": 1465,
"s": 1280,
"text": "The K-means clustering algorithm works as follows. We are given the data set to be clustered, and a value of K. In our example, the data set would be the locations of the green pixels."
},
{
"code": null,
"e": 1680,
"s": 1465,
"text": "The algorithm initializes the K clusters (somehow). It then iteratively adjusts the clusters so long as they keep improving. We can stop the algorithm at any time. Or when the clusters stop changing (sufficiently)."
},
{
"code": null,
"e": 1941,
"s": 1680,
"text": "How do we measure “clusters improving”? Let’s begin by noting that in K-means clustering clusters are represented by their means. (This explains the word “means” in the algorithm’s name.) In our trees example, a cluster’s mean is the associate forest’s center."
},
{
"code": null,
"e": 2226,
"s": 1941,
"text": "Next, we need the notion of how tight a cluster is. We will define a cluster’s width as the average distance of the cluster’s members from its mean. In our trees example, this is the average distance of a tree in a forest from the forest’s center. A rough proxy for the forest’s area."
},
{
"code": null,
"e": 2350,
"s": 2226,
"text": "A global measure of the tightness of the full set of clusters may then be defined as the sum of the widths of the clusters."
},
{
"code": null,
"e": 2621,
"s": 2350,
"text": "Next, let’s look at what happens inside an iteration. The algorithm tries to improve the current clustering. In two steps. First, it reassigns each data point to the cluster whose mean is closest to it. Next, it recomputes the cluster means from the updated assignments."
},
{
"code": null,
"e": 3015,
"s": 2621,
"text": "The intuition that an iteration (in which an assignment changes) improves the clustering is as follows. (This is not proof — just intuition!) In the first step, at least one data point got reassigned to a cluster whose center it is nearer to. This tends to reduce the width of one or both affected clusters. The second step, which recomputes the cluster means, often reduces the width further."
},
{
"code": null,
"e": 3023,
"s": 3015,
"text": "Example"
},
{
"code": null,
"e": 3373,
"s": 3023,
"text": "Let’s illustrate this in the example below in which both effects come into play. We have 3 1D points to be clustered: 1, 5, and 6. Say the current clusters are {1, 5} and {6}. Their means are 3 and 6 respectively. In the next iteration 5 moves to the second cluster. This results in the clustering {1} and {5, 6} having means 1 and 5.5 respectively."
},
{
"code": null,
"e": 3403,
"s": 3373,
"text": "This shift is depicted below."
},
{
"code": null,
"e": 3429,
"s": 3403,
"text": "{1, 5}, {6} → {1}, {5, 6}"
},
{
"code": null,
"e": 3692,
"s": 3429,
"text": "Let’s see how the cluster widths changed. The original clusters {1, 5} and {6} were 2 and 0 units wide respectively. The new clusters {1} and {5, 6} are 0 and 0.5 units wide respectively. So the summed widths reduced. That is, the overall clustering got tighter."
},
{
"code": null,
"e": 3910,
"s": 3692,
"text": "Finally, for completeness, let’s note that after the clusters have been initialized (before the iterations begin) their means need to be computed. This extra step is needed since step 1 of an iteration uses the means."
},
{
"code": null,
"e": 3931,
"s": 3910,
"text": "K-medians Clustering"
},
{
"code": null,
"e": 4201,
"s": 3931,
"text": "Consider the 1D data 1, 100, 102, 200 and say K = 2. What should be the two clusters? Either {{1, 100, 102}, {200}} or {{1}, {100,102, 200}}. In the first case 1 is an outlier; in the second case 200. The mean of a cluster with an outlier is skewed towards the outlier."
},
{
"code": null,
"e": 4339,
"s": 4201,
"text": "In the presence of outliers, a sensible variant of K-means clustering involves just replacing ‘mean’ with ‘median’. Nothing else changes."
},
{
"code": null,
"e": 4444,
"s": 4339,
"text": "Consider {1, 100, 102}. The mean is 67.66 whereas the median is 100. This is graphically depicted below."
},
{
"code": null,
"e": 4486,
"s": 4444,
"text": "Soft K-means Clustering: The EM algorithm"
},
{
"code": null,
"e": 4700,
"s": 4486,
"text": "K-means clustering is a special case of a powerful statistical algorithm called EM. We will describe EM in the context of K-means clustering, calling it EMC. For contrast, we will denote k-means clustering as KMC."
},
{
"code": null,
"e": 4841,
"s": 4700,
"text": "EMC models a cluster as a probability distribution over the data space. Think of this as specifying a cluster by a soft membership function."
},
{
"code": null,
"e": 5184,
"s": 4841,
"text": "Take our trees example. Imagine that we are okay with elliptical forests (of which circular ones are special cases). We might model such a cluster as a two-dimensional Gaussian whose mean models the cluster’s center. Its covariance matrix captures the parameters that describe the shape of the ellipse (the major and minor axes and the tilt)."
},
{
"code": null,
"e": 5493,
"s": 5184,
"text": "Before going further, let’s note that when we say elliptical clusters, this is just an approximation for visual insights. A cluster doesn’t have a hard boundary. Much like a mountain doesn’t have a hard boundary separating it from the plains. Nonetheless, as with a mountain, the imagined boundary is useful."
},
{
"code": null,
"e": 5563,
"s": 5493,
"text": "As in K-means clustering, the number of clusters is fixed in advance."
},
{
"code": null,
"e": 5699,
"s": 5563,
"text": "The next key concept is the probability model that describes the process of generating clusters. We call such a model a generative one."
},
{
"code": null,
"e": 5883,
"s": 5699,
"text": "The EMC generative model is a mixture whose components are the K individual cluster models. This mixture is parametrized by a distribution of mixing probabilities over the K clusters."
},
{
"code": null,
"e": 5982,
"s": 5883,
"text": "The generation process works as follows. We repeat the following independently as long as we like."
},
{
"code": null,
"e": 6091,
"s": 5982,
"text": "Randomly sample a cluster, call it c, from C.Randomly sample a data point, call it x, from c’s distribution."
},
{
"code": null,
"e": 6137,
"s": 6091,
"text": "Randomly sample a cluster, call it c, from C."
},
{
"code": null,
"e": 6201,
"s": 6137,
"text": "Randomly sample a data point, call it x, from c’s distribution."
},
{
"code": null,
"e": 6270,
"s": 6201,
"text": "This results in a set of data points labeled with their cluster ids."
},
{
"code": null,
"e": 6393,
"s": 6270,
"text": "During the clustering process, the cluster ids of the data points are of course not known. The job of EMC is to find them."
},
{
"code": null,
"e": 6666,
"s": 6393,
"text": "In more detail, and a bit more generally, EMC’s aim is to learn the parameters of the various cluster models, together with the mixing probabilities, from the data. (We say “more generally” because this way we can also cluster new data that the algorithm hasn’t seen yet.)"
},
{
"code": null,
"e": 6692,
"s": 6666,
"text": "The EMC algorithm’s steps"
},
{
"code": null,
"e": 6819,
"s": 6692,
"text": "Just like K-means clustering, EMC works iteratively to improve the clustering. In fact, each iteration has the same two steps."
},
{
"code": null,
"e": 7032,
"s": 6819,
"text": "The two steps in an EMC iteration are more advanced versions of the corresponding steps in KMC. We’ll start by reviewing the KMC versions, then morph them into EMC ones. During the process, new ideas will emerge."
},
{
"code": null,
"e": 7277,
"s": 7032,
"text": "The first KMP step was to reassign the data points to the nearest clusters. The two words to focus on here are ‘reassign’ and ‘nearest’. Let’s look at ‘reassign’ first. As it turns out, first we have to abstract out a bit, to the word ‘assign’."
},
{
"code": null,
"e": 7297,
"s": 7277,
"text": "Cluster Assignments"
},
{
"code": null,
"e": 7587,
"s": 7297,
"text": "In KMC, the cluster assigned to a data point at any given time is unique. In EMC, a data point’s membership is modeled as a probability distribution over the various clusters. Thus the datum potentially belongs to multiple clusters, to a varying degree. This is graphically depicted below."
},
{
"code": null,
"e": 7686,
"s": 7587,
"text": "The KMC version is a special case in which the distribution’s mass is concentrated on one cluster."
},
{
"code": null,
"e": 7939,
"s": 7686,
"text": "How do we compute this probability distribution at any point in time? Actually, we could do it even for the KMC. Whereas the EMC’s version will be more accurate, let’s start by describing one from the KMC as it is simpler and we are on familiar ground."
},
{
"code": null,
"e": 8416,
"s": 7939,
"text": "Consider a datum x. We can compute the distance of x to every cluster. Next, we turn distances into membership scores which we call cluster affinities. One way to do this is to define data point x’s affinity for a cluster c at distance d from x to be 1/(d+p). Here p is a tiny positive number to avoid divide-by-zero. Next, we sum up these affinities. Finally, we divide each affinity by this sum. This gives us the soft cluster memberships of x as a probability distribution."
},
{
"code": null,
"e": 8716,
"s": 8416,
"text": "What we described above is fine for illustrative purposes but probably not effective enough for actual use. Simply put, cluster affinities can get overly diluted. That is, a single data point may belong to way too many clusters. Such diffusion can get in the way of trying to find a good clustering."
},
{
"code": null,
"e": 8983,
"s": 8716,
"text": "This issue can be mitigated by using softmax instead. This involves surgery on only the step in going from distance to affinity. Specifically, the affinity of distance d is defined as e^-d. Thus affinity drops exponentially with distance. Now we normalize as before."
},
{
"code": null,
"e": 9135,
"s": 8983,
"text": "Using the softmax this way produces a k-means like behavior. Simply put softmax is a better approximation to max than the function that came before it."
},
{
"code": null,
"e": 9164,
"s": 9135,
"text": "Bayesian Cluster Assignments"
},
{
"code": null,
"e": 9333,
"s": 9164,
"text": "Whereas the softmax approach described above can be effective in practice, a more elaborate approach is below. Let c denote a cluster and x a data point. By Bayes rule,"
},
{
"code": null,
"e": 9375,
"s": 9333,
"text": "P(c|x) = P(x|c)*P(c)/sum_c’ P(x|c’)*P(c’)"
},
{
"code": null,
"e": 9725,
"s": 9375,
"text": "At any given point in time, we have an estimate of P(c). At any given point in time, we can also estimate P(x|c) as cluster c’s current probability model is fully specified. If, as in our trees example, a cluster’s model was a two-dimensional Gaussian, fully specified just means that the cluster’s mean and covariance matrices have specific values."
},
{
"code": null,
"e": 9765,
"s": 9725,
"text": "Completing The First Step’s Description"
},
{
"code": null,
"e": 10028,
"s": 9765,
"text": "So we have all the information to compute P(c|x). Note that this approach takes into account the cluster sizes as well. (Think of P(c) as proportional to c’s size.) So if two clusters were equally near a data point, the data point would favor the larger cluster."
},
{
"code": null,
"e": 10044,
"s": 10028,
"text": "The Second Step"
},
{
"code": null,
"e": 10283,
"s": 10044,
"text": "The second step in KMC was to recompute the cluster means. In EMC, this generalizes to “reestimate the model parameters”. These include the parameters of the various cluster models as well as the mixing probabilities of the mixture model."
},
{
"code": null,
"e": 10432,
"s": 10283,
"text": "We’ll illustrate this step for the case in which the cluster models are two-dimensional Gaussians. This will immediately apply to our trees example."
},
{
"code": null,
"e": 10650,
"s": 10432,
"text": "Let’s start with reestimating a cluster’s mean. In KMC, this was just the mean of the data points in the cluster. In EMC, a data point can be in multiple clusters to a varying degree so this needs some generalization."
},
{
"code": null,
"e": 10826,
"s": 10650,
"text": "Fortunately, the generalization is intuitively easy to describe. In EMC a data point x contributes to the mean of cluster c with weight proportional to P(c|x). In more detail,"
},
{
"code": null,
"e": 10865,
"s": 10826,
"text": "mean(c) = sum_x P(c|x)*x/ sum_x P(c|x)"
},
{
"code": null,
"e": 11066,
"s": 10865,
"text": "Let’s illustrate this in the KMC special case. P(c|x) is 1 for c’s members and 0 for the rest. So mean(c) = sum_{x in c} x/sum_{x in c} 1 = sum_{x in c} x/cluster size(c) which is exactly what we had."
},
{
"code": null,
"e": 11281,
"s": 11066,
"text": "In summary, in KMC a data point contributes to the mean of its unique cluster. In EMC a data point contributes to the means of potentially multiple clusters, with strengths based on the involved cluster affinities."
},
{
"code": null,
"e": 11382,
"s": 11281,
"text": "The covariance matrix of a cluster may be estimated similarly, albeit the details are more involved."
},
{
"code": null,
"e": 11435,
"s": 11382,
"text": "The mixing probabilities are reestimated as follows."
},
{
"code": null,
"e": 11475,
"s": 11435,
"text": "P(c) = sum_x P(c|x)/sum_{x, c’} P(c’|x)"
},
{
"code": null,
"e": 11597,
"s": 11475,
"text": "Think of P(c) as the sum of the weighted votes it receives divided by the sum of the weighted votes all clusters receive."
},
{
"code": null,
"e": 11633,
"s": 11597,
"text": "Example: A Mixture Of Two Gaussians"
},
{
"code": null,
"e": 11683,
"s": 11633,
"text": "EMC is a complex algorithm. An example will help."
},
{
"code": null,
"e": 11778,
"s": 11683,
"text": "We will operate on a single dimension and set K = 2. We will model each cluster as a Gaussian."
},
{
"code": null,
"e": 11823,
"s": 11778,
"text": "The situation is graphically depicted below."
},
{
"code": null,
"e": 12093,
"s": 11823,
"text": "For numerical calculations let’s restrict the situation further. Let’s consider the same 3 data points 1, 5, and 6 and the same initial clusters {1, 5} and {6}. In EMC, we also need to initialize the model parameters. Let’s just estimate them from the initial clusters."
},
{
"code": null,
"e": 12351,
"s": 12093,
"text": "Let’s set the cluster posterior probabilities from the initial clustering. That is, as, in KMC, a datum determines its cluster uniquely. Next, we compute the cluster means to be 3 and 6 respectively. The cluster standard deviations are 2 and 0 respectively."
},
{
"code": null,
"e": 12475,
"s": 12351,
"text": "The second cluster’s standard deviation of 0 poses a slight problem. The resulting Gaussian is degenerate. We can’t use it."
},
{
"code": null,
"e": 12727,
"s": 12475,
"text": "We’ll patch this situation as follows. We will add n copies of 1, 5, and 6, where n >> 1. To these, we will add a few points sampled randomly from a Gaussian whose mean and standard deviation are the corresponding statistics of the sample 1, 5, and 6."
},
{
"code": null,
"e": 12873,
"s": 12727,
"text": "Now we will initialize the clusters from this expanded data. The reason for n >> 1 is because we want 1, 5, and 6 to remain the dominant numbers."
},
{
"code": null,
"e": 13144,
"s": 12873,
"text": "This may be interpreted as a Bayesian approach in which we have incorporated a prior that the standard deviations of all clusters must be positive. While we are at it, let’s tack on another sensible prior: that neither cluster is empty, i.e. its mixing probability is 0."
},
{
"code": null,
"e": 13366,
"s": 13144,
"text": "For illustration purposes let’s wish away the synthetic data we added. We will bring it in whenever it is relevant. That is, let’s start as before, with three points 1, 5, and 6, and the initial clustering {1, 5} and {6}."
},
{
"code": null,
"e": 13566,
"s": 13366,
"text": "We get the cluster means to be approximately 3 and 6 respectively. (This is because the synthetic data has some effect.) The cluster standard deviations are approximately 2 and positive respectively."
},
{
"code": null,
"e": 13711,
"s": 13566,
"text": "Next, we update the posterior probabilities of the two clusters. For visual convenience, we’ll use the distance versions of the update formulae."
},
{
"code": null,
"e": 13827,
"s": 13711,
"text": "The before and after depictions below will help illustrate the update process. First, let’s depict the data points."
},
{
"code": null,
"e": 13845,
"s": 13827,
"text": "x 1 5 6"
},
{
"code": null,
"e": 13933,
"s": 13845,
"text": "Next, let’s see the probabilities of cluster 1 before the update. (P(2|x) is 1-P(1|x).)"
},
{
"code": null,
"e": 13980,
"s": 13933,
"text": "x 1 5 6P(1|x) 1 1 0"
},
{
"code": null,
"e": 14061,
"s": 13980,
"text": "Next, let’s see the updated probabilities of cluster 1 based on their distances."
},
{
"code": null,
"e": 14108,
"s": 14061,
"text": "x 1 5 6P(1|x) ~1 ~0 0"
},
{
"code": null,
"e": 14215,
"s": 14108,
"text": "The bold-faced one changed the most. Effectively we softly moved data point 5 from cluster 1 to cluster 2."
},
{
"code": null,
"e": 14403,
"s": 14215,
"text": "Now each data point’s cluster probabilities are concentrated on one cluster. Plus nearby points (5 and 6) have high posteriors for the same cluster. So the clustering is in a happy state."
},
{
"code": null,
"e": 14411,
"s": 14403,
"text": "Summary"
}
] |
Program for Fahrenheit to Celsius conversion - GeeksforGeeks
|
07 Mar, 2022
Given a Temperature n in Fahrenheit scale convert it into Celsius scale .Examples:
Input : 32
Output : 0
Input :- 40
Output : -40
Formula for converting Fahrenheit scale to Celsius scale
T(°C) = (T(°F) - 32) × 5/9
C
C++
Java
Python3
C#
PHP
Javascript
/* Program in C to convert Degree Farenheit to Degree Celsuis */#include <stdio.h> //function to convert Degree Farenheit to Degree Celsuisfloat farenheit_to_celsius(float f){ return ((f - 32.0) * 5.0 / 9.0);} int main(){ float f = 40; // passing parameter to function printf("Temperature in Degree Celsius : %0.2f",farenheit_to_celsius(f)); return 0;}
// CPP program to convert Fahrenheit// scale to Celsius scale#include <bits/stdc++.h>using namespace std; // function to convert// Fahrenheit to Celsiusfloat Conversion(float n){ return (n - 32.0) * 5.0 / 9.0;} // driver codeint main(){ float n = 40; cout << Conversion(n); return 0;}
// Java program to convert Fahrenheit// scale to Celsius scaleclass GFG { // function to convert// Fahrenheit to Celsiusstatic float Conversion(float n){ return (n - 32.0f) * 5.0f / 9.0f;} // Driver codepublic static void main(String[] args) { float n = 40; System.out.println(Conversion(n));}} // This code is contributed by Anant Agarwal.
# Python3 program to convert Fahrenheit# scale to Celsius scale # function to convert# Fahrenheit to Celsiusdef Conversion(n): return(n - 32.0) * 5.0 / 9.0 # driver coden = 40x = Conversion(n)print (x) # This article is contributed by Himanshu Ranjan
// c# program to convert Fahrenheit// scale to Celsius scaleusing System; class GFG { // function to convert// Fahrenheit to Celsiusstatic float Conversion(float n){ return (n - 32.0f) * 5.0f / 9.0f;} // Driver codepublic static void Main(){ float n = 40; Console.Write(Conversion(n));}} // This code is contributed by Nitin Mittal.
<?php// PHP program to convert Fahrenheit// scale to Celsius scale // function to convert// Fahrenheit to Celsiusfunction Conversion($n){ return ($n - 32.0) * 5.0 / 9.0;} // Driver Code $n = 40; echo Conversion($n); // This code is contributed by nitin mittal?>
<script> // Javascript program to convert Fahrenheit// scale to Celsius scale // function to convert// Fahrenheit to Celsiusfunction Conversion(n){ return (n - 32.0) * 5.0 / 9.0;} // driver code let n = 40; document.write(Conversion(n)); // This code is contributed Mayank Tyagi </script>
Output:
4.44444
This article is contributed by Dibyendu Roy Chaudhuri. 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.
nitin mittal
mayanktyagi1709
sonawanejaydeep11
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
C++ Classes and Objects
Operator Overloading in C++
Constructors in C++
Copy Constructor in C++
Overriding in Java
Polymorphism in C++
C++ Data Types
Constructors in Java
Different ways of Reading a text file in Java
|
[
{
"code": null,
"e": 24310,
"s": 24282,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 24395,
"s": 24310,
"text": "Given a Temperature n in Fahrenheit scale convert it into Celsius scale .Examples: "
},
{
"code": null,
"e": 24443,
"s": 24395,
"text": "Input : 32\nOutput : 0\n\nInput :- 40\nOutput : -40"
},
{
"code": null,
"e": 24504,
"s": 24445,
"text": "Formula for converting Fahrenheit scale to Celsius scale "
},
{
"code": null,
"e": 24531,
"s": 24504,
"text": "T(°C) = (T(°F) - 32) × 5/9"
},
{
"code": null,
"e": 24535,
"s": 24533,
"text": "C"
},
{
"code": null,
"e": 24539,
"s": 24535,
"text": "C++"
},
{
"code": null,
"e": 24544,
"s": 24539,
"text": "Java"
},
{
"code": null,
"e": 24552,
"s": 24544,
"text": "Python3"
},
{
"code": null,
"e": 24555,
"s": 24552,
"text": "C#"
},
{
"code": null,
"e": 24559,
"s": 24555,
"text": "PHP"
},
{
"code": null,
"e": 24570,
"s": 24559,
"text": "Javascript"
},
{
"code": "/* Program in C to convert Degree Farenheit to Degree Celsuis */#include <stdio.h> //function to convert Degree Farenheit to Degree Celsuisfloat farenheit_to_celsius(float f){ return ((f - 32.0) * 5.0 / 9.0);} int main(){ float f = 40; // passing parameter to function printf(\"Temperature in Degree Celsius : %0.2f\",farenheit_to_celsius(f)); return 0;}",
"e": 24930,
"s": 24570,
"text": null
},
{
"code": "// CPP program to convert Fahrenheit// scale to Celsius scale#include <bits/stdc++.h>using namespace std; // function to convert// Fahrenheit to Celsiusfloat Conversion(float n){ return (n - 32.0) * 5.0 / 9.0;} // driver codeint main(){ float n = 40; cout << Conversion(n); return 0;}",
"e": 25228,
"s": 24930,
"text": null
},
{
"code": "// Java program to convert Fahrenheit// scale to Celsius scaleclass GFG { // function to convert// Fahrenheit to Celsiusstatic float Conversion(float n){ return (n - 32.0f) * 5.0f / 9.0f;} // Driver codepublic static void main(String[] args) { float n = 40; System.out.println(Conversion(n));}} // This code is contributed by Anant Agarwal.",
"e": 25582,
"s": 25228,
"text": null
},
{
"code": "# Python3 program to convert Fahrenheit# scale to Celsius scale # function to convert# Fahrenheit to Celsiusdef Conversion(n): return(n - 32.0) * 5.0 / 9.0 # driver coden = 40x = Conversion(n)print (x) # This article is contributed by Himanshu Ranjan",
"e": 25836,
"s": 25582,
"text": null
},
{
"code": "// c# program to convert Fahrenheit// scale to Celsius scaleusing System; class GFG { // function to convert// Fahrenheit to Celsiusstatic float Conversion(float n){ return (n - 32.0f) * 5.0f / 9.0f;} // Driver codepublic static void Main(){ float n = 40; Console.Write(Conversion(n));}} // This code is contributed by Nitin Mittal.",
"e": 26182,
"s": 25836,
"text": null
},
{
"code": "<?php// PHP program to convert Fahrenheit// scale to Celsius scale // function to convert// Fahrenheit to Celsiusfunction Conversion($n){ return ($n - 32.0) * 5.0 / 9.0;} // Driver Code $n = 40; echo Conversion($n); // This code is contributed by nitin mittal?>",
"e": 26461,
"s": 26182,
"text": null
},
{
"code": "<script> // Javascript program to convert Fahrenheit// scale to Celsius scale // function to convert// Fahrenheit to Celsiusfunction Conversion(n){ return (n - 32.0) * 5.0 / 9.0;} // driver code let n = 40; document.write(Conversion(n)); // This code is contributed Mayank Tyagi </script>",
"e": 26760,
"s": 26461,
"text": null
},
{
"code": null,
"e": 26769,
"s": 26760,
"text": "Output: "
},
{
"code": null,
"e": 26777,
"s": 26769,
"text": "4.44444"
},
{
"code": null,
"e": 27208,
"s": 26777,
"text": "This article is contributed by Dibyendu Roy Chaudhuri. 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": 27221,
"s": 27208,
"text": "nitin mittal"
},
{
"code": null,
"e": 27237,
"s": 27221,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 27255,
"s": 27237,
"text": "sonawanejaydeep11"
},
{
"code": null,
"e": 27274,
"s": 27255,
"text": "School Programming"
},
{
"code": null,
"e": 27372,
"s": 27274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27391,
"s": 27372,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27415,
"s": 27391,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27443,
"s": 27415,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27463,
"s": 27443,
"text": "Constructors in C++"
},
{
"code": null,
"e": 27487,
"s": 27463,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 27506,
"s": 27487,
"text": "Overriding in Java"
},
{
"code": null,
"e": 27526,
"s": 27506,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 27541,
"s": 27526,
"text": "C++ Data Types"
},
{
"code": null,
"e": 27562,
"s": 27541,
"text": "Constructors in Java"
}
] |
\widetilde - Tex Command
|
\widetilde - Used to create widetilde symbol.
{ \widetilde}
\widetilde command draws widetilde symbol.
\widetilde a
a~
\widetilde A
A~
\widetilde AB
A~B
\widetilde{AB}
AB~
\widetilde a
a~
\widetilde a
\widetilde A
A~
\widetilde A
\widetilde AB
A~B
\widetilde AB
\widetilde{AB}
AB~
\widetilde{AB}
14 Lectures
52 mins
Ashraf Said
11 Lectures
1 hours
Ashraf Said
9 Lectures
1 hours
Emenwa Global, Ejike IfeanyiChukwu
29 Lectures
2.5 hours
Mohammad Nauman
14 Lectures
1 hours
Daniel Stern
15 Lectures
47 mins
Nishant Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 8032,
"s": 7986,
"text": "\\widetilde - Used to create widetilde symbol."
},
{
"code": null,
"e": 8046,
"s": 8032,
"text": "{ \\widetilde}"
},
{
"code": null,
"e": 8089,
"s": 8046,
"text": "\\widetilde command draws widetilde symbol."
},
{
"code": null,
"e": 8172,
"s": 8089,
"text": "\n\\widetilde a\n\na~\n\n\n\\widetilde A\n\nA~\n\n\n\\widetilde AB\n\nA~B\n\n\n\\widetilde{AB}\n\nAB~\n\n\n"
},
{
"code": null,
"e": 8191,
"s": 8172,
"text": "\\widetilde a\n\na~\n\n"
},
{
"code": null,
"e": 8204,
"s": 8191,
"text": "\\widetilde a"
},
{
"code": null,
"e": 8223,
"s": 8204,
"text": "\\widetilde A\n\nA~\n\n"
},
{
"code": null,
"e": 8236,
"s": 8223,
"text": "\\widetilde A"
},
{
"code": null,
"e": 8257,
"s": 8236,
"text": "\\widetilde AB\n\nA~B\n\n"
},
{
"code": null,
"e": 8271,
"s": 8257,
"text": "\\widetilde AB"
},
{
"code": null,
"e": 8293,
"s": 8271,
"text": "\\widetilde{AB}\n\nAB~\n\n"
},
{
"code": null,
"e": 8308,
"s": 8293,
"text": "\\widetilde{AB}"
},
{
"code": null,
"e": 8340,
"s": 8308,
"text": "\n 14 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 8353,
"s": 8340,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8386,
"s": 8353,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8399,
"s": 8386,
"text": " Ashraf Said"
},
{
"code": null,
"e": 8431,
"s": 8399,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8467,
"s": 8431,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8502,
"s": 8467,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 8519,
"s": 8502,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 8552,
"s": 8519,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8566,
"s": 8552,
"text": " Daniel Stern"
},
{
"code": null,
"e": 8598,
"s": 8566,
"text": "\n 15 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 8613,
"s": 8598,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 8620,
"s": 8613,
"text": " Print"
},
{
"code": null,
"e": 8631,
"s": 8620,
"text": " Add Notes"
}
] |
JavaFX | Circle with examples - GeeksforGeeks
|
25 Oct, 2019
Circle class is a part of the JavaFX library. Circle class creates a circle with a specified x and y position for the center of the circle, the specified radius for the circle and a specified fill.The radius and the center of the circles are measured in pixels.
Constructors of the class are:
Circle(): creates a empty instance of circleCircle(double r): creates a circle with a specified radiusCircle(double X, double Y, double r): creates a circle with given X and y coordinates of the center of the circle, and the radius.Circle(double r, paint f) creates a circle with a specified radius and fillCircle(double X, double Y, double r, Paint f): creates a circle with given X and y coordinates of the center of the circle, and the radius and also a specified fill .
Circle(): creates a empty instance of circle
Circle(double r): creates a circle with a specified radius
Circle(double X, double Y, double r): creates a circle with given X and y coordinates of the center of the circle, and the radius.
Circle(double r, paint f) creates a circle with a specified radius and fill
Circle(double X, double Y, double r, Paint f): creates a circle with given X and y coordinates of the center of the circle, and the radius and also a specified fill .
Commonly used methods:
Below programs illustrate the use of the Circle class:
Java program to create a circle by passing the coordinates of the center and radius as arguments in constructor: This program creates a Circle indicated by the name circle( the coordinates of the center and the radius is passed as arguments). The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a circle and using the functions setCenterX, setCenterY and setRadius to set the coordinates of center and radius: This program creates a Circle indicated by the name circle. The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a circle with specified radius and coordinates of center and also specified fill: This program creates a Circle indicated by the name circle.The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. .The function set Fill() is used to set the fill of the circle The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached.The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.htmlMy Personal Notes
arrow_drop_upSave
Java program to create a circle by passing the coordinates of the center and radius as arguments in constructor: This program creates a Circle indicated by the name circle( the coordinates of the center and the radius is passed as arguments). The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java program to create a circle and using the functions setCenterX, setCenterY and setRadius to set the coordinates of center and radius: This program creates a Circle indicated by the name circle. The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java program to create a circle with specified radius and coordinates of center and also specified fill: This program creates a Circle indicated by the name circle.The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. .The function set Fill() is used to set the fill of the circle The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached.The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.htmlMy Personal Notes
arrow_drop_upSave
// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating circle"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note : The above programs might not run in an online IDE please use an offline compiler.
Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.html
ManasChhabra2
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
|
[
{
"code": null,
"e": 24042,
"s": 24014,
"text": "\n25 Oct, 2019"
},
{
"code": null,
"e": 24304,
"s": 24042,
"text": "Circle class is a part of the JavaFX library. Circle class creates a circle with a specified x and y position for the center of the circle, the specified radius for the circle and a specified fill.The radius and the center of the circles are measured in pixels."
},
{
"code": null,
"e": 24335,
"s": 24304,
"text": "Constructors of the class are:"
},
{
"code": null,
"e": 24809,
"s": 24335,
"text": "Circle(): creates a empty instance of circleCircle(double r): creates a circle with a specified radiusCircle(double X, double Y, double r): creates a circle with given X and y coordinates of the center of the circle, and the radius.Circle(double r, paint f) creates a circle with a specified radius and fillCircle(double X, double Y, double r, Paint f): creates a circle with given X and y coordinates of the center of the circle, and the radius and also a specified fill ."
},
{
"code": null,
"e": 24854,
"s": 24809,
"text": "Circle(): creates a empty instance of circle"
},
{
"code": null,
"e": 24913,
"s": 24854,
"text": "Circle(double r): creates a circle with a specified radius"
},
{
"code": null,
"e": 25044,
"s": 24913,
"text": "Circle(double X, double Y, double r): creates a circle with given X and y coordinates of the center of the circle, and the radius."
},
{
"code": null,
"e": 25120,
"s": 25044,
"text": "Circle(double r, paint f) creates a circle with a specified radius and fill"
},
{
"code": null,
"e": 25287,
"s": 25120,
"text": "Circle(double X, double Y, double r, Paint f): creates a circle with given X and y coordinates of the center of the circle, and the radius and also a specified fill ."
},
{
"code": null,
"e": 25310,
"s": 25287,
"text": "Commonly used methods:"
},
{
"code": null,
"e": 25365,
"s": 25310,
"text": "Below programs illustrate the use of the Circle class:"
},
{
"code": null,
"e": 30868,
"s": 25365,
"text": "Java program to create a circle by passing the coordinates of the center and radius as arguments in constructor: This program creates a Circle indicated by the name circle( the coordinates of the center and the radius is passed as arguments). The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a circle and using the functions setCenterX, setCenterY and setRadius to set the coordinates of center and radius: This program creates a Circle indicated by the name circle. The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Java program to create a circle with specified radius and coordinates of center and also specified fill: This program creates a Circle indicated by the name circle.The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. .The function set Fill() is used to set the fill of the circle The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached.The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32428,
"s": 30868,
"text": "Java program to create a circle by passing the coordinates of the center and radius as arguments in constructor: This program creates a Circle indicated by the name circle( the coordinates of the center and the radius is passed as arguments). The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java program to create circle by passing the// coordinates of the center and radius// as arguments in constructorimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(150.0f, 150.0f, 80.f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 33432,
"s": 32428,
"text": null
},
{
"code": null,
"e": 33440,
"s": 33432,
"text": "Output:"
},
{
"code": null,
"e": 35279,
"s": 33440,
"text": "Java program to create a circle and using the functions setCenterX, setCenterY and setRadius to set the coordinates of center and radius: This program creates a Circle indicated by the name circle. The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java program to create a circle and using // the functions setCenterX, setCenterY and setRadius// to set the coordinates of center and radiusimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 36482,
"s": 35279,
"text": null
},
{
"code": null,
"e": 36490,
"s": 36482,
"text": "Output:"
},
{
"code": null,
"e": 38596,
"s": 36490,
"text": "Java program to create a circle with specified radius and coordinates of center and also specified fill: This program creates a Circle indicated by the name circle.The coordinates for the center and the radius of the circle is set using setCenterX(), setCenterY(), and setRadius function. .The function set Fill() is used to set the fill of the circle The Circle will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the circle is attached.The group is attached to the scene. Finally, the show() method is called to display the final results.// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note : The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.htmlMy Personal Notes\narrow_drop_upSave"
},
{
"code": "// Java program to create a circle with specified// radius and coordinates of center and also specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Circle;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class circle_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating circle\"); // create a circle Circle circle = new Circle(); // set the position of center of the circle circle.setCenterX(100.0f); circle.setCenterY(100.0f); // set Radius of the circle circle.setRadius(50.0f); // set the fill of the circle circle.setFill(Color.BLUE); // create a Group Group group = new Group(circle); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 39837,
"s": 38596,
"text": null
},
{
"code": null,
"e": 39845,
"s": 39837,
"text": "Output:"
},
{
"code": null,
"e": 39934,
"s": 39845,
"text": "Note : The above programs might not run in an online IDE please use an offline compiler."
},
{
"code": null,
"e": 40013,
"s": 39934,
"text": "Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/shape/Circle.html"
},
{
"code": null,
"e": 40027,
"s": 40013,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 40034,
"s": 40027,
"text": "JavaFX"
},
{
"code": null,
"e": 40039,
"s": 40034,
"text": "Java"
},
{
"code": null,
"e": 40044,
"s": 40039,
"text": "Java"
},
{
"code": null,
"e": 40142,
"s": 40044,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40174,
"s": 40142,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 40225,
"s": 40174,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 40255,
"s": 40225,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 40274,
"s": 40255,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 40305,
"s": 40274,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 40337,
"s": 40305,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 40357,
"s": 40337,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 40372,
"s": 40357,
"text": "Stream In Java"
},
{
"code": null,
"e": 40396,
"s": 40372,
"text": "Singleton Class in Java"
}
] |
Drawing an SVG file on an HTML5 canvas
|
To drawHTMLImageElements on a canvas element, use the drawImage() method.This method defines an Image variable with src=”mySVG.svg”, anduse drawImage on load.
var myImg = new Image();
myImg.onload = function() {
ctx.drawImage(myImg, 0, 0);
}
img.src = "http://www.example.com/files/sample.svg ";
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "To drawHTMLImageElements on a canvas element, use the drawImage() method.This method defines an Image variable with src=”mySVG.svg”, anduse drawImage on load."
},
{
"code": null,
"e": 1361,
"s": 1221,
"text": "var myImg = new Image();\nmyImg.onload = function() {\n ctx.drawImage(myImg, 0, 0);\n}\nimg.src = \"http://www.example.com/files/sample.svg \";"
}
] |
Internal details of std::sort() in C++ - GeeksforGeeks
|
26 Jul, 2021
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a built-in function in C++ STL by the name of sort().
std::sort() is a generic function in C++ Standard Library, for doing comparison sorting.
sort(startaddress, endaddress, comparator)
where:
startaddress: the address of the first element of the array
endaddress: the address of the last element of the array
comparator: the comparison to be done with the array.
This argument is optional.
C++
// C++ program to demonstrate// behaviour of sort() in STL. #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n); cout << "\nArray after sorting using " "default sort is : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;}
Array after sorting using default sort is :
0 1 2 3 4 5 6 7 8 9
Best Case – O(N log N)
Average Case- O(N log N)
Worse Case- O(N log N)
where, N = number of elements to be sorted.
The algorithm used by sort() is IntroSort. Introsort being a hybrid sorting algorithm uses three sorting algorithm to minimize the running time, Quicksort, Heapsort and Insertion Sort. Simply putting, it is the best sorting algorithm around. It is a hybrid sorting algorithm, which means that it uses more than one sorting algorithms as a routine.
C++
/* A Program to sort the array using Introsort. The most popular C++ STL Algorithm- sort() uses Introsort. */ #include<bits/stdc++.h>using namespace std; // A utility function to swap the values pointed by// the two pointersvoid swapValue(int *a, int *b){ int *temp = a; a = b; b = temp; return;} /* Function to sort an array using insertion sort*/void InsertionSort(int arr[], int *begin, int *end){ // Get the left and the right index of the subarray // to be sorted int left = begin - arr; int right = end - arr; for (int i = left+1; i <= right; i++) { int key = arr[i]; int j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= left && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } return;} // A function to partition the array and return// the partition pointint* Partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { // increment index of smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (arr + i + 1);} // A function that find the middle of the// values pointed by the pointers a, b, c// and return that pointerint *MedianOfThree(int * a, int * b, int * c){ if (*a < *b && *b < *c) return (b); if (*a < *c && *c <= *b) return (c); if (*b <= *a && *a < *c) return (a); if (*b < *c && *c <= *a) return (c); if (*c <= *a && *a < *b) return (a); if (*c <= *b && *b <= *c) return (b);} // A Utility function to perform intro sortvoid IntrosortUtil(int arr[], int * begin, int * end, int depthLimit){ // Count the number of elements int size = end - begin; // If partition size is low then do insertion sort if (size < 16) { InsertionSort(arr, begin, end); return; } // If the depth is zero use heapsort if (depthLimit == 0) { make_heap(begin, end+1); sort_heap(begin, end+1); return; } // Else use a median-of-three concept to // find a good pivot int * pivot = MedianOfThree(begin, begin+size/2, end); // Swap the values pointed by the two pointers swapValue(pivot, end); // Perform Quick Sort int * partitionPoint = Partition(arr, begin-arr, end-arr); IntrosortUtil(arr, begin, partitionPoint-1, depthLimit - 1); IntrosortUtil(arr, partitionPoint + 1, end, depthLimit - 1); return;} /* Implementation of introsort*/void Introsort(int arr[], int *begin, int *end){ int depthLimit = 2 * log(end-begin); // Perform a recursive Introsort IntrosortUtil(arr, begin, end, depthLimit); return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ for (int i=0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver program to test Introsortint main(){ int arr[] = {3, 1, 23, -9, 233, 23, -313, 32, -9}; int n = sizeof(arr) / sizeof(arr[0]); // Pass the array, the pointer to the first element and // the pointer to the last element Introsort(arr, arr, arr+n-1); printArray(arr, n); return(0);}
-313 -9 -9 1 3 23 23 32 233
Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array
It is better to use sort() instead of qsort() because:
sort() does not use unsafe void pointers like qsort().qsort() makes large number of function calls for comparison function compared to sort().C++ code with sort() is relatively faster than code with qsort().
sort() does not use unsafe void pointers like qsort().
qsort() makes large number of function calls for comparison function compared to sort().
C++ code with sort() is relatively faster than code with qsort().
Detailed article : Comparison of sort() with qsort()
singghakshay
STL
Technical Scripter 2018
C++
Sorting
Sorting
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 24202,
"s": 24174,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24418,
"s": 24202,
"text": "Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a built-in function in C++ STL by the name of sort(). "
},
{
"code": null,
"e": 24509,
"s": 24418,
"text": "std::sort() is a generic function in C++ Standard Library, for doing comparison sorting. "
},
{
"code": null,
"e": 24772,
"s": 24509,
"text": "sort(startaddress, endaddress, comparator)\n\nwhere:\nstartaddress: the address of the first element of the array\nendaddress: the address of the last element of the array\ncomparator: the comparison to be done with the array. \n This argument is optional. "
},
{
"code": null,
"e": 24776,
"s": 24772,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// behaviour of sort() in STL. #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n); cout << \"\\nArray after sorting using \" \"default sort is : \\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}",
"e": 25161,
"s": 24776,
"text": null
},
{
"code": null,
"e": 25226,
"s": 25161,
"text": "Array after sorting using default sort is : \n0 1 2 3 4 5 6 7 8 9"
},
{
"code": null,
"e": 25251,
"s": 25228,
"text": "Best Case – O(N log N)"
},
{
"code": null,
"e": 25276,
"s": 25251,
"text": "Average Case- O(N log N)"
},
{
"code": null,
"e": 25299,
"s": 25276,
"text": "Worse Case- O(N log N)"
},
{
"code": null,
"e": 25344,
"s": 25299,
"text": "where, N = number of elements to be sorted. "
},
{
"code": null,
"e": 25693,
"s": 25344,
"text": "The algorithm used by sort() is IntroSort. Introsort being a hybrid sorting algorithm uses three sorting algorithm to minimize the running time, Quicksort, Heapsort and Insertion Sort. Simply putting, it is the best sorting algorithm around. It is a hybrid sorting algorithm, which means that it uses more than one sorting algorithms as a routine. "
},
{
"code": null,
"e": 25697,
"s": 25693,
"text": "C++"
},
{
"code": "/* A Program to sort the array using Introsort. The most popular C++ STL Algorithm- sort() uses Introsort. */ #include<bits/stdc++.h>using namespace std; // A utility function to swap the values pointed by// the two pointersvoid swapValue(int *a, int *b){ int *temp = a; a = b; b = temp; return;} /* Function to sort an array using insertion sort*/void InsertionSort(int arr[], int *begin, int *end){ // Get the left and the right index of the subarray // to be sorted int left = begin - arr; int right = end - arr; for (int i = left+1; i <= right; i++) { int key = arr[i]; int j = i-1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= left && arr[j] > key) { arr[j+1] = arr[j]; j = j-1; } arr[j+1] = key; } return;} // A function to partition the array and return// the partition pointint* Partition(int arr[], int low, int high){ int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { // increment index of smaller element i++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return (arr + i + 1);} // A function that find the middle of the// values pointed by the pointers a, b, c// and return that pointerint *MedianOfThree(int * a, int * b, int * c){ if (*a < *b && *b < *c) return (b); if (*a < *c && *c <= *b) return (c); if (*b <= *a && *a < *c) return (a); if (*b < *c && *c <= *a) return (c); if (*c <= *a && *a < *b) return (a); if (*c <= *b && *b <= *c) return (b);} // A Utility function to perform intro sortvoid IntrosortUtil(int arr[], int * begin, int * end, int depthLimit){ // Count the number of elements int size = end - begin; // If partition size is low then do insertion sort if (size < 16) { InsertionSort(arr, begin, end); return; } // If the depth is zero use heapsort if (depthLimit == 0) { make_heap(begin, end+1); sort_heap(begin, end+1); return; } // Else use a median-of-three concept to // find a good pivot int * pivot = MedianOfThree(begin, begin+size/2, end); // Swap the values pointed by the two pointers swapValue(pivot, end); // Perform Quick Sort int * partitionPoint = Partition(arr, begin-arr, end-arr); IntrosortUtil(arr, begin, partitionPoint-1, depthLimit - 1); IntrosortUtil(arr, partitionPoint + 1, end, depthLimit - 1); return;} /* Implementation of introsort*/void Introsort(int arr[], int *begin, int *end){ int depthLimit = 2 * log(end-begin); // Perform a recursive Introsort IntrosortUtil(arr, begin, end, depthLimit); return;} // A utility function ot print an array of size nvoid printArray(int arr[], int n){ for (int i=0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver program to test Introsortint main(){ int arr[] = {3, 1, 23, -9, 233, 23, -313, 32, -9}; int n = sizeof(arr) / sizeof(arr[0]); // Pass the array, the pointer to the first element and // the pointer to the last element Introsort(arr, arr, arr+n-1); printArray(arr, n); return(0);}",
"e": 29198,
"s": 25697,
"text": null
},
{
"code": null,
"e": 29226,
"s": 29198,
"text": "-313 -9 -9 1 3 23 23 32 233"
},
{
"code": null,
"e": 29388,
"s": 29228,
"text": "Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array "
},
{
"code": null,
"e": 29444,
"s": 29388,
"text": "It is better to use sort() instead of qsort() because: "
},
{
"code": null,
"e": 29652,
"s": 29444,
"text": "sort() does not use unsafe void pointers like qsort().qsort() makes large number of function calls for comparison function compared to sort().C++ code with sort() is relatively faster than code with qsort()."
},
{
"code": null,
"e": 29707,
"s": 29652,
"text": "sort() does not use unsafe void pointers like qsort()."
},
{
"code": null,
"e": 29796,
"s": 29707,
"text": "qsort() makes large number of function calls for comparison function compared to sort()."
},
{
"code": null,
"e": 29862,
"s": 29796,
"text": "C++ code with sort() is relatively faster than code with qsort()."
},
{
"code": null,
"e": 29916,
"s": 29862,
"text": "Detailed article : Comparison of sort() with qsort() "
},
{
"code": null,
"e": 29929,
"s": 29916,
"text": "singghakshay"
},
{
"code": null,
"e": 29933,
"s": 29929,
"text": "STL"
},
{
"code": null,
"e": 29957,
"s": 29933,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29961,
"s": 29957,
"text": "C++"
},
{
"code": null,
"e": 29969,
"s": 29961,
"text": "Sorting"
},
{
"code": null,
"e": 29977,
"s": 29969,
"text": "Sorting"
},
{
"code": null,
"e": 29981,
"s": 29977,
"text": "STL"
},
{
"code": null,
"e": 29985,
"s": 29981,
"text": "CPP"
},
{
"code": null,
"e": 30083,
"s": 29985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30111,
"s": 30083,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30131,
"s": 30111,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30155,
"s": 30131,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30188,
"s": 30155,
"text": "Friend class and function in C++"
}
] |
How to convert a string into a integer without using parseInt() function in JavaScript ? - GeeksforGeeks
|
02 Jun, 2021
In JavaScript, there is a simple function parseInt() to convert a string to an integer. In order to know more about the function, you can refer to this. In this article, we will learn how to convert the string to integer without using the parseInt() function. Advantage of parseInt() over this method. The parseInt() function converts number which is present in any base to base 10 which is not possible using the method discusses above.
The very simple idea is to multiply the string with 1. If the string contains a number it will convert to an integer otherwise NaN will be returned
Example 1:
Javascript
<script> function convertStoI() { var a = "100"; var b = a*1; console.log(typeof(b)); var d = "3 11 43"*1; console.log(typeof(d)); }convertStoI();</script>
Output:
number
number
Example 2:
Javascript
</script> function convertStoI() { // The second argument specifies // the number passes is in base 2 var r = parseInt("111", 2); console.log('Integer value is ' + r); // The second argument specifies // the number passes is in base 8 var p = parseInt("156", 8); console.log('Integer value is ' + p); // The second argument specifies // the number passes is in base 16 var q = parseInt("AE", 16); console.log('Integer value is ' + q); }convertStoI();</script>
Output:
Integer value is 7
Integer value is 110
Integer value is 174
javascript-basics
JavaScript-Questions
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25324,
"s": 25296,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 25762,
"s": 25324,
"text": "In JavaScript, there is a simple function parseInt() to convert a string to an integer. In order to know more about the function, you can refer to this. In this article, we will learn how to convert the string to integer without using the parseInt() function. Advantage of parseInt() over this method. The parseInt() function converts number which is present in any base to base 10 which is not possible using the method discusses above."
},
{
"code": null,
"e": 25910,
"s": 25762,
"text": "The very simple idea is to multiply the string with 1. If the string contains a number it will convert to an integer otherwise NaN will be returned"
},
{
"code": null,
"e": 25921,
"s": 25910,
"text": "Example 1:"
},
{
"code": null,
"e": 25932,
"s": 25921,
"text": "Javascript"
},
{
"code": "<script> function convertStoI() { var a = \"100\"; var b = a*1; console.log(typeof(b)); var d = \"3 11 43\"*1; console.log(typeof(d)); }convertStoI();</script> ",
"e": 26137,
"s": 25932,
"text": null
},
{
"code": null,
"e": 26145,
"s": 26137,
"text": "Output:"
},
{
"code": null,
"e": 26159,
"s": 26145,
"text": "number\nnumber"
},
{
"code": null,
"e": 26170,
"s": 26159,
"text": "Example 2:"
},
{
"code": null,
"e": 26181,
"s": 26170,
"text": "Javascript"
},
{
"code": "</script> function convertStoI() { // The second argument specifies // the number passes is in base 2 var r = parseInt(\"111\", 2); console.log('Integer value is ' + r); // The second argument specifies // the number passes is in base 8 var p = parseInt(\"156\", 8); console.log('Integer value is ' + p); // The second argument specifies // the number passes is in base 16 var q = parseInt(\"AE\", 16); console.log('Integer value is ' + q); }convertStoI();</script>",
"e": 26777,
"s": 26181,
"text": null
},
{
"code": null,
"e": 26785,
"s": 26777,
"text": "Output:"
},
{
"code": null,
"e": 26846,
"s": 26785,
"text": "Integer value is 7\nInteger value is 110\nInteger value is 174"
},
{
"code": null,
"e": 26864,
"s": 26846,
"text": "javascript-basics"
},
{
"code": null,
"e": 26885,
"s": 26864,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 26903,
"s": 26885,
"text": "javascript-string"
},
{
"code": null,
"e": 26914,
"s": 26903,
"text": "JavaScript"
},
{
"code": null,
"e": 26931,
"s": 26914,
"text": "Web Technologies"
},
{
"code": null,
"e": 27029,
"s": 26931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27090,
"s": 27029,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27131,
"s": 27090,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27185,
"s": 27131,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27233,
"s": 27185,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 27273,
"s": 27233,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27315,
"s": 27273,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27348,
"s": 27315,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27391,
"s": 27348,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27453,
"s": 27391,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Find the most repeated word in a text file - GeeksforGeeks
|
25 Oct, 2021
Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files, and binary files (written in binary language,0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language.
Here we are operating on the .txt file in Python. Through this program, we will find the most repeated word in a file.
Approach:
We will take the content of the file as input.
We will save each word in a list after removing spaces and punctuation from the input string.
Find the frequency of each word.
Print the word which has a maximum frequency.
Input File:
Below is the implementation of the above approach:
Python3
# Python program to find the most repeated word# in a text file # A file named "gfg", will be opened with the # reading mode.file = open("gfg.txt","r")frequent_word = ""frequency = 0 words = [] # Traversing file line by linefor line in file: # splits each line into # words and removing spaces # and punctuations from the input line_word = line.lower().replace(',','').replace('.','').split(" "); # Adding them to list words for w in line_word: words.append(w); # Finding the max occurred wordfor i in range(0, len(words)): # Declaring count count = 1; # Count each word in the file for j in range(i+1, len(words)): if(words[i] == words[j]): count = count + 1; # If the count value is more # than highest frequency then if(count > frequency): frequency = count; frequent_word = words[i]; print("Most repeated word: " + frequent_word)print("Frequency: " + str(frequency))file.close();
Output:
Most repeated word: well
Frequency: 3
saurabh1990aror
Python file-handling-programs
python-file-handling
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 25778,
"s": 25581,
"text": "Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files, and binary files (written in binary language,0s and 1s)."
},
{
"code": null,
"e": 25956,
"s": 25778,
"text": "Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\\n’) in python by default."
},
{
"code": null,
"e": 26115,
"s": 25956,
"text": "Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language."
},
{
"code": null,
"e": 26234,
"s": 26115,
"text": "Here we are operating on the .txt file in Python. Through this program, we will find the most repeated word in a file."
},
{
"code": null,
"e": 26244,
"s": 26234,
"text": "Approach:"
},
{
"code": null,
"e": 26291,
"s": 26244,
"text": "We will take the content of the file as input."
},
{
"code": null,
"e": 26385,
"s": 26291,
"text": "We will save each word in a list after removing spaces and punctuation from the input string."
},
{
"code": null,
"e": 26418,
"s": 26385,
"text": "Find the frequency of each word."
},
{
"code": null,
"e": 26464,
"s": 26418,
"text": "Print the word which has a maximum frequency."
},
{
"code": null,
"e": 26476,
"s": 26464,
"text": "Input File:"
},
{
"code": null,
"e": 26527,
"s": 26476,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26535,
"s": 26527,
"text": "Python3"
},
{
"code": "# Python program to find the most repeated word# in a text file # A file named \"gfg\", will be opened with the # reading mode.file = open(\"gfg.txt\",\"r\")frequent_word = \"\"frequency = 0 words = [] # Traversing file line by linefor line in file: # splits each line into # words and removing spaces # and punctuations from the input line_word = line.lower().replace(',','').replace('.','').split(\" \"); # Adding them to list words for w in line_word: words.append(w); # Finding the max occurred wordfor i in range(0, len(words)): # Declaring count count = 1; # Count each word in the file for j in range(i+1, len(words)): if(words[i] == words[j]): count = count + 1; # If the count value is more # than highest frequency then if(count > frequency): frequency = count; frequent_word = words[i]; print(\"Most repeated word: \" + frequent_word)print(\"Frequency: \" + str(frequency))file.close();",
"e": 27538,
"s": 26535,
"text": null
},
{
"code": null,
"e": 27546,
"s": 27538,
"text": "Output:"
},
{
"code": null,
"e": 27584,
"s": 27546,
"text": "Most repeated word: well\nFrequency: 3"
},
{
"code": null,
"e": 27600,
"s": 27584,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27630,
"s": 27600,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 27651,
"s": 27630,
"text": "python-file-handling"
},
{
"code": null,
"e": 27675,
"s": 27651,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 27682,
"s": 27675,
"text": "Python"
},
{
"code": null,
"e": 27701,
"s": 27682,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27799,
"s": 27701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27831,
"s": 27799,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27873,
"s": 27831,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27915,
"s": 27873,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27971,
"s": 27915,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27998,
"s": 27971,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28029,
"s": 27998,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28068,
"s": 28029,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28097,
"s": 28068,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28119,
"s": 28097,
"text": "Defaultdict in Python"
}
] |
regexp_like(string, pattern)
|
presto:default> SELECT regexp_like('1a 2b 3c 6f', '\d+c') as expression;
expression
------------
true
Here, the digit 3 has character c, hence the result is true.
presto:default> SELECT regexp_like('1a 2b 3c 6f', '\d+e') as expression;
expression
------------
false
Here, the character e is not in the regular expression.
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": 2080,
"s": 2006,
"text": "presto:default> SELECT regexp_like('1a 2b 3c 6f', '\\d+c') as expression; "
},
{
"code": null,
"e": 2116,
"s": 2080,
"text": " expression \n------------ \n true\n"
},
{
"code": null,
"e": 2177,
"s": 2116,
"text": "Here, the digit 3 has character c, hence the result is true."
},
{
"code": null,
"e": 2251,
"s": 2177,
"text": "presto:default> SELECT regexp_like('1a 2b 3c 6f', '\\d+e') as expression; "
},
{
"code": null,
"e": 2289,
"s": 2251,
"text": " expression \n------------ \n false \n"
},
{
"code": null,
"e": 2345,
"s": 2289,
"text": "Here, the character e is not in the regular expression."
},
{
"code": null,
"e": 2380,
"s": 2345,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2399,
"s": 2380,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 2434,
"s": 2399,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2455,
"s": 2434,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 2488,
"s": 2455,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2501,
"s": 2488,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 2536,
"s": 2501,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 2554,
"s": 2536,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2587,
"s": 2554,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2605,
"s": 2587,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2638,
"s": 2605,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 2656,
"s": 2638,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 2663,
"s": 2656,
"text": " Print"
},
{
"code": null,
"e": 2674,
"s": 2663,
"text": " Add Notes"
}
] |
acpid command in Linux with Examples - GeeksforGeeks
|
17 Sep, 2021
The acpid daemon provides intelligent power management on a system and allows to query battery and configuration status by supporting the Advanced Configuration and Power Interface (ACPI). The ACPI events are notified to the user-space programs by acpid. The ACPI (Advanced Configuration and Power Interface) specification allows the operating system to control the amount of power it provides to each device or peripheral attached to the system. This makes the operating system to turn off specific devices when they are no longer in use such as the monitor, providing stable and efficient power management. acpid being a daemon runs as a background process by default and it should start during the system boot. Whenever an event occurs it executes programs to handle the event. It does so as it opens an events file (/proc/acpi/event by default) and reads all the lines. When a line is received (an event), it examines a list of rules to execute the one that matches the event. If there is a lock file (/var/lock/acpid by default) it ignores all incoming ACPI events. Simple configuration files are used to define the rules. It looks in a configuration directory (/etc/acpi/events by default) and all the files that do not begin with a period (‘.’) or end with a tilde (~) are parsed. Each file must define an event and a corresponding action. Blank lines or lines with the first character as hash (‘#’) are ignored.
There are three tokens in each line: the key, a literal equal sign and the value.
The key can take up to 63 characters, is case-insensitive but whitespaces matters.
The value can take up to 511 characters, it is case and whitespace sensitive. The event value consists of a regular expression and events are matched against it.
Installation Command:
sudo apt-get install acpid
Synopsis:
acpid [options]
Options:
c, –confdir directory Changes the directory that acpid looks for rule configuration files. The default directory is /etc/acpi/events.
C, –clientmax number Changes the maximum number of non-root socket connections that can be made to the acpid socket. The default is 256.
d, –debug Increases the acpid debug level by one. It runs in the foreground if the debug level is non-zero and logs to stderr and to the regular syslog.
e, –eventfile filename Changes the event file. Acpid reads events from it. The default file is /proc/acpi/event.
f, –foreground Keeps acpid in the foreground by not forking at startup.
l, –logevents Tells acpid to log information related to all the events and actions.
L, –lockfile filename Changes the lock file that is used to stop event processing. The default file is /var/lock/acpid.
g, –socketgroup groupname Changes the group ownership of domain socket. Acpid publishes events to it.
m, –socketmode mode Changes the permissions of the UNIX domain socket. Default is 0666.
s, –socketfile filename Changes the name of the UNIX domain socket that is opened by acpid. The default is /var/run/acpid.socket.
S, –nosocket filename Tells acpid to not open a UNIX domain socket. This overrides the -s option, it also negates all other socket options.
p, –pidfile filename Tells acpid to use the specified file as its pidfile. If the file exists, it will be removed and over-written. The default is /var/run/acpid.pid.
v, –version Prints the version information and exits.
h, –help Shows help and exits.
Service Control
Use the service utility for controlling the acpid service:
service acpid
To Start the service:
service acpid start
You will be prompted for authentication.
To Stop the service:
service acpid stop
You will be prompted for authentication.
Check if the service is started or stopped:
service acpid status
varshagumber28
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
Conditional Statements | Shell Script
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
Mutex lock for Linux Thread Synchronization
|
[
{
"code": null,
"e": 24036,
"s": 24008,
"text": "\n17 Sep, 2021"
},
{
"code": null,
"e": 25457,
"s": 24036,
"text": "The acpid daemon provides intelligent power management on a system and allows to query battery and configuration status by supporting the Advanced Configuration and Power Interface (ACPI). The ACPI events are notified to the user-space programs by acpid. The ACPI (Advanced Configuration and Power Interface) specification allows the operating system to control the amount of power it provides to each device or peripheral attached to the system. This makes the operating system to turn off specific devices when they are no longer in use such as the monitor, providing stable and efficient power management. acpid being a daemon runs as a background process by default and it should start during the system boot. Whenever an event occurs it executes programs to handle the event. It does so as it opens an events file (/proc/acpi/event by default) and reads all the lines. When a line is received (an event), it examines a list of rules to execute the one that matches the event. If there is a lock file (/var/lock/acpid by default) it ignores all incoming ACPI events. Simple configuration files are used to define the rules. It looks in a configuration directory (/etc/acpi/events by default) and all the files that do not begin with a period (‘.’) or end with a tilde (~) are parsed. Each file must define an event and a corresponding action. Blank lines or lines with the first character as hash (‘#’) are ignored. "
},
{
"code": null,
"e": 25540,
"s": 25457,
"text": "There are three tokens in each line: the key, a literal equal sign and the value. "
},
{
"code": null,
"e": 25625,
"s": 25542,
"text": "The key can take up to 63 characters, is case-insensitive but whitespaces matters."
},
{
"code": null,
"e": 25787,
"s": 25625,
"text": "The value can take up to 511 characters, it is case and whitespace sensitive. The event value consists of a regular expression and events are matched against it."
},
{
"code": null,
"e": 25810,
"s": 25787,
"text": "Installation Command: "
},
{
"code": null,
"e": 25839,
"s": 25812,
"text": "sudo apt-get install acpid"
},
{
"code": null,
"e": 25851,
"s": 25839,
"text": "Synopsis: "
},
{
"code": null,
"e": 25867,
"s": 25851,
"text": "acpid [options]"
},
{
"code": null,
"e": 25878,
"s": 25867,
"text": "Options: "
},
{
"code": null,
"e": 26012,
"s": 25878,
"text": "c, –confdir directory Changes the directory that acpid looks for rule configuration files. The default directory is /etc/acpi/events."
},
{
"code": null,
"e": 26149,
"s": 26012,
"text": "C, –clientmax number Changes the maximum number of non-root socket connections that can be made to the acpid socket. The default is 256."
},
{
"code": null,
"e": 26302,
"s": 26149,
"text": "d, –debug Increases the acpid debug level by one. It runs in the foreground if the debug level is non-zero and logs to stderr and to the regular syslog."
},
{
"code": null,
"e": 26415,
"s": 26302,
"text": "e, –eventfile filename Changes the event file. Acpid reads events from it. The default file is /proc/acpi/event."
},
{
"code": null,
"e": 26487,
"s": 26415,
"text": "f, –foreground Keeps acpid in the foreground by not forking at startup."
},
{
"code": null,
"e": 26571,
"s": 26487,
"text": "l, –logevents Tells acpid to log information related to all the events and actions."
},
{
"code": null,
"e": 26691,
"s": 26571,
"text": "L, –lockfile filename Changes the lock file that is used to stop event processing. The default file is /var/lock/acpid."
},
{
"code": null,
"e": 26793,
"s": 26691,
"text": "g, –socketgroup groupname Changes the group ownership of domain socket. Acpid publishes events to it."
},
{
"code": null,
"e": 26881,
"s": 26793,
"text": "m, –socketmode mode Changes the permissions of the UNIX domain socket. Default is 0666."
},
{
"code": null,
"e": 27011,
"s": 26881,
"text": "s, –socketfile filename Changes the name of the UNIX domain socket that is opened by acpid. The default is /var/run/acpid.socket."
},
{
"code": null,
"e": 27151,
"s": 27011,
"text": "S, –nosocket filename Tells acpid to not open a UNIX domain socket. This overrides the -s option, it also negates all other socket options."
},
{
"code": null,
"e": 27318,
"s": 27151,
"text": "p, –pidfile filename Tells acpid to use the specified file as its pidfile. If the file exists, it will be removed and over-written. The default is /var/run/acpid.pid."
},
{
"code": null,
"e": 27374,
"s": 27318,
"text": "v, –version Prints the version information and exits. "
},
{
"code": null,
"e": 27409,
"s": 27376,
"text": "h, –help Shows help and exits. "
},
{
"code": null,
"e": 27429,
"s": 27411,
"text": "Service Control "
},
{
"code": null,
"e": 27490,
"s": 27429,
"text": "Use the service utility for controlling the acpid service: "
},
{
"code": null,
"e": 27504,
"s": 27490,
"text": "service acpid"
},
{
"code": null,
"e": 27530,
"s": 27506,
"text": "To Start the service: "
},
{
"code": null,
"e": 27550,
"s": 27530,
"text": "service acpid start"
},
{
"code": null,
"e": 27591,
"s": 27550,
"text": "You will be prompted for authentication."
},
{
"code": null,
"e": 27614,
"s": 27591,
"text": "To Stop the service: "
},
{
"code": null,
"e": 27633,
"s": 27614,
"text": "service acpid stop"
},
{
"code": null,
"e": 27676,
"s": 27635,
"text": "You will be prompted for authentication."
},
{
"code": null,
"e": 27722,
"s": 27676,
"text": "Check if the service is started or stopped: "
},
{
"code": null,
"e": 27743,
"s": 27722,
"text": "service acpid status"
},
{
"code": null,
"e": 27760,
"s": 27745,
"text": "varshagumber28"
},
{
"code": null,
"e": 27774,
"s": 27760,
"text": "linux-command"
},
{
"code": null,
"e": 27794,
"s": 27774,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 27801,
"s": 27794,
"text": "Picked"
},
{
"code": null,
"e": 27812,
"s": 27801,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27910,
"s": 27812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27919,
"s": 27910,
"text": "Comments"
},
{
"code": null,
"e": 27932,
"s": 27919,
"text": "Old Comments"
},
{
"code": null,
"e": 27970,
"s": 27932,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28005,
"s": 27970,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 28040,
"s": 28005,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 28078,
"s": 28040,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 28114,
"s": 28078,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 28152,
"s": 28114,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 28187,
"s": 28152,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 28223,
"s": 28187,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 28260,
"s": 28223,
"text": "touch command in Linux with Examples"
}
] |
ByteBuffer wrap() method in Java with Examples - GeeksforGeeks
|
01 Nov, 2019
The wrap() method of java.nio.ByteBuffer Class is used to wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer’s capacity and limit will be array.length, its position will be zero, and its mark will be undefined. It’s backing array will be the given array, and its array offset will be zero.
Syntax:
public static ByteBuffer wrap(float[] array)
Parameters: This method takes a float array as parameter which is the array that will back this buffer.
Return Value: This method returns the new byte buffer.
Below are the examples to illustrate the wrap() method:
Examples 1:
// Java program to demonstrate// wrap() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println("Array length : " + bbb.length); // print the byte array element System.out.println("\nArray element : " + Arrays.toString(bbb)); // wrap the byte array into byteBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bbb); // Rewind the ByteBuffer byteBuffer.rewind(); // print the byte buffer System.out.println("\nbyteBuffer : " + Arrays.toString(byteBuffer.array())); // print the ByteBuffer capacity System.out.println("\nbyteBuffer capacity : " + byteBuffer.capacity()); // print the ByteBuffer position System.out.println("\nbyteBuffer position: " + byteBuffer.position()); }}
Array length : 3
Array element : [10, 20, 30]
byteBuffer : [10, 20, 30]
byteBuffer capacity : 3
byteBuffer position: 0
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#wrap-byte:A-
The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer’s capacity will be array.length, its position will be offset, its limit will be offset + length, and its mark will be undefined. It’s backing array will be the given array, and its array offset will be zero.
Syntax :
public static ByteBuffer wrap(byte[] array,
int offset, int length)
Parameters: This method takes following parameters:
array: The array that will back the new buffer.
offset: The offset of the subarray to be used; must be non-negative and no larger than array.length. The new buffer’s position will be set to this value.
length: The length of the subarray to be used; must be non-negative and no larger than array.length – offset. The new buffer’s limit will be set to offset + length.
Return Value: This method returns the new byte buffer.
Throws: This method throws the IndexOutOfBoundsException(If the preconditions on the offset and length parameters do not hold) .
Below are the examples to illustrate the wrap() method:
Examples 1:
// Java program to demonstrate// wrap() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println("Array length : " + bbb.length); // print the byte array element System.out.println("\nArray element : " + Arrays.toString(bbb)); // wrap the byte array into ByteBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bbb, 0, bbb.length); // Rewind the bytebuffer byteBuffer.rewind(); // print the byte buffer System.out.println("\nbyteBuffer : " + Arrays.toString(byteBuffer.array())); // print the ByteBuffer capacity System.out.println("\nbyteBuffer capacity : " + byteBuffer.capacity()); // print the ByteBuffer position System.out.println("\nbyteBuffer position: " + byteBuffer.position()); }}
Array length : 3
Array element : [10, 20, 30]
byteBuffer : [10, 20, 30]
byteBuffer capacity : 3
byteBuffer position: 0
Examples 2: To demonstrate NullPointerException
// Java program to demonstrate// asReadOnlyBuffer() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println("Array length : " + bbb.length); // print the byte array element System.out.println("\nArray element : " + Arrays.toString(bbb)); try { // wrap the byte array into byteBuffer // using wrap() method System.out.println("\nHere " + "offset and length does not hold" + " the required condition "); ByteBuffer byteBuffer = ByteBuffer.wrap(bbb, 1, bbb.length); // Rewind the bytebuffer byteBuffer.rewind(); // print the byte buffer System.out.println("\nbyteBuffer : " + Arrays.toString(byteBuffer.array())); // print the byteBuffer capacity System.out.println("\nbytebuffer capacity : " + byteBuffer.capacity()); // print the byteBuffer position System.out.println("\nbytebuffer position: " + byteBuffer.position()); } catch (IndexOutOfBoundsException e) { System.out.println("Exception throws: " + e); } }}
Array length : 3
Array element : [10, 20, 30]
Here offset and length does not hold the required condition
Exception throws: java.lang.IndexOutOfBoundsException
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#wrap-byte:A-int-int-
shubham_singh
Akanksha_Rai
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
|
[
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n01 Nov, 2019"
},
{
"code": null,
"e": 24946,
"s": 24514,
"text": "The wrap() method of java.nio.ByteBuffer Class is used to wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer’s capacity and limit will be array.length, its position will be zero, and its mark will be undefined. It’s backing array will be the given array, and its array offset will be zero."
},
{
"code": null,
"e": 24954,
"s": 24946,
"text": "Syntax:"
},
{
"code": null,
"e": 24999,
"s": 24954,
"text": "public static ByteBuffer wrap(float[] array)"
},
{
"code": null,
"e": 25103,
"s": 24999,
"text": "Parameters: This method takes a float array as parameter which is the array that will back this buffer."
},
{
"code": null,
"e": 25158,
"s": 25103,
"text": "Return Value: This method returns the new byte buffer."
},
{
"code": null,
"e": 25214,
"s": 25158,
"text": "Below are the examples to illustrate the wrap() method:"
},
{
"code": null,
"e": 25226,
"s": 25214,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// wrap() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println(\"Array length : \" + bbb.length); // print the byte array element System.out.println(\"\\nArray element : \" + Arrays.toString(bbb)); // wrap the byte array into byteBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bbb); // Rewind the ByteBuffer byteBuffer.rewind(); // print the byte buffer System.out.println(\"\\nbyteBuffer : \" + Arrays.toString(byteBuffer.array())); // print the ByteBuffer capacity System.out.println(\"\\nbyteBuffer capacity : \" + byteBuffer.capacity()); // print the ByteBuffer position System.out.println(\"\\nbyteBuffer position: \" + byteBuffer.position()); }}",
"e": 26366,
"s": 25226,
"text": null
},
{
"code": null,
"e": 26491,
"s": 26366,
"text": "Array length : 3\n\nArray element : [10, 20, 30]\n\nbyteBuffer : [10, 20, 30]\n\nbyteBuffer capacity : 3\n\nbyteBuffer position: 0\n"
},
{
"code": null,
"e": 26582,
"s": 26491,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#wrap-byte:A-"
},
{
"code": null,
"e": 26949,
"s": 26582,
"text": "The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer’s capacity will be array.length, its position will be offset, its limit will be offset + length, and its mark will be undefined. It’s backing array will be the given array, and its array offset will be zero."
},
{
"code": null,
"e": 26958,
"s": 26949,
"text": "Syntax :"
},
{
"code": null,
"e": 27053,
"s": 26958,
"text": "public static ByteBuffer wrap(byte[] array, \n int offset, int length)"
},
{
"code": null,
"e": 27105,
"s": 27053,
"text": "Parameters: This method takes following parameters:"
},
{
"code": null,
"e": 27153,
"s": 27105,
"text": "array: The array that will back the new buffer."
},
{
"code": null,
"e": 27307,
"s": 27153,
"text": "offset: The offset of the subarray to be used; must be non-negative and no larger than array.length. The new buffer’s position will be set to this value."
},
{
"code": null,
"e": 27472,
"s": 27307,
"text": "length: The length of the subarray to be used; must be non-negative and no larger than array.length – offset. The new buffer’s limit will be set to offset + length."
},
{
"code": null,
"e": 27527,
"s": 27472,
"text": "Return Value: This method returns the new byte buffer."
},
{
"code": null,
"e": 27656,
"s": 27527,
"text": "Throws: This method throws the IndexOutOfBoundsException(If the preconditions on the offset and length parameters do not hold) ."
},
{
"code": null,
"e": 27712,
"s": 27656,
"text": "Below are the examples to illustrate the wrap() method:"
},
{
"code": null,
"e": 27724,
"s": 27712,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// wrap() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println(\"Array length : \" + bbb.length); // print the byte array element System.out.println(\"\\nArray element : \" + Arrays.toString(bbb)); // wrap the byte array into ByteBuffer // using wrap() method ByteBuffer byteBuffer = ByteBuffer.wrap(bbb, 0, bbb.length); // Rewind the bytebuffer byteBuffer.rewind(); // print the byte buffer System.out.println(\"\\nbyteBuffer : \" + Arrays.toString(byteBuffer.array())); // print the ByteBuffer capacity System.out.println(\"\\nbyteBuffer capacity : \" + byteBuffer.capacity()); // print the ByteBuffer position System.out.println(\"\\nbyteBuffer position: \" + byteBuffer.position()); }}",
"e": 28928,
"s": 27724,
"text": null
},
{
"code": null,
"e": 29053,
"s": 28928,
"text": "Array length : 3\n\nArray element : [10, 20, 30]\n\nbyteBuffer : [10, 20, 30]\n\nbyteBuffer capacity : 3\n\nbyteBuffer position: 0\n"
},
{
"code": null,
"e": 29101,
"s": 29053,
"text": "Examples 2: To demonstrate NullPointerException"
},
{
"code": "// Java program to demonstrate// asReadOnlyBuffer() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declare and initialize the byte array byte[] bbb = { 10, 20, 30 }; // print the byte array length System.out.println(\"Array length : \" + bbb.length); // print the byte array element System.out.println(\"\\nArray element : \" + Arrays.toString(bbb)); try { // wrap the byte array into byteBuffer // using wrap() method System.out.println(\"\\nHere \" + \"offset and length does not hold\" + \" the required condition \"); ByteBuffer byteBuffer = ByteBuffer.wrap(bbb, 1, bbb.length); // Rewind the bytebuffer byteBuffer.rewind(); // print the byte buffer System.out.println(\"\\nbyteBuffer : \" + Arrays.toString(byteBuffer.array())); // print the byteBuffer capacity System.out.println(\"\\nbytebuffer capacity : \" + byteBuffer.capacity()); // print the byteBuffer position System.out.println(\"\\nbytebuffer position: \" + byteBuffer.position()); } catch (IndexOutOfBoundsException e) { System.out.println(\"Exception throws: \" + e); } }}",
"e": 30677,
"s": 29101,
"text": null
},
{
"code": null,
"e": 30842,
"s": 30677,
"text": "Array length : 3\n\nArray element : [10, 20, 30]\n\nHere offset and length does not hold the required condition \nException throws: java.lang.IndexOutOfBoundsException\n"
},
{
"code": null,
"e": 30941,
"s": 30842,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#wrap-byte:A-int-int-"
},
{
"code": null,
"e": 30955,
"s": 30941,
"text": "shubham_singh"
},
{
"code": null,
"e": 30968,
"s": 30955,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 30984,
"s": 30968,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 30999,
"s": 30984,
"text": "Java-Functions"
},
{
"code": null,
"e": 31016,
"s": 30999,
"text": "Java-NIO package"
},
{
"code": null,
"e": 31021,
"s": 31016,
"text": "Java"
},
{
"code": null,
"e": 31026,
"s": 31021,
"text": "Java"
},
{
"code": null,
"e": 31124,
"s": 31026,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31133,
"s": 31124,
"text": "Comments"
},
{
"code": null,
"e": 31146,
"s": 31133,
"text": "Old Comments"
},
{
"code": null,
"e": 31178,
"s": 31146,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 31208,
"s": 31178,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 31227,
"s": 31208,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 31278,
"s": 31227,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 31296,
"s": 31278,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 31327,
"s": 31296,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 31359,
"s": 31327,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31378,
"s": 31359,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 31398,
"s": 31378,
"text": "Stack Class in Java"
}
] |
How to generate a 24bit hash using Python?
|
A random 24 bit hash is just random 24 bits. You can generate these just using the random module.
import random
hash = random.getrandbits(24)
print(hex(hash))
This will give the output
0x94fbee
|
[
{
"code": null,
"e": 1161,
"s": 1062,
"text": "A random 24 bit hash is just random 24 bits. You can generate these just using the random module. "
},
{
"code": null,
"e": 1222,
"s": 1161,
"text": "import random\nhash = random.getrandbits(24)\nprint(hex(hash))"
},
{
"code": null,
"e": 1248,
"s": 1222,
"text": "This will give the output"
},
{
"code": null,
"e": 1257,
"s": 1248,
"text": "0x94fbee"
}
] |
Is there any equivalent to typedef of C/C++ in Java ? - GeeksforGeeks
|
30 Mar, 2020
In one line, There is nothing in Java which is equivalent to typedef of C++.
In Java, class is used to name and construct types or we can say that class is the combined function of C++’s struct and typedef. But that is totally different thing and not the equivalent of typedef anywhere.
typedef: It is a keyword not a function that is used in C/C++ language to assign alternative names to existing data types. It is used with the user defined data types when the name of data types get little bit complicated that time the typedef keyword is used, unless it is unnecessary.Syntax of using typedef:
typedef existing_name alias_name;
C++
C
// C++ program to demonstrate typedef #include <bits/stdc++.h>using namespace std; // After this line BYTE can be used // in place of unsifted char typedef unsigned char BYTE; int main() { BYTE b1, b2; b1 = 'a'; cout << b1 ; return 0; } // This code is contributed by shubhamsingh10
// C program to demonstrate typedef#include <stdio.h> // After this line BYTE can be used// in place of unsifted chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'a'; printf("%c ", b1); return 0;}
a
typedef with pointers:typedef will also work with the pointer in C/C++ language like renaming existing keywords. In case of pointers * binds in the right not the left side.
int* x, y;
In the above syntax, we are actually declaring x as a pointer of type int, whereas y will be declared as a plain integer But if we use typedef then we can declare any number of pointers in a single statement like below.
typedef int* IntPtr ;
IntPtr x, y, z;
typedef can be used for :
typedef can provide a simple name for a complicated type cast
typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type
SHUBHAMSINGH10
C-Data Types
cpp-data-types
Picked
Technical Scripter 2018
C Language
C++
Java
Java
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++
Core Dump (Segmentation fault) in C/C++
Command line arguments in C/C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
|
[
{
"code": null,
"e": 24449,
"s": 24421,
"text": "\n30 Mar, 2020"
},
{
"code": null,
"e": 24526,
"s": 24449,
"text": "In one line, There is nothing in Java which is equivalent to typedef of C++."
},
{
"code": null,
"e": 24736,
"s": 24526,
"text": "In Java, class is used to name and construct types or we can say that class is the combined function of C++’s struct and typedef. But that is totally different thing and not the equivalent of typedef anywhere."
},
{
"code": null,
"e": 25047,
"s": 24736,
"text": "typedef: It is a keyword not a function that is used in C/C++ language to assign alternative names to existing data types. It is used with the user defined data types when the name of data types get little bit complicated that time the typedef keyword is used, unless it is unnecessary.Syntax of using typedef:"
},
{
"code": null,
"e": 25082,
"s": 25047,
"text": "typedef existing_name alias_name;\n"
},
{
"code": null,
"e": 25086,
"s": 25082,
"text": "C++"
},
{
"code": null,
"e": 25088,
"s": 25086,
"text": "C"
},
{
"code": "// C++ program to demonstrate typedef #include <bits/stdc++.h>using namespace std; // After this line BYTE can be used // in place of unsifted char typedef unsigned char BYTE; int main() { BYTE b1, b2; b1 = 'a'; cout << b1 ; return 0; } // This code is contributed by shubhamsingh10",
"e": 25393,
"s": 25088,
"text": null
},
{
"code": "// C program to demonstrate typedef#include <stdio.h> // After this line BYTE can be used// in place of unsifted chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'a'; printf(\"%c \", b1); return 0;}",
"e": 25617,
"s": 25393,
"text": null
},
{
"code": null,
"e": 25620,
"s": 25617,
"text": "a\n"
},
{
"code": null,
"e": 25793,
"s": 25620,
"text": "typedef with pointers:typedef will also work with the pointer in C/C++ language like renaming existing keywords. In case of pointers * binds in the right not the left side."
},
{
"code": null,
"e": 25805,
"s": 25793,
"text": "int* x, y;\n"
},
{
"code": null,
"e": 26025,
"s": 25805,
"text": "In the above syntax, we are actually declaring x as a pointer of type int, whereas y will be declared as a plain integer But if we use typedef then we can declare any number of pointers in a single statement like below."
},
{
"code": null,
"e": 26064,
"s": 26025,
"text": "typedef int* IntPtr ;\nIntPtr x, y, z;\n"
},
{
"code": null,
"e": 26090,
"s": 26064,
"text": "typedef can be used for :"
},
{
"code": null,
"e": 26152,
"s": 26090,
"text": "typedef can provide a simple name for a complicated type cast"
},
{
"code": null,
"e": 26272,
"s": 26152,
"text": "typedef can also be used to give names to unnamed types. In such cases, the typedef will be the only name for said type"
},
{
"code": null,
"e": 26287,
"s": 26272,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 26300,
"s": 26287,
"text": "C-Data Types"
},
{
"code": null,
"e": 26315,
"s": 26300,
"text": "cpp-data-types"
},
{
"code": null,
"e": 26322,
"s": 26315,
"text": "Picked"
},
{
"code": null,
"e": 26346,
"s": 26322,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 26357,
"s": 26346,
"text": "C Language"
},
{
"code": null,
"e": 26361,
"s": 26357,
"text": "C++"
},
{
"code": null,
"e": 26366,
"s": 26361,
"text": "Java"
},
{
"code": null,
"e": 26371,
"s": 26366,
"text": "Java"
},
{
"code": null,
"e": 26375,
"s": 26371,
"text": "CPP"
},
{
"code": null,
"e": 26473,
"s": 26375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26482,
"s": 26473,
"text": "Comments"
},
{
"code": null,
"e": 26495,
"s": 26482,
"text": "Old Comments"
},
{
"code": null,
"e": 26530,
"s": 26495,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26558,
"s": 26530,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 26598,
"s": 26558,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 26630,
"s": 26598,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 26676,
"s": 26630,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 26694,
"s": 26676,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 26740,
"s": 26694,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 26759,
"s": 26740,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26802,
"s": 26759,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Priority Queue using Linked List - GeeksforGeeks
|
23 Dec, 2021
Implement Priority Queue using Linked Lists.
push(): This function is used to insert a new data into the queue.
pop(): This function removes the element with the highest priority from the queue.
peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue.
Priority Queues can be implemented using common data structures like arrays, linked-lists, heaps and binary trees.
Prerequisites : Linked Lists, Priority Queues
The list is so created so that the highest priority element is always at the head of the list. The list is arranged in descending order of elements based on their priority. This allow us to remove the highest priority element in O(1) time. To insert an element we must traverse the list and find the proper position to insert the node so that the overall order of the priority queue is maintained. This makes the push() operation takes O(N) time. The pop() and peek() operations are performed in constant time.
Algorithm : PUSH(HEAD, DATA, PRIORITY) Step 1: Create new node with DATA and PRIORITY Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step 5. Step 3: NEW -> NEXT = HEAD Step 4: HEAD = NEW Step 5: Set TEMP to head of the list Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRIORITY Step 7: TEMP = TEMP -> NEXT [END OF LOOP] Step 8: NEW -> NEXT = TEMP -> NEXT Step 9: TEMP -> NEXT = NEW Step 10: EndPOP(HEAD) Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT. Step 3: Free the node at the head of the list Step 4: EndPEEK(HEAD): Step 1: Return HEAD -> DATA Step 2: End
Below is the implementation of the algorithm :
C++
C
Java
Python3
C#
Javascript
// C++ code to implement Priority Queue// using Linked List#include <bits/stdc++.h>using namespace std; // Nodetypedef struct node{ int data; // Lower values indicate // higher priority int priority; struct node* next; } Node; // Function to create a new nodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head){ return (*head)->data;} // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has // lesser priority than new node. So // insert newnode before head node // and change head node. if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head){ return (*head) == NULL;} // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { cout << " " << peek(&pq); pop(&pq); } return 0;} // This code is contributed by shivanisinghss2110
// C code to implement Priority Queue// using Linked List#include <stdio.h>#include <stdlib.h> // Nodetypedef struct node { int data; // Lower values indicate higher priority int priority; struct node* next; } Node; // Function to Create A New NodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head){ return (*head)->data;} // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has lesser // priority than new node. So insert new // node before head node and change head node. if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head){ return (*head) == NULL;} // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { printf("%d ", peek(&pq)); pop(&pq); } return 0;}
// Java code to implement Priority Queue// using Linked Listimport java.util.* ; class Solution{ // Nodestatic class Node { int data; // Lower values indicate higher priority int priority; Node next; } static Node node = new Node(); // Function to Create A New Nodestatic Node newNode(int d, int p){ Node temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp;} // Return the value at headstatic int peek(Node head){ return (head).data;} // Removes the element with the// highest priority form the liststatic Node pop(Node head){ Node temp = head; (head) = (head).next; return head;} // Function to push according to prioritystatic Node push(Node head, int d, int p){ Node start = (head); // Create new Node Node temp = newNode(d, p); // Special Case: The head of list has lesser // priority than new node. So insert new // node before head node and change head node. if ((head).priority > p) { // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head;} // Function to check is list is emptystatic int isEmpty(Node head){ return ((head) == null)?1:0;} // Driver codepublic static void main(String args[]){ // Create a Priority Queue // 7.4.5.6 Node pq = newNode(4, 1); pq =push(pq, 5, 2); pq =push(pq, 6, 3); pq =push(pq, 7, 0); while (isEmpty(pq)==0) { System.out.printf("%d ", peek(pq)); pq=pop(pq); } }} // This code is contributed// by Arnab Kundu
# Python3 code to implement Priority Queue# using Singly Linked List # Class to create new node which includes# Node Data, and Node Priorityclass PriorityQueueNode: def __init__(self, value, pr): self.data = value self.priority = pr self.next = None # Implementation of Priority Queueclass PriorityQueue: def __init__(self): self.front = None # Method to check Priority Queue is Empty # or not if Empty then it will return True # Otherwise False def isEmpty(self): return True if self.front == None else False # Method to add items in Priority Queue # According to their priority value def push(self, value, priority): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: # Creating a new node and assigning # it to class variable self.front = PriorityQueueNode(value, priority) # Returning 1 for successful execution return 1 else: # Special condition check to see that # first node priority value if self.front.priority > priority: # Creating a new node newNode = PriorityQueueNode(value, priority) # Updating the new node next value newNode.next = self.front # Assigning it to self.front self.front = newNode # Returning 1 for successful execution return 1 else: # Traversing through Queue until it # finds the next smaller priority node temp = self.front while temp.next: # If same priority node found then current # node will come after previous node if priority <= temp.next.priority: break temp = temp.next newNode = PriorityQueueNode(value, priority) newNode.next = temp.next temp.next = newNode # Returning 1 for successful execution return 1 # Method to remove high priority item # from the Priority Queue def pop(self): # Condition check for checking # Priority Queue is empty or not if self.isEmpty() == True: return else: # Removing high priority node from # Priority Queue, and updating front # with next node self.front = self.front.next return 1 # Method to return high priority node # value Not removing it def peek(self): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: return else: return self.front.data # Method to Traverse through Priority # Queue def traverse(self): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: return "Queue is Empty!" else: temp = self.front while temp: print(temp.data, end = " ") temp = temp.next # Driver codeif __name__ == "__main__": # Creating an instance of Priority # Queue, and adding values # 7 -> 4 -> 5 -> 6 pq = PriorityQueue() pq.push(4, 1) pq.push(5, 2) pq.push(6, 3) pq.push(7, 0) # Traversing through Priority Queue pq.traverse() # Removing highest Priority item # for priority queue pq.pop() # This code is contributed by himanshu kanojiya
// C# code to implement Priority Queue// using Linked Listusing System; class GFG{// Nodepublic class Node{ public int data; // Lower values indicate // higher priority public int priority; public Node next;} public static Node node = new Node(); // Function to Create A New Nodepublic static Node newNode(int d, int p){ Node temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp;} // Return the value at headpublic static int peek(Node head){ return (head).data;} // Removes the element with the// highest priority form the listpublic static Node pop(Node head){ Node temp = head; (head) = (head).next; return head;} // Function to push according to prioritypublic static Node push(Node head, int d, int p){ Node start = (head); // Create new Node Node temp = newNode(d, p); // Special Case: The head of list // has lesser priority than new node. // So insert new node before head node // and change head node. if ((head).priority > p) { // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head;} // Function to check is list is emptypublic static int isEmpty(Node head){ return ((head) == null) ? 1 : 0;} // Driver codepublic static void Main(string[] args){ // Create a Priority Queue // 7.4.5.6 Node pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { Console.Write("{0:D} ", peek(pq)); pq = pop(pq); }}} // This code is contributed by Shrikant13
<script> // JavaScript code to implement Priority Queue // using Linked List // Node class Node { // Lower values indicate // higher priority constructor() { this.data = 0; this.priority = 0; this.next = null; } } var node = new Node(); // Function to Create A New Node function newNode(d, p) { var temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp; } // Return the value at head function peek(head) { return head.data; } // Removes the element with the // highest priority form the list function pop(head) { var temp = head; head = head.next; return head; } // Function to push according to priority function push(head, d, p) { var start = head; // Create new Node var temp = newNode(d, p); // Special Case: The head of list // has lesser priority than new node. // So insert new node before head node // and change head node. if (head.priority > p) { // Insert New Node before head temp.next = head; head = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head; } // Function to check is list is empty function isEmpty(head) { return head == null ? 1 : 0; } // Driver code // Create a Priority Queue // 7.4.5.6 var pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { document.write(peek(pq) + " "); pq = pop(pq); } // This code is contributed by rdtank. </script>
7 4 5 6
Time Complexities and Comparison with Binary Heap:
peek() push() pop()
-----------------------------------------
Linked List | O(1) O(n) O(1)
|
Binary Heap | O(1) O(Log n) O(Log n)
andrew1234
shrikanth13
romeosaurabh
nik_3112
shivanisinghss2110
himanshukanojiya
rdtank
sagartomar9927
hosseindehghanipour1998
priority-queue
Linked List
Queue
Linked List
Queue
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Linked List vs Array
Doubly Linked List | Set 1 (Introduction and Insertion)
Detect loop in a linked list
Merge two sorted linked lists
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
|
[
{
"code": null,
"e": 24368,
"s": 24340,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 24414,
"s": 24368,
"text": "Implement Priority Queue using Linked Lists. "
},
{
"code": null,
"e": 24481,
"s": 24414,
"text": "push(): This function is used to insert a new data into the queue."
},
{
"code": null,
"e": 24564,
"s": 24481,
"text": "pop(): This function removes the element with the highest priority from the queue."
},
{
"code": null,
"e": 24687,
"s": 24564,
"text": "peek() / top(): This function is used to get the highest priority element in the queue without removing it from the queue."
},
{
"code": null,
"e": 24802,
"s": 24687,
"text": "Priority Queues can be implemented using common data structures like arrays, linked-lists, heaps and binary trees."
},
{
"code": null,
"e": 24848,
"s": 24802,
"text": "Prerequisites : Linked Lists, Priority Queues"
},
{
"code": null,
"e": 25359,
"s": 24848,
"text": "The list is so created so that the highest priority element is always at the head of the list. The list is arranged in descending order of elements based on their priority. This allow us to remove the highest priority element in O(1) time. To insert an element we must traverse the list and find the proper position to insert the node so that the overall order of the priority queue is maintained. This makes the push() operation takes O(N) time. The pop() and peek() operations are performed in constant time."
},
{
"code": null,
"e": 26016,
"s": 25359,
"text": "Algorithm : PUSH(HEAD, DATA, PRIORITY) Step 1: Create new node with DATA and PRIORITY Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step 5. Step 3: NEW -> NEXT = HEAD Step 4: HEAD = NEW Step 5: Set TEMP to head of the list Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRIORITY Step 7: TEMP = TEMP -> NEXT [END OF LOOP] Step 8: NEW -> NEXT = TEMP -> NEXT Step 9: TEMP -> NEXT = NEW Step 10: EndPOP(HEAD) Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT. Step 3: Free the node at the head of the list Step 4: EndPEEK(HEAD): Step 1: Return HEAD -> DATA Step 2: End"
},
{
"code": null,
"e": 26064,
"s": 26016,
"text": "Below is the implementation of the algorithm : "
},
{
"code": null,
"e": 26068,
"s": 26064,
"text": "C++"
},
{
"code": null,
"e": 26070,
"s": 26068,
"text": "C"
},
{
"code": null,
"e": 26075,
"s": 26070,
"text": "Java"
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Python3"
},
{
"code": null,
"e": 26086,
"s": 26083,
"text": "C#"
},
{
"code": null,
"e": 26097,
"s": 26086,
"text": "Javascript"
},
{
"code": "// C++ code to implement Priority Queue// using Linked List#include <bits/stdc++.h>using namespace std; // Nodetypedef struct node{ int data; // Lower values indicate // higher priority int priority; struct node* next; } Node; // Function to create a new nodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head){ return (*head)->data;} // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has // lesser priority than new node. So // insert newnode before head node // and change head node. if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head){ return (*head) == NULL;} // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { cout << \" \" << peek(&pq); pop(&pq); } return 0;} // This code is contributed by shivanisinghss2110",
"e": 27977,
"s": 26097,
"text": null
},
{
"code": "// C code to implement Priority Queue// using Linked List#include <stdio.h>#include <stdlib.h> // Nodetypedef struct node { int data; // Lower values indicate higher priority int priority; struct node* next; } Node; // Function to Create A New NodeNode* newNode(int d, int p){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = d; temp->priority = p; temp->next = NULL; return temp;} // Return the value at headint peek(Node** head){ return (*head)->data;} // Removes the element with the// highest priority form the listvoid pop(Node** head){ Node* temp = *head; (*head) = (*head)->next; free(temp);} // Function to push according to priorityvoid push(Node** head, int d, int p){ Node* start = (*head); // Create new Node Node* temp = newNode(d, p); // Special Case: The head of list has lesser // priority than new node. So insert new // node before head node and change head node. if ((*head)->priority > p) { // Insert New Node before head temp->next = *head; (*head) = temp; } else { // Traverse the list and find a // position to insert new node while (start->next != NULL && start->next->priority < p) { start = start->next; } // Either at the ends of the list // or at required position temp->next = start->next; start->next = temp; }} // Function to check is list is emptyint isEmpty(Node** head){ return (*head) == NULL;} // Driver codeint main(){ // Create a Priority Queue // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { printf(\"%d \", peek(&pq)); pop(&pq); } return 0;}",
"e": 29752,
"s": 27977,
"text": null
},
{
"code": "// Java code to implement Priority Queue// using Linked Listimport java.util.* ; class Solution{ // Nodestatic class Node { int data; // Lower values indicate higher priority int priority; Node next; } static Node node = new Node(); // Function to Create A New Nodestatic Node newNode(int d, int p){ Node temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp;} // Return the value at headstatic int peek(Node head){ return (head).data;} // Removes the element with the// highest priority form the liststatic Node pop(Node head){ Node temp = head; (head) = (head).next; return head;} // Function to push according to prioritystatic Node push(Node head, int d, int p){ Node start = (head); // Create new Node Node temp = newNode(d, p); // Special Case: The head of list has lesser // priority than new node. So insert new // node before head node and change head node. if ((head).priority > p) { // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head;} // Function to check is list is emptystatic int isEmpty(Node head){ return ((head) == null)?1:0;} // Driver codepublic static void main(String args[]){ // Create a Priority Queue // 7.4.5.6 Node pq = newNode(4, 1); pq =push(pq, 5, 2); pq =push(pq, 6, 3); pq =push(pq, 7, 0); while (isEmpty(pq)==0) { System.out.printf(\"%d \", peek(pq)); pq=pop(pq); } }} // This code is contributed// by Arnab Kundu",
"e": 31705,
"s": 29752,
"text": null
},
{
"code": "# Python3 code to implement Priority Queue# using Singly Linked List # Class to create new node which includes# Node Data, and Node Priorityclass PriorityQueueNode: def __init__(self, value, pr): self.data = value self.priority = pr self.next = None # Implementation of Priority Queueclass PriorityQueue: def __init__(self): self.front = None # Method to check Priority Queue is Empty # or not if Empty then it will return True # Otherwise False def isEmpty(self): return True if self.front == None else False # Method to add items in Priority Queue # According to their priority value def push(self, value, priority): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: # Creating a new node and assigning # it to class variable self.front = PriorityQueueNode(value, priority) # Returning 1 for successful execution return 1 else: # Special condition check to see that # first node priority value if self.front.priority > priority: # Creating a new node newNode = PriorityQueueNode(value, priority) # Updating the new node next value newNode.next = self.front # Assigning it to self.front self.front = newNode # Returning 1 for successful execution return 1 else: # Traversing through Queue until it # finds the next smaller priority node temp = self.front while temp.next: # If same priority node found then current # node will come after previous node if priority <= temp.next.priority: break temp = temp.next newNode = PriorityQueueNode(value, priority) newNode.next = temp.next temp.next = newNode # Returning 1 for successful execution return 1 # Method to remove high priority item # from the Priority Queue def pop(self): # Condition check for checking # Priority Queue is empty or not if self.isEmpty() == True: return else: # Removing high priority node from # Priority Queue, and updating front # with next node self.front = self.front.next return 1 # Method to return high priority node # value Not removing it def peek(self): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: return else: return self.front.data # Method to Traverse through Priority # Queue def traverse(self): # Condition check for checking Priority # Queue is empty or not if self.isEmpty() == True: return \"Queue is Empty!\" else: temp = self.front while temp: print(temp.data, end = \" \") temp = temp.next # Driver codeif __name__ == \"__main__\": # Creating an instance of Priority # Queue, and adding values # 7 -> 4 -> 5 -> 6 pq = PriorityQueue() pq.push(4, 1) pq.push(5, 2) pq.push(6, 3) pq.push(7, 0) # Traversing through Priority Queue pq.traverse() # Removing highest Priority item # for priority queue pq.pop() # This code is contributed by himanshu kanojiya",
"e": 35801,
"s": 31705,
"text": null
},
{
"code": "// C# code to implement Priority Queue// using Linked Listusing System; class GFG{// Nodepublic class Node{ public int data; // Lower values indicate // higher priority public int priority; public Node next;} public static Node node = new Node(); // Function to Create A New Nodepublic static Node newNode(int d, int p){ Node temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp;} // Return the value at headpublic static int peek(Node head){ return (head).data;} // Removes the element with the// highest priority form the listpublic static Node pop(Node head){ Node temp = head; (head) = (head).next; return head;} // Function to push according to prioritypublic static Node push(Node head, int d, int p){ Node start = (head); // Create new Node Node temp = newNode(d, p); // Special Case: The head of list // has lesser priority than new node. // So insert new node before head node // and change head node. if ((head).priority > p) { // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head;} // Function to check is list is emptypublic static int isEmpty(Node head){ return ((head) == null) ? 1 : 0;} // Driver codepublic static void Main(string[] args){ // Create a Priority Queue // 7.4.5.6 Node pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { Console.Write(\"{0:D} \", peek(pq)); pq = pop(pq); }}} // This code is contributed by Shrikant13",
"e": 37780,
"s": 35801,
"text": null
},
{
"code": "<script> // JavaScript code to implement Priority Queue // using Linked List // Node class Node { // Lower values indicate // higher priority constructor() { this.data = 0; this.priority = 0; this.next = null; } } var node = new Node(); // Function to Create A New Node function newNode(d, p) { var temp = new Node(); temp.data = d; temp.priority = p; temp.next = null; return temp; } // Return the value at head function peek(head) { return head.data; } // Removes the element with the // highest priority form the list function pop(head) { var temp = head; head = head.next; return head; } // Function to push according to priority function push(head, d, p) { var start = head; // Create new Node var temp = newNode(d, p); // Special Case: The head of list // has lesser priority than new node. // So insert new node before head node // and change head node. if (head.priority > p) { // Insert New Node before head temp.next = head; head = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority < p) { start = start.next; } // Either at the ends of the list // or at required position temp.next = start.next; start.next = temp; } return head; } // Function to check is list is empty function isEmpty(head) { return head == null ? 1 : 0; } // Driver code // Create a Priority Queue // 7.4.5.6 var pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { document.write(peek(pq) + \" \"); pq = pop(pq); } // This code is contributed by rdtank. </script>",
"e": 39916,
"s": 37780,
"text": null
},
{
"code": null,
"e": 39924,
"s": 39916,
"text": "7 4 5 6"
},
{
"code": null,
"e": 39978,
"s": 39926,
"text": "Time Complexities and Comparison with Binary Heap: "
},
{
"code": null,
"e": 40160,
"s": 39978,
"text": " peek() push() pop()\n-----------------------------------------\nLinked List | O(1) O(n) O(1)\n |\nBinary Heap | O(1) O(Log n) O(Log n)"
},
{
"code": null,
"e": 40171,
"s": 40160,
"text": "andrew1234"
},
{
"code": null,
"e": 40183,
"s": 40171,
"text": "shrikanth13"
},
{
"code": null,
"e": 40196,
"s": 40183,
"text": "romeosaurabh"
},
{
"code": null,
"e": 40205,
"s": 40196,
"text": "nik_3112"
},
{
"code": null,
"e": 40224,
"s": 40205,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 40241,
"s": 40224,
"text": "himanshukanojiya"
},
{
"code": null,
"e": 40248,
"s": 40241,
"text": "rdtank"
},
{
"code": null,
"e": 40263,
"s": 40248,
"text": "sagartomar9927"
},
{
"code": null,
"e": 40287,
"s": 40263,
"text": "hosseindehghanipour1998"
},
{
"code": null,
"e": 40302,
"s": 40287,
"text": "priority-queue"
},
{
"code": null,
"e": 40314,
"s": 40302,
"text": "Linked List"
},
{
"code": null,
"e": 40320,
"s": 40314,
"text": "Queue"
},
{
"code": null,
"e": 40332,
"s": 40320,
"text": "Linked List"
},
{
"code": null,
"e": 40338,
"s": 40332,
"text": "Queue"
},
{
"code": null,
"e": 40353,
"s": 40338,
"text": "priority-queue"
},
{
"code": null,
"e": 40451,
"s": 40353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40470,
"s": 40451,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 40491,
"s": 40470,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 40547,
"s": 40491,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 40576,
"s": 40547,
"text": "Detect loop in a linked list"
},
{
"code": null,
"e": 40606,
"s": 40576,
"text": "Merge two sorted linked lists"
},
{
"code": null,
"e": 40646,
"s": 40606,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 40680,
"s": 40646,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 40704,
"s": 40680,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 40720,
"s": 40704,
"text": "Queue in Python"
}
] |
AWT Graphics Class
|
The Graphics class is the abstract super class for all graphics contexts which allow an application to draw onto components that can be realized on various devices, or onto off-screen images as well.
A Graphics object encapsulates all state information required for the basic rendering operations that Java supports. State information includes the following properties.
The Component object on which to draw.
The Component object on which to draw.
A translation origin for rendering and clipping coordinates.
A translation origin for rendering and clipping coordinates.
The current clip.
The current clip.
The current color.
The current color.
The current font.
The current font.
The current logical pixel operation function.
The current logical pixel operation function.
The current XOR alternation color
The current XOR alternation color
Following is the declaration for java.awt.Graphics class:
public abstract class Graphics
extends Object
Graphics() ()
Constructs a new Graphics object.
abstract void clearRect(int x, int y, int width, int height)
Clears the specified rectangle by filling it with the background color of the current drawing surface.
abstract void clipRect(int x, int y, int width, int height)
Intersects the current clip with the specified rectangle.
abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy.
abstract Graphics create()
Creates a new Graphics object that is a copy of this Graphics object.
Graphics create(int x, int y, int width, int height)
Creates a new Graphics object based on this Graphics object, but with a new translation and clip area.
abstract void dispose()
Disposes of this graphics context and releases any system resources that it is using.
void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle.
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x, int y)
Draws the text given by the specified byte array, using this graphics context's current font and color.
void drawChars(char[] data, int offset, int length, int x, int y)
Draws the text given by the specified character array, using this graphics context's current font and color.
abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is currently available.
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
Draws as much of the specified image as is currently available.
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
abstract void drawOval(int x, int y, int width, int height)
Draws the outline of an oval.
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
Draws a closed polygon defined by arrays of x and y coordinates.
void drawPolygon(Polygon p)
Draws the outline of a polygon defined by the specified Polygon object.
abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
Draws a sequence of connected lines defined by arrays of x and y coordinates.
void drawRect(int x, int y, int width, int height)
Draws the outline of the specified rectangle.
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
abstract void drawString(AttributedCharacterIterator iterator, int x, int y)
Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.
abstract void drawString(String str, int x, int y)
Draws the text given by the specified string, using this graphics context's current font and color.
void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color.
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Fills a closed polygon defined by arrays of x and y coordinates.
void fillPolygon(Polygon p)
Fills the polygon defined by the specified Polygon object with the graphics context's current color.
abstract void fillRect(int x, int y, int width, int height)
Fills the specified rectangle.
abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
Fills the specified rounded corner rectangle with the current color.
void finalize()
Disposes of this graphics context once it is no longer referenced.
abstract Shape getClip()
Gets the current clipping area.
abstract Rectangle getClipBounds()
Returns the bounding rectangle of the current clipping area.
Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the current clipping area.
Rectangle getClipRect()
Deprecated. As of JDK version 1.1, replaced by getClipBounds().
abstract Color getColor()
Gets this graphics context's current color.
abstract Font getFont()
Gets the current font.
FontMetrics getFontMetrics()
Gets the font metrics of the current font.
abstract FontMetrics getFontMetrics(Font f)
Gets the font metrics for the specified font.
boolean hitClip(int x, int y, int width, int height)
Returns true if the specified rectangular area might intersect the current clipping area.
abstract void setClip(int x, int y, int width, int height)
Sets the current clip to the rectangle specified by the given coordinates.
abstract void setClip(Shape clip)
Sets the current clipping area to an arbitrary clip shape.
abstract void setColor(Color c)
Sets this graphics context's current color to the specified color.
abstract void setFont(Font font)
Sets this graphics context's font to the specified font.
abstract void setPaintMode()
Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color.
abstract void setXORMode(Color c1)
Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color.
String toString()
Returns a String object representing this Graphics object's value.
abstract void translate(int x, int y)
Translates the origin of the graphics context to the point (x, y) in the current coordinate system.
This class inherits methods from the following classes:
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class AWTGraphicsDemo extends Frame {
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
public static void main(String[] args){
AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();
awtGraphicsDemo.setVisible(true);
}
private void prepareGUI(){
setSize(400,400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}
@Override
public void paint(Graphics g) {
g.setColor(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 24);
g.setFont(font);
g.drawString("Welcome to TutorialsPoint", 50, 150);
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1947,
"s": 1747,
"text": "The Graphics class is the abstract super class for all graphics contexts which allow an application to draw onto components that can be realized on various devices, or onto off-screen images as well."
},
{
"code": null,
"e": 2117,
"s": 1947,
"text": "A Graphics object encapsulates all state information required for the basic rendering operations that Java supports. State information includes the following properties."
},
{
"code": null,
"e": 2156,
"s": 2117,
"text": "The Component object on which to draw."
},
{
"code": null,
"e": 2195,
"s": 2156,
"text": "The Component object on which to draw."
},
{
"code": null,
"e": 2256,
"s": 2195,
"text": "A translation origin for rendering and clipping coordinates."
},
{
"code": null,
"e": 2317,
"s": 2256,
"text": "A translation origin for rendering and clipping coordinates."
},
{
"code": null,
"e": 2335,
"s": 2317,
"text": "The current clip."
},
{
"code": null,
"e": 2353,
"s": 2335,
"text": "The current clip."
},
{
"code": null,
"e": 2372,
"s": 2353,
"text": "The current color."
},
{
"code": null,
"e": 2391,
"s": 2372,
"text": "The current color."
},
{
"code": null,
"e": 2409,
"s": 2391,
"text": "The current font."
},
{
"code": null,
"e": 2427,
"s": 2409,
"text": "The current font."
},
{
"code": null,
"e": 2473,
"s": 2427,
"text": "The current logical pixel operation function."
},
{
"code": null,
"e": 2519,
"s": 2473,
"text": "The current logical pixel operation function."
},
{
"code": null,
"e": 2554,
"s": 2519,
"text": "The current XOR alternation color "
},
{
"code": null,
"e": 2589,
"s": 2554,
"text": "The current XOR alternation color "
},
{
"code": null,
"e": 2647,
"s": 2589,
"text": "Following is the declaration for java.awt.Graphics class:"
},
{
"code": null,
"e": 2696,
"s": 2647,
"text": "public abstract class Graphics\n extends Object"
},
{
"code": null,
"e": 2711,
"s": 2696,
"text": "Graphics() () "
},
{
"code": null,
"e": 2745,
"s": 2711,
"text": "Constructs a new Graphics object."
},
{
"code": null,
"e": 2806,
"s": 2745,
"text": "abstract void clearRect(int x, int y, int width, int height)"
},
{
"code": null,
"e": 2909,
"s": 2806,
"text": "Clears the specified rectangle by filling it with the background color of the current drawing surface."
},
{
"code": null,
"e": 2969,
"s": 2909,
"text": "abstract void clipRect(int x, int y, int width, int height)"
},
{
"code": null,
"e": 3027,
"s": 2969,
"text": "Intersects the current clip with the specified rectangle."
},
{
"code": null,
"e": 3103,
"s": 3027,
"text": "abstract void copyArea(int x, int y, int width, int height, int dx, int dy)"
},
{
"code": null,
"e": 3173,
"s": 3103,
"text": "Copies an area of the component by a distance specified by dx and dy."
},
{
"code": null,
"e": 3202,
"s": 3173,
"text": "abstract Graphics\tcreate() "
},
{
"code": null,
"e": 3272,
"s": 3202,
"text": "Creates a new Graphics object that is a copy of this Graphics object."
},
{
"code": null,
"e": 3325,
"s": 3272,
"text": "Graphics create(int x, int y, int width, int height)"
},
{
"code": null,
"e": 3428,
"s": 3325,
"text": "Creates a new Graphics object based on this Graphics object, but with a new translation and clip area."
},
{
"code": null,
"e": 3454,
"s": 3428,
"text": "abstract void dispose() "
},
{
"code": null,
"e": 3540,
"s": 3454,
"text": "Disposes of this graphics context and releases any system resources that it is using."
},
{
"code": null,
"e": 3611,
"s": 3540,
"text": "void draw3DRect(int x, int y, int width, int height, boolean raised) "
},
{
"code": null,
"e": 3671,
"s": 3611,
"text": "Draws a 3-D highlighted outline of the specified rectangle."
},
{
"code": null,
"e": 3760,
"s": 3671,
"text": "abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)"
},
{
"code": null,
"e": 3844,
"s": 3760,
"text": "Draws the outline of a circular or elliptical arc covering the specified rectangle."
},
{
"code": null,
"e": 3912,
"s": 3844,
"text": "void drawBytes(byte[] data, int offset, int length, int x, int y) "
},
{
"code": null,
"e": 4016,
"s": 3912,
"text": "Draws the text given by the specified byte array, using this graphics context's current font and color."
},
{
"code": null,
"e": 4084,
"s": 4016,
"text": "void drawChars(char[] data, int offset, int length, int x, int y) "
},
{
"code": null,
"e": 4193,
"s": 4084,
"text": "Draws the text given by the specified character array, using this graphics context's current font and color."
},
{
"code": null,
"e": 4284,
"s": 4193,
"text": "abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)"
},
{
"code": null,
"e": 4348,
"s": 4284,
"text": "Draws as much of the specified image as is currently available."
},
{
"code": null,
"e": 4424,
"s": 4348,
"text": "abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)"
},
{
"code": null,
"e": 4488,
"s": 4424,
"text": "Draws as much of the specified image as is currently available."
},
{
"code": null,
"e": 4603,
"s": 4488,
"text": "abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) "
},
{
"code": null,
"e": 4706,
"s": 4603,
"text": "Draws as much of the specified image as has already been scaled to fit inside the specified rectangle."
},
{
"code": null,
"e": 4806,
"s": 4706,
"text": "abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) "
},
{
"code": null,
"e": 4909,
"s": 4806,
"text": "Draws as much of the specified image as has already been scaled to fit inside the specified rectangle."
},
{
"code": null,
"e": 5059,
"s": 4909,
"text": "abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) "
},
{
"code": null,
"e": 5237,
"s": 5059,
"text": "Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface."
},
{
"code": null,
"e": 5373,
"s": 5237,
"text": "abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) "
},
{
"code": null,
"e": 5551,
"s": 5373,
"text": "Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface."
},
{
"code": null,
"e": 5606,
"s": 5551,
"text": "abstract void drawLine(int x1, int y1, int x2, int y2)"
},
{
"code": null,
"e": 5732,
"s": 5606,
"text": "Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system."
},
{
"code": null,
"e": 5794,
"s": 5732,
"text": "abstract void drawOval(int x, int y, int width, int height) "
},
{
"code": null,
"e": 5824,
"s": 5794,
"text": "Draws the outline of an oval."
},
{
"code": null,
"e": 5895,
"s": 5824,
"text": "abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) "
},
{
"code": null,
"e": 5960,
"s": 5895,
"text": "Draws a closed polygon defined by arrays of x and y coordinates."
},
{
"code": null,
"e": 5990,
"s": 5960,
"text": "void drawPolygon(Polygon p) "
},
{
"code": null,
"e": 6062,
"s": 5990,
"text": "Draws the outline of a polygon defined by the specified Polygon object."
},
{
"code": null,
"e": 6134,
"s": 6062,
"text": "abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) "
},
{
"code": null,
"e": 6212,
"s": 6134,
"text": "Draws a sequence of connected lines defined by arrays of x and y coordinates."
},
{
"code": null,
"e": 6265,
"s": 6212,
"text": "void drawRect(int x, int y, int width, int height) "
},
{
"code": null,
"e": 6311,
"s": 6265,
"text": "Draws the outline of the specified rectangle."
},
{
"code": null,
"e": 6407,
"s": 6311,
"text": "abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) "
},
{
"code": null,
"e": 6495,
"s": 6407,
"text": "Draws an outlined round-cornered rectangle using this graphics context's current color."
},
{
"code": null,
"e": 6574,
"s": 6495,
"text": "abstract void drawString(AttributedCharacterIterator iterator, int x, int y) "
},
{
"code": null,
"e": 6706,
"s": 6574,
"text": "Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class."
},
{
"code": null,
"e": 6759,
"s": 6706,
"text": "abstract void drawString(String str, int x, int y) "
},
{
"code": null,
"e": 6859,
"s": 6759,
"text": "Draws the text given by the specified string, using this graphics context's current font and color."
},
{
"code": null,
"e": 6930,
"s": 6859,
"text": "void fill3DRect(int x, int y, int width, int height, boolean raised) "
},
{
"code": null,
"e": 6996,
"s": 6930,
"text": "Paints a 3-D highlighted rectangle filled with the current color."
},
{
"code": null,
"e": 7086,
"s": 6996,
"text": "abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) "
},
{
"code": null,
"e": 7155,
"s": 7086,
"text": "Fills a circular or elliptical arc covering the specified rectangle."
},
{
"code": null,
"e": 7217,
"s": 7155,
"text": "abstract void fillOval(int x, int y, int width, int height) "
},
{
"code": null,
"e": 7290,
"s": 7217,
"text": "Fills an oval bounded by the specified rectangle with the current color."
},
{
"code": null,
"e": 7361,
"s": 7290,
"text": "abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) "
},
{
"code": null,
"e": 7426,
"s": 7361,
"text": "Fills a closed polygon defined by arrays of x and y coordinates."
},
{
"code": null,
"e": 7456,
"s": 7426,
"text": "void fillPolygon(Polygon p) "
},
{
"code": null,
"e": 7557,
"s": 7456,
"text": "Fills the polygon defined by the specified Polygon object with the graphics context's current color."
},
{
"code": null,
"e": 7619,
"s": 7557,
"text": "abstract void fillRect(int x, int y, int width, int height) "
},
{
"code": null,
"e": 7650,
"s": 7619,
"text": "Fills the specified rectangle."
},
{
"code": null,
"e": 7746,
"s": 7650,
"text": "abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) "
},
{
"code": null,
"e": 7815,
"s": 7746,
"text": "Fills the specified rounded corner rectangle with the current color."
},
{
"code": null,
"e": 7833,
"s": 7815,
"text": "void finalize() "
},
{
"code": null,
"e": 7900,
"s": 7833,
"text": "Disposes of this graphics context once it is no longer referenced."
},
{
"code": null,
"e": 7927,
"s": 7900,
"text": "abstract Shape\tgetClip() "
},
{
"code": null,
"e": 7959,
"s": 7927,
"text": "Gets the current clipping area."
},
{
"code": null,
"e": 7996,
"s": 7959,
"text": "abstract Rectangle\tgetClipBounds() "
},
{
"code": null,
"e": 8057,
"s": 7996,
"text": "Returns the bounding rectangle of the current clipping area."
},
{
"code": null,
"e": 8095,
"s": 8057,
"text": "Rectangle getClipBounds(Rectangle r) "
},
{
"code": null,
"e": 8157,
"s": 8095,
"text": " Returns the bounding rectangle of the current clipping area."
},
{
"code": null,
"e": 8183,
"s": 8157,
"text": "Rectangle getClipRect() "
},
{
"code": null,
"e": 8247,
"s": 8183,
"text": "Deprecated. As of JDK version 1.1, replaced by getClipBounds()."
},
{
"code": null,
"e": 8275,
"s": 8247,
"text": "abstract Color\tgetColor() "
},
{
"code": null,
"e": 8319,
"s": 8275,
"text": "Gets this graphics context's current color."
},
{
"code": null,
"e": 8345,
"s": 8319,
"text": "abstract Font\tgetFont() "
},
{
"code": null,
"e": 8368,
"s": 8345,
"text": "Gets the current font."
},
{
"code": null,
"e": 8399,
"s": 8368,
"text": "FontMetrics getFontMetrics() "
},
{
"code": null,
"e": 8442,
"s": 8399,
"text": "Gets the font metrics of the current font."
},
{
"code": null,
"e": 8488,
"s": 8442,
"text": "abstract FontMetrics\tgetFontMetrics(Font f) "
},
{
"code": null,
"e": 8534,
"s": 8488,
"text": "Gets the font metrics for the specified font."
},
{
"code": null,
"e": 8589,
"s": 8534,
"text": "boolean hitClip(int x, int y, int width, int height) "
},
{
"code": null,
"e": 8679,
"s": 8589,
"text": "Returns true if the specified rectangular area might intersect the current clipping area."
},
{
"code": null,
"e": 8740,
"s": 8679,
"text": "abstract void setClip(int x, int y, int width, int height) "
},
{
"code": null,
"e": 8815,
"s": 8740,
"text": "Sets the current clip to the rectangle specified by the given coordinates."
},
{
"code": null,
"e": 8851,
"s": 8815,
"text": "abstract void setClip(Shape clip) "
},
{
"code": null,
"e": 8910,
"s": 8851,
"text": "Sets the current clipping area to an arbitrary clip shape."
},
{
"code": null,
"e": 8944,
"s": 8910,
"text": "abstract void setColor(Color c) "
},
{
"code": null,
"e": 9011,
"s": 8944,
"text": "Sets this graphics context's current color to the specified color."
},
{
"code": null,
"e": 9046,
"s": 9011,
"text": "abstract void setFont(Font font) "
},
{
"code": null,
"e": 9103,
"s": 9046,
"text": "Sets this graphics context's font to the specified font."
},
{
"code": null,
"e": 9134,
"s": 9103,
"text": "abstract void setPaintMode() "
},
{
"code": null,
"e": 9252,
"s": 9134,
"text": "Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color."
},
{
"code": null,
"e": 9289,
"s": 9252,
"text": "abstract void setXORMode(Color c1) "
},
{
"code": null,
"e": 9422,
"s": 9289,
"text": "Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color."
},
{
"code": null,
"e": 9442,
"s": 9422,
"text": "String\ttoString() "
},
{
"code": null,
"e": 9509,
"s": 9442,
"text": "Returns a String object representing this Graphics object's value."
},
{
"code": null,
"e": 9549,
"s": 9509,
"text": "abstract void translate(int x, int y) "
},
{
"code": null,
"e": 9649,
"s": 9549,
"text": "Translates the origin of the graphics context to the point (x, y) in the current coordinate system."
},
{
"code": null,
"e": 9705,
"s": 9649,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 9722,
"s": 9705,
"text": "java.lang.Object"
},
{
"code": null,
"e": 9739,
"s": 9722,
"text": "java.lang.Object"
},
{
"code": null,
"e": 9853,
"s": 9739,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 10706,
"s": 9853,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.awt.geom.*;\n\npublic class AWTGraphicsDemo extends Frame {\n \n public AWTGraphicsDemo(){\n super(\"Java AWT Examples\");\n prepareGUI();\n }\n\n public static void main(String[] args){\n AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo(); \n awtGraphicsDemo.setVisible(true);\n }\n\n private void prepareGUI(){\n setSize(400,400);\n addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n } \n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.GRAY);\n Font font = new Font(\"Serif\", Font.PLAIN, 24);\n g.setFont(font);\n g.drawString(\"Welcome to TutorialsPoint\", 50, 150); \n }\n}"
},
{
"code": null,
"e": 10797,
"s": 10706,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 10854,
"s": 10797,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AWTGraphicsDemo.java"
},
{
"code": null,
"e": 10951,
"s": 10854,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 11002,
"s": 10951,
"text": "D:\\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo"
},
{
"code": null,
"e": 11030,
"s": 11002,
"text": "Verify the following output"
},
{
"code": null,
"e": 11063,
"s": 11030,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 11071,
"s": 11063,
"text": " EduOLC"
},
{
"code": null,
"e": 11078,
"s": 11071,
"text": " Print"
},
{
"code": null,
"e": 11089,
"s": 11078,
"text": " Add Notes"
}
] |
How to create an empty plot using ggplot2 in R?
|
The two most easy ways to create an empty plot using ggplot2 are using geom_blank function and also adding the theme_bw along with the geom_blank. The geom_blank will create an empty plot with white gridlines and grey background, on the other hand, addition of theme_bw will create the empty plot with grey gridlines and white background.
Consider the below data frame:
Live Demo
> set.seed(151)
> x<-rnorm(20)
> y<-rnorm(20,1,0.5)
> df<-data.frame(x,y)
> df
x y
1 -0.05153895 0.3139643
2 0.76573738 0.1816184
3 -0.14673959 0.8201743
4 -0.11318581 1.6005576
5 -0.39551140 0.6770630
6 0.78227595 0.7446956
7 -1.39747811 0.7004385
8 -1.01883832 1.2728014
9 0.22947586 0.7543531
10 0.67217297 1.0957678
11 -0.48455178 0.7207362
12 0.56060896 1.4613498
13 0.06615648 1.5769990
14 -1.34987612 0.3137949
15 -0.24291581 1.6450906
16 -1.23674102 1.5774510
17 -1.47467765 1.7228397
18 2.43715892 1.1305064
19 0.67352581 1.9645730
20 0.31003951 0.7000570
Loading ggplot2 package and creating an empty plot with grey background:
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_blank()
Creating an empty plot with white background:
> ggplot(df,aes(x,y))+geom_blank()+theme_bw()
|
[
{
"code": null,
"e": 1401,
"s": 1062,
"text": "The two most easy ways to create an empty plot using ggplot2 are using geom_blank function and also adding the theme_bw along with the geom_blank. The geom_blank will create an empty plot with white gridlines and grey background, on the other hand, addition of theme_bw will create the empty plot with grey gridlines and white background."
},
{
"code": null,
"e": 1432,
"s": 1401,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1442,
"s": 1432,
"text": "Live Demo"
},
{
"code": null,
"e": 1521,
"s": 1442,
"text": "> set.seed(151)\n> x<-rnorm(20)\n> y<-rnorm(20,1,0.5)\n> df<-data.frame(x,y)\n> df"
},
{
"code": null,
"e": 2038,
"s": 1521,
"text": " x y\n1 -0.05153895 0.3139643\n2 0.76573738 0.1816184\n3 -0.14673959 0.8201743\n4 -0.11318581 1.6005576\n5 -0.39551140 0.6770630\n6 0.78227595 0.7446956\n7 -1.39747811 0.7004385\n8 -1.01883832 1.2728014\n9 0.22947586 0.7543531\n10 0.67217297 1.0957678\n11 -0.48455178 0.7207362\n12 0.56060896 1.4613498\n13 0.06615648 1.5769990\n14 -1.34987612 0.3137949\n15 -0.24291581 1.6450906\n16 -1.23674102 1.5774510\n17 -1.47467765 1.7228397\n18 2.43715892 1.1305064\n19 0.67352581 1.9645730\n20 0.31003951 0.7000570"
},
{
"code": null,
"e": 2111,
"s": 2038,
"text": "Loading ggplot2 package and creating an empty plot with grey background:"
},
{
"code": null,
"e": 2165,
"s": 2111,
"text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_blank()"
},
{
"code": null,
"e": 2211,
"s": 2165,
"text": "Creating an empty plot with white background:"
},
{
"code": null,
"e": 2257,
"s": 2211,
"text": "> ggplot(df,aes(x,y))+geom_blank()+theme_bw()"
}
] |
TimeSpan.Subtract() Method in C#
|
The TimeSpan.Subtract() method in C# is used to return a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance.
The syntax is as follows −
public TimeSpan Subtract (TimeSpan span);
Above, the parameter span is the time interval to be subtracted.
Let us now see an example −
Live Demo
using System;
public class Demo {
public static void Main(){
TimeSpan span1 = TimeSpan.FromTicks(1);
TimeSpan span2 = new TimeSpan(1);
TimeSpan span3 = TimeSpan.FromHours(1);
TimeSpan span4 = TimeSpan.FromMilliseconds(1);
TimeSpan span5 = TimeSpan.FromMinutes(1);
TimeSpan span6 = TimeSpan.FromMinutes(1);
Console.WriteLine("TimeSpan1 = "+span1);
Console.WriteLine("TimeSpan2 = "+span2);
Console.WriteLine("TimeSpan3 = "+span3);
Console.WriteLine("TimeSpan4 = "+span4);
Console.WriteLine("TimeSpan5 = "+span5);
Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3));
Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4));
Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5));
TimeSpan res1 = span1.Subtract(span2);
TimeSpan res2 = span2.Subtract(span2);
Console.WriteLine("Result = "+res1);
Console.WriteLine("Result = "+res2);
}
}
This will produce the following output −
TimeSpan1 = 00:00:00.0000001
TimeSpan2 = 00:00:00.0000001
TimeSpan3 = 01:00:00
TimeSpan4 = 00:00:00.0010000
TimeSpan5 = 00:01:00
Result (Comparison of span1 and span2) = 0
Result (Comparison of span2 and span3) = -1
Result (Comparison of span1 and span3) = -1
Result (Comparison of span3 and span4) = 1
Result (Comparison of span4 and span5) = -1
Result = 00:00:00
Result = 00:00:00
Let us now see another example −
Live Demo
using System;
public class Demo {
public static void Main(){
TimeSpan span1 = TimeSpan.FromTicks(1500);
TimeSpan span2 = new TimeSpan(2, 40, 55);
TimeSpan span3 = TimeSpan.FromHours(5);
TimeSpan span4 = TimeSpan.FromMilliseconds(1000);
TimeSpan span5 = TimeSpan.FromMinutes(50);
TimeSpan span6 = TimeSpan.FromMinutes(50);
Console.WriteLine("TimeSpan1 = "+span1);
Console.WriteLine("TimeSpan2 = "+span2);
Console.WriteLine("TimeSpan3 = "+span3);
Console.WriteLine("TimeSpan4 = "+span4);
Console.WriteLine("TimeSpan5 = "+span5);
Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
Console.WriteLine("Result (Comparison of span2 and span3) = "+TimeSpan.Compare(span2, span3));
Console.WriteLine("Result (Comparison of span1 and span3) = "+TimeSpan.Compare(span1, span3));
Console.WriteLine("Result (Comparison of span3 and span4) = "+TimeSpan.Compare(span3, span4));
Console.WriteLine("Result (Comparison of span4 and span5) = "+TimeSpan.Compare(span4, span5));
TimeSpan res1 = span1.Subtract(span2);
TimeSpan res2 = span2.Subtract(span2);
Console.WriteLine("Result = "+res1);
Console.WriteLine("Result = "+res2);
}
}
This will produce the following output −
TimeSpan1 = 00:00:00.0001500
TimeSpan2 = 02:40:55
TimeSpan3 = 05:00:00
TimeSpan4 = 00:00:01
TimeSpan5 = 00:50:00
Result (Comparison of span1 and span2) = -1
Result (Comparison of span2 and span3) = -1
Result (Comparison of span1 and span3) = -1
Result (Comparison of span3 and span4) = 1
Result (Comparison of span4 and span5) = -1
Result = -02:40:54.9998500
Result = 00:00:00
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "The TimeSpan.Subtract() method in C# is used to return a new TimeSpan object whose value is the difference between the specified TimeSpan object and this instance."
},
{
"code": null,
"e": 1253,
"s": 1226,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1295,
"s": 1253,
"text": "public TimeSpan Subtract (TimeSpan span);"
},
{
"code": null,
"e": 1360,
"s": 1295,
"text": "Above, the parameter span is the time interval to be subtracted."
},
{
"code": null,
"e": 1388,
"s": 1360,
"text": "Let us now see an example −"
},
{
"code": null,
"e": 1399,
"s": 1388,
"text": " Live Demo"
},
{
"code": null,
"e": 2667,
"s": 1399,
"text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = TimeSpan.FromTicks(1);\n TimeSpan span2 = new TimeSpan(1);\n TimeSpan span3 = TimeSpan.FromHours(1);\n TimeSpan span4 = TimeSpan.FromMilliseconds(1);\n TimeSpan span5 = TimeSpan.FromMinutes(1);\n TimeSpan span6 = TimeSpan.FromMinutes(1);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"TimeSpan4 = \"+span4);\n Console.WriteLine(\"TimeSpan5 = \"+span5);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n Console.WriteLine(\"Result (Comparison of span2 and span3) = \"+TimeSpan.Compare(span2, span3));\n Console.WriteLine(\"Result (Comparison of span1 and span3) = \"+TimeSpan.Compare(span1, span3));\n Console.WriteLine(\"Result (Comparison of span3 and span4) = \"+TimeSpan.Compare(span3, span4));\n Console.WriteLine(\"Result (Comparison of span4 and span5) = \"+TimeSpan.Compare(span4, span5));\n TimeSpan res1 = span1.Subtract(span2);\n TimeSpan res2 = span2.Subtract(span2);\n Console.WriteLine(\"Result = \"+res1);\n Console.WriteLine(\"Result = \"+res2);\n }\n}"
},
{
"code": null,
"e": 2708,
"s": 2667,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3091,
"s": 2708,
"text": "TimeSpan1 = 00:00:00.0000001\nTimeSpan2 = 00:00:00.0000001\nTimeSpan3 = 01:00:00\nTimeSpan4 = 00:00:00.0010000\nTimeSpan5 = 00:01:00\nResult (Comparison of span1 and span2) = 0\nResult (Comparison of span2 and span3) = -1\nResult (Comparison of span1 and span3) = -1\nResult (Comparison of span3 and span4) = 1\nResult (Comparison of span4 and span5) = -1\nResult = 00:00:00\nResult = 00:00:00"
},
{
"code": null,
"e": 3124,
"s": 3091,
"text": "Let us now see another example −"
},
{
"code": null,
"e": 3135,
"s": 3124,
"text": " Live Demo"
},
{
"code": null,
"e": 4419,
"s": 3135,
"text": "using System;\npublic class Demo {\n public static void Main(){\n TimeSpan span1 = TimeSpan.FromTicks(1500);\n TimeSpan span2 = new TimeSpan(2, 40, 55);\n TimeSpan span3 = TimeSpan.FromHours(5);\n TimeSpan span4 = TimeSpan.FromMilliseconds(1000);\n TimeSpan span5 = TimeSpan.FromMinutes(50);\n TimeSpan span6 = TimeSpan.FromMinutes(50);\n Console.WriteLine(\"TimeSpan1 = \"+span1);\n Console.WriteLine(\"TimeSpan2 = \"+span2);\n Console.WriteLine(\"TimeSpan3 = \"+span3);\n Console.WriteLine(\"TimeSpan4 = \"+span4);\n Console.WriteLine(\"TimeSpan5 = \"+span5);\n Console.WriteLine(\"Result (Comparison of span1 and span2) = \"+TimeSpan.Compare(span1, span2));\n Console.WriteLine(\"Result (Comparison of span2 and span3) = \"+TimeSpan.Compare(span2, span3));\n Console.WriteLine(\"Result (Comparison of span1 and span3) = \"+TimeSpan.Compare(span1, span3));\n Console.WriteLine(\"Result (Comparison of span3 and span4) = \"+TimeSpan.Compare(span3, span4));\n Console.WriteLine(\"Result (Comparison of span4 and span5) = \"+TimeSpan.Compare(span4, span5));\n TimeSpan res1 = span1.Subtract(span2);\n TimeSpan res2 = span2.Subtract(span2);\n Console.WriteLine(\"Result = \"+res1);\n Console.WriteLine(\"Result = \"+res2);\n }\n}"
},
{
"code": null,
"e": 4460,
"s": 4419,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4837,
"s": 4460,
"text": "TimeSpan1 = 00:00:00.0001500\nTimeSpan2 = 02:40:55\nTimeSpan3 = 05:00:00\nTimeSpan4 = 00:00:01\nTimeSpan5 = 00:50:00\nResult (Comparison of span1 and span2) = -1\nResult (Comparison of span2 and span3) = -1\nResult (Comparison of span1 and span3) = -1\nResult (Comparison of span3 and span4) = 1\nResult (Comparison of span4 and span5) = -1\nResult = -02:40:54.9998500\nResult = 00:00:00"
}
] |
Double compare() Method in Java with Examples - GeeksforGeeks
|
22 Jun, 2021
The compare() method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.
Syntax:
public static int compare(double d1, double d2)
Parameters: The function accepts two parameters:
d1: The first double value to be compared.
d2: The second double value to be compared.
Return Value: The function returns value as below:
0: if d1 is numerically equal to d2.
Negative value: if d1 is numerically less than d2.
Positive value: if d1 is numerically greater than d2.
Below programs illustrates the use of Double.compare() function:
Program 1: When two integers are same
Java
// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 1023d; Double d2 = 1023d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println("d1=d2"); } else if (Double.compare(d1, d2) < 0) { System.out.println("d1<d2"); } else { System.out.println("d1>d2"); } }}
d1=d2
Program 2 : When d1<d2
Java
// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 10d; Double d2 = 1023d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println("d1=d2"); } else if (Double.compare(d1, d2) < 0) { System.out.println("d1<d2"); } else { System.out.println("d1>d2"); } }}
d1
Program 3 : When d1>d2
Java
// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 1023d; Double d2 = 10d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println("d1=d2"); } else if (Double.compare(d1, d2) < 0) { System.out.println("d1<d2"); } else { System.out.println("d1>d2"); } }}
d1>d2
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double, %20double)
rajeev0719singh
Java-Double
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
Overriding in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24370,
"s": 24342,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 24603,
"s": 24370,
"text": "The compare() method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. "
},
{
"code": null,
"e": 24612,
"s": 24603,
"text": "Syntax: "
},
{
"code": null,
"e": 24660,
"s": 24612,
"text": "public static int compare(double d1, double d2)"
},
{
"code": null,
"e": 24711,
"s": 24660,
"text": "Parameters: The function accepts two parameters: "
},
{
"code": null,
"e": 24754,
"s": 24711,
"text": "d1: The first double value to be compared."
},
{
"code": null,
"e": 24798,
"s": 24754,
"text": "d2: The second double value to be compared."
},
{
"code": null,
"e": 24851,
"s": 24798,
"text": "Return Value: The function returns value as below: "
},
{
"code": null,
"e": 24888,
"s": 24851,
"text": "0: if d1 is numerically equal to d2."
},
{
"code": null,
"e": 24939,
"s": 24888,
"text": "Negative value: if d1 is numerically less than d2."
},
{
"code": null,
"e": 24993,
"s": 24939,
"text": "Positive value: if d1 is numerically greater than d2."
},
{
"code": null,
"e": 25058,
"s": 24993,
"text": "Below programs illustrates the use of Double.compare() function:"
},
{
"code": null,
"e": 25098,
"s": 25058,
"text": "Program 1: When two integers are same "
},
{
"code": null,
"e": 25103,
"s": 25098,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 1023d; Double d2 = 1023d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println(\"d1=d2\"); } else if (Double.compare(d1, d2) < 0) { System.out.println(\"d1<d2\"); } else { System.out.println(\"d1>d2\"); } }}",
"e": 25680,
"s": 25103,
"text": null
},
{
"code": null,
"e": 25686,
"s": 25680,
"text": "d1=d2"
},
{
"code": null,
"e": 25711,
"s": 25688,
"text": "Program 2 : When d1<d2"
},
{
"code": null,
"e": 25716,
"s": 25711,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 10d; Double d2 = 1023d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println(\"d1=d2\"); } else if (Double.compare(d1, d2) < 0) { System.out.println(\"d1<d2\"); } else { System.out.println(\"d1>d2\"); } }}",
"e": 26291,
"s": 25716,
"text": null
},
{
"code": null,
"e": 26294,
"s": 26291,
"text": "d1"
},
{
"code": null,
"e": 26317,
"s": 26294,
"text": "Program 3 : When d1>d2"
},
{
"code": null,
"e": 26322,
"s": 26317,
"text": "Java"
},
{
"code": "// Java Program to illustrate// the Double.compare() method import java.lang.Double; public class GFG { public static void main(String[] args) { // Get the two double values // to be compared Double d1 = 1023d; Double d2 = 10d; // function call to compare two double values if (Double.compare(d1, d2) == 0) { System.out.println(\"d1=d2\"); } else if (Double.compare(d1, d2) < 0) { System.out.println(\"d1<d2\"); } else { System.out.println(\"d1>d2\"); } }}",
"e": 26897,
"s": 26322,
"text": null
},
{
"code": null,
"e": 26903,
"s": 26897,
"text": "d1>d2"
},
{
"code": null,
"e": 27008,
"s": 26905,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double, %20double) "
},
{
"code": null,
"e": 27024,
"s": 27008,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27036,
"s": 27024,
"text": "Java-Double"
},
{
"code": null,
"e": 27051,
"s": 27036,
"text": "Java-Functions"
},
{
"code": null,
"e": 27069,
"s": 27051,
"text": "Java-lang package"
},
{
"code": null,
"e": 27074,
"s": 27069,
"text": "Java"
},
{
"code": null,
"e": 27079,
"s": 27074,
"text": "Java"
},
{
"code": null,
"e": 27177,
"s": 27079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27209,
"s": 27177,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27228,
"s": 27209,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27246,
"s": 27228,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27278,
"s": 27246,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27298,
"s": 27278,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27313,
"s": 27298,
"text": "Stream In Java"
},
{
"code": null,
"e": 27337,
"s": 27313,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27349,
"s": 27337,
"text": "Set in Java"
},
{
"code": null,
"e": 27368,
"s": 27349,
"text": "Overriding in Java"
}
] |
Why You Are Using t-SNE Wrong. And how to avoid the common pitfalls... | by Tyler Folkman | Towards Data Science
|
t-SNE has become a very popular technique for visualizing high dimensional data. It’s extremely common to take the features from an inner layer of a deep learning model and plot them in 2-dimensions using t-SNE to reduce the dimensionality. Unfortunately, most people just use scikit-learn’s implementation without actually understanding the results and misinterpreting what they mean.
While t-SNE is a dimensionality reduction technique, it is mostly used for visualization and not data pre-processing (like you might with PCA). For this reason, you almost always reduce the dimensionality down to 2 with t-SNE, so that you can then plot the data in two dimensions.
The reason t-SNE is common for visualization is that the goal of the algorithm is to take your high dimensional data and represent it correctly in lower dimensions — thus points that are close in high dimensions should remain close in low dimensions. It does this in a non-linear and local way, so different regions of data could be transformed differently.
t-SNE has a hyper-parameter called perplexity. Perplexity balances the attention t-SNE gives to local and global aspects of the data and can have large effects on the resulting plot. A few notes on this parameter:
It is roughly a guess of the number of close neighbors each point has. Thus, a denser dataset usually requires a higher perplexity value.
It is recommended to be between 5 and 50.
It should be smaller than the number of data points.
The biggest mistake people make with t-SNE is only using one value for perplexity and not testing how the results change with other values. If choosing different values between 5 and 50 significantly change your interpretation of the data, then you should consider other ways to visualize or validate your hypothesis.
It is also overlooked that since t-SNE uses gradient descent, you also have to tune appropriate values for your learning rate and the number of steps for the optimizer. The key is to make sure the algorithm runs long enough to stabilize.
There is an incredibly good article on t-SNE that discusses much of the above as well as the following points that you need to be aware of:
You cannot see the relative sizes of clusters in a t-SNE plot. This point is crucial to understand as t-SNE naturally expands dense clusters and shrinks spares ones. I often see people draw inferences by comparing the relative sizes of clusters in the visualization. Don’t make this mistake.
Distances between well-separated clusters in a t-SNE plot may mean nothing. Another common fallacy. So don’t necessarily be dismayed if your “beach” cluster is closer to your “city” cluster than your “lake” cluster.
Clumps of points — especially with small perplexity values — might just be noise. It is important to be careful when using small perplexity values for this reason. And to remember to always test many perplexity values for robustness.
Now — as promised some code! A few things of note with this code:
I first reduce the dimensionality to 50 using PCA before running t-SNE. I have found that to be good practice (when having over 50 features) because otherwise, t-SNE will take forever to run.
I don’t show various values for perplexity as mentioned above. I will leave that as an exercise for the reader. Just run the t-SNE code a few more times with different perplexity values and compare visualizations.
from sklearn.datasets import fetch_mldatafrom sklearn.manifold import TSNEfrom sklearn.decomposition import PCAimport seaborn as snsimport numpy as npimport matplotlib.pyplot as plt # get mnist datamnist = fetch_mldata("MNIST original")X = mnist.data / 255.0y = mnist.target # first reduce dimensionality before feeding to t-snepca = PCA(n_components=50)X_pca = pca.fit_transform(X) # randomly sample data to run quicklyrows = np.arange(70000)np.random.shuffle(rows)n_select = 10000 # reduce dimensionality with t-snetsne = TSNE(n_components=2, verbose=1, perplexity=50, n_iter=1000, learning_rate=200)tsne_results = tsne.fit_transform(X_pca[rows[:n_select],:])# visualizedf_tsne = pd.DataFrame(tsne_results, columns=['comp1', 'comp2'])df_tsne['label'] = y[rows[:n_select]]sns.lmplot(x='comp1', y='comp2', data=df_tsne, hue='label', fit_reg=False)
And here is the resulting visualization:
I hope this has been a helpful guide on how to use t-SNE more effectively and better understand its output!
You can also find this article here.
Join my email list to stay in touch.
|
[
{
"code": null,
"e": 557,
"s": 171,
"text": "t-SNE has become a very popular technique for visualizing high dimensional data. It’s extremely common to take the features from an inner layer of a deep learning model and plot them in 2-dimensions using t-SNE to reduce the dimensionality. Unfortunately, most people just use scikit-learn’s implementation without actually understanding the results and misinterpreting what they mean."
},
{
"code": null,
"e": 838,
"s": 557,
"text": "While t-SNE is a dimensionality reduction technique, it is mostly used for visualization and not data pre-processing (like you might with PCA). For this reason, you almost always reduce the dimensionality down to 2 with t-SNE, so that you can then plot the data in two dimensions."
},
{
"code": null,
"e": 1196,
"s": 838,
"text": "The reason t-SNE is common for visualization is that the goal of the algorithm is to take your high dimensional data and represent it correctly in lower dimensions — thus points that are close in high dimensions should remain close in low dimensions. It does this in a non-linear and local way, so different regions of data could be transformed differently."
},
{
"code": null,
"e": 1410,
"s": 1196,
"text": "t-SNE has a hyper-parameter called perplexity. Perplexity balances the attention t-SNE gives to local and global aspects of the data and can have large effects on the resulting plot. A few notes on this parameter:"
},
{
"code": null,
"e": 1548,
"s": 1410,
"text": "It is roughly a guess of the number of close neighbors each point has. Thus, a denser dataset usually requires a higher perplexity value."
},
{
"code": null,
"e": 1590,
"s": 1548,
"text": "It is recommended to be between 5 and 50."
},
{
"code": null,
"e": 1643,
"s": 1590,
"text": "It should be smaller than the number of data points."
},
{
"code": null,
"e": 1961,
"s": 1643,
"text": "The biggest mistake people make with t-SNE is only using one value for perplexity and not testing how the results change with other values. If choosing different values between 5 and 50 significantly change your interpretation of the data, then you should consider other ways to visualize or validate your hypothesis."
},
{
"code": null,
"e": 2199,
"s": 1961,
"text": "It is also overlooked that since t-SNE uses gradient descent, you also have to tune appropriate values for your learning rate and the number of steps for the optimizer. The key is to make sure the algorithm runs long enough to stabilize."
},
{
"code": null,
"e": 2339,
"s": 2199,
"text": "There is an incredibly good article on t-SNE that discusses much of the above as well as the following points that you need to be aware of:"
},
{
"code": null,
"e": 2631,
"s": 2339,
"text": "You cannot see the relative sizes of clusters in a t-SNE plot. This point is crucial to understand as t-SNE naturally expands dense clusters and shrinks spares ones. I often see people draw inferences by comparing the relative sizes of clusters in the visualization. Don’t make this mistake."
},
{
"code": null,
"e": 2847,
"s": 2631,
"text": "Distances between well-separated clusters in a t-SNE plot may mean nothing. Another common fallacy. So don’t necessarily be dismayed if your “beach” cluster is closer to your “city” cluster than your “lake” cluster."
},
{
"code": null,
"e": 3081,
"s": 2847,
"text": "Clumps of points — especially with small perplexity values — might just be noise. It is important to be careful when using small perplexity values for this reason. And to remember to always test many perplexity values for robustness."
},
{
"code": null,
"e": 3147,
"s": 3081,
"text": "Now — as promised some code! A few things of note with this code:"
},
{
"code": null,
"e": 3339,
"s": 3147,
"text": "I first reduce the dimensionality to 50 using PCA before running t-SNE. I have found that to be good practice (when having over 50 features) because otherwise, t-SNE will take forever to run."
},
{
"code": null,
"e": 3553,
"s": 3339,
"text": "I don’t show various values for perplexity as mentioned above. I will leave that as an exercise for the reader. Just run the t-SNE code a few more times with different perplexity values and compare visualizations."
},
{
"code": null,
"e": 4401,
"s": 3553,
"text": "from sklearn.datasets import fetch_mldatafrom sklearn.manifold import TSNEfrom sklearn.decomposition import PCAimport seaborn as snsimport numpy as npimport matplotlib.pyplot as plt # get mnist datamnist = fetch_mldata(\"MNIST original\")X = mnist.data / 255.0y = mnist.target # first reduce dimensionality before feeding to t-snepca = PCA(n_components=50)X_pca = pca.fit_transform(X) # randomly sample data to run quicklyrows = np.arange(70000)np.random.shuffle(rows)n_select = 10000 # reduce dimensionality with t-snetsne = TSNE(n_components=2, verbose=1, perplexity=50, n_iter=1000, learning_rate=200)tsne_results = tsne.fit_transform(X_pca[rows[:n_select],:])# visualizedf_tsne = pd.DataFrame(tsne_results, columns=['comp1', 'comp2'])df_tsne['label'] = y[rows[:n_select]]sns.lmplot(x='comp1', y='comp2', data=df_tsne, hue='label', fit_reg=False)"
},
{
"code": null,
"e": 4442,
"s": 4401,
"text": "And here is the resulting visualization:"
},
{
"code": null,
"e": 4550,
"s": 4442,
"text": "I hope this has been a helpful guide on how to use t-SNE more effectively and better understand its output!"
},
{
"code": null,
"e": 4587,
"s": 4550,
"text": "You can also find this article here."
}
] |
Solidity - While Loop
|
The most basic loop in Solidity is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
The flow chart of while loop looks as follows −
The syntax of while loop in Solidity is as follows −
while (expression) {
Statement(s) to be executed if expression is true
}
Try the following example to implement while loop.
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData;
constructor() public{
storedData = 10;
}
function getResult() public view returns(string memory){
uint a = 10;
uint b = 2;
uint result = a + b;
return integerToString(result);
}
function integerToString(uint _i) internal pure
returns (string memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) { // while loop
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
Run the above program using steps provided in Solidity First Application chapter.
0: string: 12
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2816,
"s": 2555,
"text": "The most basic loop in Solidity is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates."
},
{
"code": null,
"e": 2864,
"s": 2816,
"text": "The flow chart of while loop looks as follows −"
},
{
"code": null,
"e": 2917,
"s": 2864,
"text": "The syntax of while loop in Solidity is as follows −"
},
{
"code": null,
"e": 2994,
"s": 2917,
"text": "while (expression) {\n Statement(s) to be executed if expression is true\n}\n"
},
{
"code": null,
"e": 3045,
"s": 2994,
"text": "Try the following example to implement while loop."
},
{
"code": null,
"e": 3808,
"s": 3045,
"text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; \n constructor() public{\n storedData = 10; \n }\n function getResult() public view returns(string memory){\n uint a = 10; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n while (_i != 0) { // while loop\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);\n }\n}"
},
{
"code": null,
"e": 3890,
"s": 3808,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 3905,
"s": 3890,
"text": "0: string: 12\n"
},
{
"code": null,
"e": 3940,
"s": 3905,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3957,
"s": 3940,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3992,
"s": 3957,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4009,
"s": 3992,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4044,
"s": 4009,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4058,
"s": 4044,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 4065,
"s": 4058,
"text": " Print"
},
{
"code": null,
"e": 4076,
"s": 4065,
"text": " Add Notes"
}
] |
try and except in Python Program
|
In this tutorial, we are going to learn about the try and except of Python. Python has a concept called error and exception handling.
The keywords try and except are used in the error and exception handling.
Basically, we will find two types of errors in Python. They are −
Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program.
Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program.
Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,
Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,
We can't stop syntax errors. But, we can intimate if the program runs into an exception error using try-except. Let's see the most common exception errors in Python.
ZeroDivisionError − It occurs when we try to divide any number with zero (0).
ZeroDivisionError − It occurs when we try to divide any number with zero (0).
ValueError − It raises when we pass an inappropriate value to a function.
ValueError − It raises when we pass an inappropriate value to a function.
IndexError − When we try to access an index that is not available.
IndexError − When we try to access an index that is not available.
KeyError − When we try to access a key that's not present in the dictionary.
KeyError − When we try to access a key that's not present in the dictionary.
ImportError − If we try to import a module that does not exist.
ImportError − If we try to import a module that does not exist.
IOError − It occurs when Python can't open a file.
IOError − It occurs when Python can't open a file.
KeyboardInterrupt − It occurs when the user presses an unrequired key.
KeyboardInterrupt − It occurs when the user presses an unrequired key.
There are many exceptional errors in Python. We can handle these easily with the try-except. Let's see the syntax of the try-except first.
# try-except syntax
try:
# statement
# statement
# ...
except:
# statement
# statement
# ...
How Python executes try-except blocks code? Let's see step by step.
First, Python executes the code inside the try block.
First, Python executes the code inside the try block.
If there is no any exception error in the code, then except block won't execute.
If there is no any exception error in the code, then except block won't execute.
If any exception error occurs in the code, then try block will be skipped and except block code will execute**.
If any exception error occurs in the code, then try block will be skipped and except block code will execute**.
If any exception error occurs and except block can't handle it, then the corresponding exception error will raise.
If any exception error occurs and except block can't handle it, then the corresponding exception error will raise.
We can have multiple except statements for one try block.
We can have multiple except statements for one try block.
Let's see an example where there is not any exception error.
Live Demo
# No exception error
try:
arr = [1, 2, 3, 4, 5]
# accesing an item from array with a valid index
two = arr[1]
print(f"We didn't get any errors {two}")
except IndexError:
print("The given index is not valid")
If you run the above program, then you will get the following result.
We didn't get any errors 2
We didn't get any exception errors. So, the code in try block is executed.
Let's see the same example with an invalid index.
Live Demo
# No exception error
try:
arr = [1, 2, 3, 4, 5]
# accesing an item from array with a invalid index
six = arr[6]
print(f"We didn't get any errors {six}")
except IndexError:
print("The given index is not valid")
If you execute the above code, then you will get the following result.
The given index is not valid
We got IndexError in the try block. So, the code in except block is executed.
Let's see what happens if except can't handle the exception error.
Live Demo
# No exception error
try:
arr = [1, 2, 3, 4, 5]
# accesing an item from array with a invalid index
six = arr[6]
print(f"We didn't get any errors {six}")
except ValueError:
print("The given index is not valid")
If run the above code, then you will get the following result.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-11-fe3737d0615b> in <module>
3 arr = [1, 2, 3, 4, 5]
4 # accesing an item from array with a invalid index
----> 5 six = arr[6]
6 print(f"We didn't get any errors {six}")
7 except ValueError:
IndexError: list index out of range
We got an error. We have given ValueError in the except block. But, we got IndexError that didn't handle by the except block. So, we got an error. Be careful while specifying the exception error in the except block.
If you have any queries regarding the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1196,
"s": 1062,
"text": "In this tutorial, we are going to learn about the try and except of Python. Python has a concept called error and exception handling."
},
{
"code": null,
"e": 1270,
"s": 1196,
"text": "The keywords try and except are used in the error and exception handling."
},
{
"code": null,
"e": 1336,
"s": 1270,
"text": "Basically, we will find two types of errors in Python. They are −"
},
{
"code": null,
"e": 1444,
"s": 1336,
"text": "Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program."
},
{
"code": null,
"e": 1552,
"s": 1444,
"text": "Syntax errors - Python gives these types of error when it doesn't understand a line of code in the program."
},
{
"code": null,
"e": 1675,
"s": 1552,
"text": "Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,"
},
{
"code": null,
"e": 1798,
"s": 1675,
"text": "Exception errors - Errors which are detected during the runtime of the program. Ex:- ZeroDivisionError, ValueError, etc..,"
},
{
"code": null,
"e": 1964,
"s": 1798,
"text": "We can't stop syntax errors. But, we can intimate if the program runs into an exception error using try-except. Let's see the most common exception errors in Python."
},
{
"code": null,
"e": 2042,
"s": 1964,
"text": "ZeroDivisionError − It occurs when we try to divide any number with zero (0)."
},
{
"code": null,
"e": 2120,
"s": 2042,
"text": "ZeroDivisionError − It occurs when we try to divide any number with zero (0)."
},
{
"code": null,
"e": 2194,
"s": 2120,
"text": "ValueError − It raises when we pass an inappropriate value to a function."
},
{
"code": null,
"e": 2268,
"s": 2194,
"text": "ValueError − It raises when we pass an inappropriate value to a function."
},
{
"code": null,
"e": 2335,
"s": 2268,
"text": "IndexError − When we try to access an index that is not available."
},
{
"code": null,
"e": 2402,
"s": 2335,
"text": "IndexError − When we try to access an index that is not available."
},
{
"code": null,
"e": 2479,
"s": 2402,
"text": "KeyError − When we try to access a key that's not present in the dictionary."
},
{
"code": null,
"e": 2556,
"s": 2479,
"text": "KeyError − When we try to access a key that's not present in the dictionary."
},
{
"code": null,
"e": 2620,
"s": 2556,
"text": "ImportError − If we try to import a module that does not exist."
},
{
"code": null,
"e": 2684,
"s": 2620,
"text": "ImportError − If we try to import a module that does not exist."
},
{
"code": null,
"e": 2735,
"s": 2684,
"text": "IOError − It occurs when Python can't open a file."
},
{
"code": null,
"e": 2786,
"s": 2735,
"text": "IOError − It occurs when Python can't open a file."
},
{
"code": null,
"e": 2857,
"s": 2786,
"text": "KeyboardInterrupt − It occurs when the user presses an unrequired key."
},
{
"code": null,
"e": 2928,
"s": 2857,
"text": "KeyboardInterrupt − It occurs when the user presses an unrequired key."
},
{
"code": null,
"e": 3067,
"s": 2928,
"text": "There are many exceptional errors in Python. We can handle these easily with the try-except. Let's see the syntax of the try-except first."
},
{
"code": null,
"e": 3178,
"s": 3067,
"text": "# try-except syntax\ntry:\n # statement\n # statement\n # ...\nexcept:\n # statement\n # statement\n # ..."
},
{
"code": null,
"e": 3246,
"s": 3178,
"text": "How Python executes try-except blocks code? Let's see step by step."
},
{
"code": null,
"e": 3300,
"s": 3246,
"text": "First, Python executes the code inside the try block."
},
{
"code": null,
"e": 3354,
"s": 3300,
"text": "First, Python executes the code inside the try block."
},
{
"code": null,
"e": 3435,
"s": 3354,
"text": "If there is no any exception error in the code, then except block won't execute."
},
{
"code": null,
"e": 3516,
"s": 3435,
"text": "If there is no any exception error in the code, then except block won't execute."
},
{
"code": null,
"e": 3628,
"s": 3516,
"text": "If any exception error occurs in the code, then try block will be skipped and except block code will execute**."
},
{
"code": null,
"e": 3740,
"s": 3628,
"text": "If any exception error occurs in the code, then try block will be skipped and except block code will execute**."
},
{
"code": null,
"e": 3855,
"s": 3740,
"text": "If any exception error occurs and except block can't handle it, then the corresponding exception error will raise."
},
{
"code": null,
"e": 3970,
"s": 3855,
"text": "If any exception error occurs and except block can't handle it, then the corresponding exception error will raise."
},
{
"code": null,
"e": 4028,
"s": 3970,
"text": "We can have multiple except statements for one try block."
},
{
"code": null,
"e": 4086,
"s": 4028,
"text": "We can have multiple except statements for one try block."
},
{
"code": null,
"e": 4147,
"s": 4086,
"text": "Let's see an example where there is not any exception error."
},
{
"code": null,
"e": 4158,
"s": 4147,
"text": " Live Demo"
},
{
"code": null,
"e": 4381,
"s": 4158,
"text": "# No exception error\ntry:\n arr = [1, 2, 3, 4, 5]\n # accesing an item from array with a valid index\n two = arr[1]\n print(f\"We didn't get any errors {two}\")\nexcept IndexError:\n print(\"The given index is not valid\")"
},
{
"code": null,
"e": 4451,
"s": 4381,
"text": "If you run the above program, then you will get the following result."
},
{
"code": null,
"e": 4478,
"s": 4451,
"text": "We didn't get any errors 2"
},
{
"code": null,
"e": 4553,
"s": 4478,
"text": "We didn't get any exception errors. So, the code in try block is executed."
},
{
"code": null,
"e": 4603,
"s": 4553,
"text": "Let's see the same example with an invalid index."
},
{
"code": null,
"e": 4614,
"s": 4603,
"text": " Live Demo"
},
{
"code": null,
"e": 4839,
"s": 4614,
"text": "# No exception error\ntry:\n arr = [1, 2, 3, 4, 5]\n # accesing an item from array with a invalid index\n six = arr[6]\n print(f\"We didn't get any errors {six}\")\nexcept IndexError:\n print(\"The given index is not valid\")"
},
{
"code": null,
"e": 4910,
"s": 4839,
"text": "If you execute the above code, then you will get the following result."
},
{
"code": null,
"e": 4939,
"s": 4910,
"text": "The given index is not valid"
},
{
"code": null,
"e": 5017,
"s": 4939,
"text": "We got IndexError in the try block. So, the code in except block is executed."
},
{
"code": null,
"e": 5084,
"s": 5017,
"text": "Let's see what happens if except can't handle the exception error."
},
{
"code": null,
"e": 5095,
"s": 5084,
"text": " Live Demo"
},
{
"code": null,
"e": 5320,
"s": 5095,
"text": "# No exception error\ntry:\n arr = [1, 2, 3, 4, 5]\n # accesing an item from array with a invalid index\n six = arr[6]\n print(f\"We didn't get any errors {six}\")\nexcept ValueError:\n print(\"The given index is not valid\")"
},
{
"code": null,
"e": 5383,
"s": 5320,
"text": "If run the above code, then you will get the following result."
},
{
"code": null,
"e": 5809,
"s": 5383,
"text": "---------------------------------------------------------------------------\nIndexError Traceback (most recent call last)\n<ipython-input-11-fe3737d0615b> in <module>\n 3 arr = [1, 2, 3, 4, 5]\n 4 # accesing an item from array with a invalid index\n----> 5 six = arr[6]\n 6 print(f\"We didn't get any errors {six}\")\n 7 except ValueError:\nIndexError: list index out of range"
},
{
"code": null,
"e": 6025,
"s": 5809,
"text": "We got an error. We have given ValueError in the except block. But, we got IndexError that didn't handle by the except block. So, we got an error. Be careful while specifying the exception error in the except block."
},
{
"code": null,
"e": 6110,
"s": 6025,
"text": "If you have any queries regarding the tutorial, mention them in the comment section."
}
] |
Difference between pointer and array in C? - GeeksforGeeks
|
03 Jun, 2021
Pointers are used for storing address of dynamically allocated arrays and for arrays which are passed as arguments to functions. In other contexts, arrays and pointer are two different things, see the following programs to justify this statement. Behavior of sizeof operator
C++
C
// 1st program to show that array and pointers are different#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; // sizof(int) * (number of element in arr[]) is printed cout << "Size of arr[] " << sizeof(arr) << "\n"; // sizeof a pointer is printed which is same for all // type of pointers (char *, void *, etc) cout << "Size of ptr " << sizeof(ptr); return 0;}
// 1st program to show that array and pointers are different#include <stdio.h> int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; // sizof(int) * (number of element in arr[]) is printed printf("Size of arr[] %ld\n", sizeof(arr)); // sizeof a pointer is printed which is same for all // type of pointers (char *, void *, etc) printf("Size of ptr %ld", sizeof(ptr)); return 0;}
Size of arr[] 24
Size of ptr 8
Assigning any address to an array variable is not allowed.
C++
C
// IInd program to show that array// and pointers are different#include <iostream>using namespace std; int main(){ int arr[] = {10, 20}, x = 10; int *ptr = &x; // This is fine arr = &x; // Compiler Error return 0;} // This code is contributed by Shubhamsingh10
// IInd program to show that array and pointers are different#include <stdio.h> int main(){ int arr[] = {10, 20}, x = 10; int *ptr = &x; // This is fine arr = &x; // Compiler Error return 0;}
Output:
Compiler Error: incompatible types when assigning to
type 'int[2]' from type 'int *'
See the previous post on this topic for more differences. Although array and pointer are different things, following properties of array make them look similar.
Array name gives address of first element of array.
Array name gives address of first element of array.
Consider the following program for example.
C++
C
// 1st program to show that array and pointers are different#include <iostream>using namespace std;int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Assigns address of array to ptr int* ptr = arr; cout << "Value of first element is " << *ptr; return 0;}
#include <stdio.h>int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Assigns address of array to ptr int* ptr = arr; printf("Value of first element is %d", *ptr); return 0;}
Value of first element is 10
Array members are accessed using pointer arithmetic. Compiler uses pointer arithmetic to access array element. For example, an expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr.
C++
C
#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; cout << "arr[2] = " << arr[2] << "\n"; cout << "*(arr + 2) = " << *(arr + 2) << "\n"; cout << "ptr[2] = " << ptr[2] << "\n"; cout << "*(ptr + 2) = " << *(ptr + 2) << "\n"; return 0;}
#include <stdio.h> int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr = arr; printf("arr[2] = %d\n", arr[2]); printf("*(arr + 2) = %d\n", *(arr + 2)); printf("ptr[2] = %d\n", ptr[2]); printf("*(ptr + 2) = %d\n", *(ptr + 2)); return 0;}
arr[2] = 30
*(arr + 2) = 30
ptr[2] = 30
*(ptr + 2) = 30
Array parameters are always passed as pointers, even when we use square brackets.
C++
C
#include <bits/stdc++.h>using namespace std; int fun(int ptr[]){ int x = 10; // Size of a pointer is printed cout << "sizeof(ptr) = " << (int)sizeof(*ptr) << endl; // This allowed because ptr is a // pointer, not array ptr = &x; cout <<"*ptr = " << *ptr; return 0;} // Driver codeint main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Size of a array is printed cout << "sizeof(arr) = " << (int)sizeof(arr) << endl; fun(arr); return 0;} // This code is contributed by shivanisinghss2110
#include <stdio.h> int fun(int ptr[]){ int x = 10; // size of a pointer is printed printf("sizeof(ptr) = %d\n", (int)sizeof(*ptr)); // This allowed because ptr is a pointer, not array ptr = &x; printf("*ptr = %d ", *ptr); return 0;} // Driver codeint main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // size of a array is printed printf("sizeof(arr) = %d\n", (int)sizeof(arr)); fun(arr); return 0;}
sizeof(arr) = 24
sizeof(ptr) = 4
*ptr = 10
Please refer Pointer vs Array in C for more details.
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
rambabuy
malihanan09
shivanisinghss2110
C Array and String
cpp-array
cpp-pointer
C Language
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++
Substring in C++
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Structures in C
Enumeration (or enum) in C
|
[
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 24291,
"s": 24015,
"text": "Pointers are used for storing address of dynamically allocated arrays and for arrays which are passed as arguments to functions. In other contexts, arrays and pointer are two different things, see the following programs to justify this statement. Behavior of sizeof operator "
},
{
"code": null,
"e": 24295,
"s": 24291,
"text": "C++"
},
{
"code": null,
"e": 24297,
"s": 24295,
"text": "C"
},
{
"code": "// 1st program to show that array and pointers are different#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; // sizof(int) * (number of element in arr[]) is printed cout << \"Size of arr[] \" << sizeof(arr) << \"\\n\"; // sizeof a pointer is printed which is same for all // type of pointers (char *, void *, etc) cout << \"Size of ptr \" << sizeof(ptr); return 0;}",
"e": 24741,
"s": 24297,
"text": null
},
{
"code": "// 1st program to show that array and pointers are different#include <stdio.h> int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; // sizof(int) * (number of element in arr[]) is printed printf(\"Size of arr[] %ld\\n\", sizeof(arr)); // sizeof a pointer is printed which is same for all // type of pointers (char *, void *, etc) printf(\"Size of ptr %ld\", sizeof(ptr)); return 0;}",
"e": 25160,
"s": 24741,
"text": null
},
{
"code": null,
"e": 25191,
"s": 25160,
"text": "Size of arr[] 24\nSize of ptr 8"
},
{
"code": null,
"e": 25251,
"s": 25191,
"text": "Assigning any address to an array variable is not allowed. "
},
{
"code": null,
"e": 25255,
"s": 25251,
"text": "C++"
},
{
"code": null,
"e": 25257,
"s": 25255,
"text": "C"
},
{
"code": "// IInd program to show that array// and pointers are different#include <iostream>using namespace std; int main(){ int arr[] = {10, 20}, x = 10; int *ptr = &x; // This is fine arr = &x; // Compiler Error return 0;} // This code is contributed by Shubhamsingh10",
"e": 25527,
"s": 25257,
"text": null
},
{
"code": "// IInd program to show that array and pointers are different#include <stdio.h> int main(){ int arr[] = {10, 20}, x = 10; int *ptr = &x; // This is fine arr = &x; // Compiler Error return 0;}",
"e": 25728,
"s": 25527,
"text": null
},
{
"code": null,
"e": 25737,
"s": 25728,
"text": "Output: "
},
{
"code": null,
"e": 25839,
"s": 25737,
"text": " Compiler Error: incompatible types when assigning to \n type 'int[2]' from type 'int *' "
},
{
"code": null,
"e": 26001,
"s": 25839,
"text": "See the previous post on this topic for more differences. Although array and pointer are different things, following properties of array make them look similar. "
},
{
"code": null,
"e": 26053,
"s": 26001,
"text": "Array name gives address of first element of array."
},
{
"code": null,
"e": 26105,
"s": 26053,
"text": "Array name gives address of first element of array."
},
{
"code": null,
"e": 26150,
"s": 26105,
"text": "Consider the following program for example. "
},
{
"code": null,
"e": 26154,
"s": 26150,
"text": "C++"
},
{
"code": null,
"e": 26156,
"s": 26154,
"text": "C"
},
{
"code": "// 1st program to show that array and pointers are different#include <iostream>using namespace std;int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Assigns address of array to ptr int* ptr = arr; cout << \"Value of first element is \" << *ptr; return 0;}",
"e": 26431,
"s": 26156,
"text": null
},
{
"code": "#include <stdio.h>int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Assigns address of array to ptr int* ptr = arr; printf(\"Value of first element is %d\", *ptr); return 0;}",
"e": 26624,
"s": 26431,
"text": null
},
{
"code": null,
"e": 26653,
"s": 26624,
"text": "Value of first element is 10"
},
{
"code": null,
"e": 26966,
"s": 26653,
"text": "Array members are accessed using pointer arithmetic. Compiler uses pointer arithmetic to access array element. For example, an expression like “arr[i]” is treated as *(arr + i) by the compiler. That is why the expressions like *(arr + i) work for array arr, and expressions like ptr[i] also work for pointer ptr."
},
{
"code": null,
"e": 26970,
"s": 26966,
"text": "C++"
},
{
"code": null,
"e": 26972,
"s": 26970,
"text": "C"
},
{
"code": "#include <iostream>using namespace std; int main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; int* ptr = arr; cout << \"arr[2] = \" << arr[2] << \"\\n\"; cout << \"*(arr + 2) = \" << *(arr + 2) << \"\\n\"; cout << \"ptr[2] = \" << ptr[2] << \"\\n\"; cout << \"*(ptr + 2) = \" << *(ptr + 2) << \"\\n\"; return 0;}",
"e": 27284,
"s": 26972,
"text": null
},
{
"code": "#include <stdio.h> int main(){ int arr[] = {10, 20, 30, 40, 50, 60}; int *ptr = arr; printf(\"arr[2] = %d\\n\", arr[2]); printf(\"*(arr + 2) = %d\\n\", *(arr + 2)); printf(\"ptr[2] = %d\\n\", ptr[2]); printf(\"*(ptr + 2) = %d\\n\", *(ptr + 2)); return 0;}",
"e": 27542,
"s": 27284,
"text": null
},
{
"code": null,
"e": 27598,
"s": 27542,
"text": "arr[2] = 30\n*(arr + 2) = 30\nptr[2] = 30\n*(ptr + 2) = 30"
},
{
"code": null,
"e": 27681,
"s": 27598,
"text": "Array parameters are always passed as pointers, even when we use square brackets. "
},
{
"code": null,
"e": 27685,
"s": 27681,
"text": "C++"
},
{
"code": null,
"e": 27687,
"s": 27685,
"text": "C"
},
{
"code": "#include <bits/stdc++.h>using namespace std; int fun(int ptr[]){ int x = 10; // Size of a pointer is printed cout << \"sizeof(ptr) = \" << (int)sizeof(*ptr) << endl; // This allowed because ptr is a // pointer, not array ptr = &x; cout <<\"*ptr = \" << *ptr; return 0;} // Driver codeint main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // Size of a array is printed cout << \"sizeof(arr) = \" << (int)sizeof(arr) << endl; fun(arr); return 0;} // This code is contributed by shivanisinghss2110",
"e": 28274,
"s": 27687,
"text": null
},
{
"code": "#include <stdio.h> int fun(int ptr[]){ int x = 10; // size of a pointer is printed printf(\"sizeof(ptr) = %d\\n\", (int)sizeof(*ptr)); // This allowed because ptr is a pointer, not array ptr = &x; printf(\"*ptr = %d \", *ptr); return 0;} // Driver codeint main(){ int arr[] = { 10, 20, 30, 40, 50, 60 }; // size of a array is printed printf(\"sizeof(arr) = %d\\n\", (int)sizeof(arr)); fun(arr); return 0;}",
"e": 28717,
"s": 28274,
"text": null
},
{
"code": null,
"e": 28761,
"s": 28717,
"text": "sizeof(arr) = 24\nsizeof(ptr) = 4\n*ptr = 10 "
},
{
"code": null,
"e": 28814,
"s": 28761,
"text": "Please refer Pointer vs Array in C for more details."
},
{
"code": null,
"e": 28982,
"s": 28814,
"text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 28993,
"s": 28984,
"text": "rambabuy"
},
{
"code": null,
"e": 29005,
"s": 28993,
"text": "malihanan09"
},
{
"code": null,
"e": 29024,
"s": 29005,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 29043,
"s": 29024,
"text": "C Array and String"
},
{
"code": null,
"e": 29053,
"s": 29043,
"text": "cpp-array"
},
{
"code": null,
"e": 29065,
"s": 29053,
"text": "cpp-pointer"
},
{
"code": null,
"e": 29076,
"s": 29065,
"text": "C Language"
},
{
"code": null,
"e": 29174,
"s": 29076,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29183,
"s": 29174,
"text": "Comments"
},
{
"code": null,
"e": 29196,
"s": 29183,
"text": "Old Comments"
},
{
"code": null,
"e": 29231,
"s": 29196,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 29259,
"s": 29231,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29305,
"s": 29259,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 29317,
"s": 29305,
"text": "fork() in C"
},
{
"code": null,
"e": 29349,
"s": 29317,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 29366,
"s": 29349,
"text": "Substring in C++"
},
{
"code": null,
"e": 29413,
"s": 29366,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 29451,
"s": 29413,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29467,
"s": 29451,
"text": "Structures in C"
}
] |
PostgreSQL - ORDER BY Clause
|
The PostgreSQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns.
The basic syntax of ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in column-list.
Consider the table COMPANY having records as follows −
testdb# select * from COMPANY;
id | name | age | address | salary
----+-------+-----+-----------+--------
1 | Paul | 32 | California| 20000
2 | Allen | 25 | Texas | 15000
3 | Teddy | 23 | Norway | 20000
4 | Mark | 25 | Rich-Mond | 65000
5 | David | 27 | Texas | 85000
6 | Kim | 22 | South-Hall| 45000
7 | James | 24 | Houston | 10000
(7 rows)
The following is an example, which would sort the result in ascending order by SALARY −
testdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;
This would produce the following result −
id | name | age | address | salary
----+-------+-----+------------+--------
6 | Kim | 22 | South-Hall | 45000
3 | Teddy | 23 | Norway | 20000
7 | James | 24 | Houston | 10000
8 | Paul | 24 | Houston | 20000
4 | Mark | 25 | Rich-Mond | 65000
2 | Allen | 25 | Texas | 15000
5 | David | 27 | Texas | 85000
1 | Paul | 32 | California | 20000
9 | James | 44 | Norway | 5000
10 | James | 45 | Texas | 5000
(10 rows)
The following is an example, which would sort the result in ascending order by NAME and SALARY −
testdb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
This would produce the following result −
id | name | age | address | salary
----+-------+-----+--------------+--------
2 | Allen | 25 | Texas | 15000
5 | David | 27 | Texas | 85000
10 | James | 45 | Texas | 5000
9 | James | 44 | Norway | 5000
7 | James | 24 | Houston | 10000
6 | Kim | 22 | South-Hall | 45000
4 | Mark | 25 | Rich-Mond | 65000
1 | Paul | 32 | California | 20000
8 | Paul | 24 | Houston | 20000
3 | Teddy | 23 | Norway | 20000
(10 rows)
The following is an example, which would sort the result in descending order by NAME −
testdb=# SELECT * FROM COMPANY ORDER BY NAME DESC;
This would produce the following result −
id | name | age | address | salary
----+-------+-----+------------+--------
3 | Teddy | 23 | Norway | 20000
1 | Paul | 32 | California | 20000
8 | Paul | 24 | Houston | 20000
4 | Mark | 25 | Rich-Mond | 65000
6 | Kim | 22 | South-Hall | 45000
7 | James | 24 | Houston | 10000
9 | James | 44 | Norway | 5000
10 | James | 45 | Texas | 5000
5 | David | 27 | Texas | 85000
2 | Allen | 25 | Texas | 15000
(10 rows)
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2945,
"s": 2825,
"text": "The PostgreSQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns."
},
{
"code": null,
"e": 2997,
"s": 2945,
"text": "The basic syntax of ORDER BY clause is as follows −"
},
{
"code": null,
"e": 3105,
"s": 2997,
"text": "SELECT column-list\nFROM table_name\n[WHERE condition]\n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n"
},
{
"code": null,
"e": 3259,
"s": 3105,
"text": "You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be available in column-list."
},
{
"code": null,
"e": 3314,
"s": 3259,
"text": "Consider the table COMPANY having records as follows −"
},
{
"code": null,
"e": 3706,
"s": 3314,
"text": "testdb# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)"
},
{
"code": null,
"e": 3794,
"s": 3706,
"text": "The following is an example, which would sort the result in ascending order by SALARY −"
},
{
"code": null,
"e": 3843,
"s": 3794,
"text": "testdb=# SELECT * FROM COMPANY ORDER BY AGE ASC;"
},
{
"code": null,
"e": 3885,
"s": 3843,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 4389,
"s": 3885,
"text": " id | name | age | address | salary\n ----+-------+-----+------------+--------\n 6 | Kim | 22 | South-Hall | 45000\n 3 | Teddy | 23 | Norway | 20000\n 7 | James | 24 | Houston | 10000\n 8 | Paul | 24 | Houston | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 2 | Allen | 25 | Texas | 15000\n 5 | David | 27 | Texas | 85000\n 1 | Paul | 32 | California | 20000\n 9 | James | 44 | Norway | 5000\n 10 | James | 45 | Texas | 5000\n(10 rows)\n"
},
{
"code": null,
"e": 4486,
"s": 4389,
"text": "The following is an example, which would sort the result in ascending order by NAME and SALARY −"
},
{
"code": null,
"e": 4544,
"s": 4486,
"text": "testdb=# SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;"
},
{
"code": null,
"e": 4586,
"s": 4544,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 5102,
"s": 4586,
"text": " id | name | age | address | salary\n----+-------+-----+--------------+--------\n 2 | Allen | 25 | Texas | 15000\n 5 | David | 27 | Texas | 85000\n 10 | James | 45 | Texas | 5000\n 9 | James | 44 | Norway | 5000\n 7 | James | 24 | Houston | 10000\n 6 | Kim | 22 | South-Hall | 45000\n 4 | Mark | 25 | Rich-Mond | 65000\n 1 | Paul | 32 | California | 20000\n 8 | Paul | 24 | Houston | 20000\n 3 | Teddy | 23 | Norway | 20000\n(10 rows)\n"
},
{
"code": null,
"e": 5189,
"s": 5102,
"text": "The following is an example, which would sort the result in descending order by NAME −"
},
{
"code": null,
"e": 5240,
"s": 5189,
"text": "testdb=# SELECT * FROM COMPANY ORDER BY NAME DESC;"
},
{
"code": null,
"e": 5282,
"s": 5240,
"text": "This would produce the following result −"
},
{
"code": null,
"e": 5774,
"s": 5282,
"text": " id | name | age | address | salary\n----+-------+-----+------------+--------\n 3 | Teddy | 23 | Norway | 20000\n 1 | Paul | 32 | California | 20000\n 8 | Paul | 24 | Houston | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 6 | Kim | 22 | South-Hall | 45000\n 7 | James | 24 | Houston | 10000\n 9 | James | 44 | Norway | 5000\n 10 | James | 45 | Texas | 5000\n 5 | David | 27 | Texas | 85000\n 2 | Allen | 25 | Texas | 15000\n(10 rows)\n"
},
{
"code": null,
"e": 5809,
"s": 5774,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5821,
"s": 5809,
"text": " John Elder"
},
{
"code": null,
"e": 5856,
"s": 5821,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5872,
"s": 5856,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 5909,
"s": 5872,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5931,
"s": 5909,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5964,
"s": 5931,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5978,
"s": 5964,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6009,
"s": 5978,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6022,
"s": 6009,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6053,
"s": 6022,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 6066,
"s": 6053,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 6073,
"s": 6066,
"text": " Print"
},
{
"code": null,
"e": 6084,
"s": 6073,
"text": " Add Notes"
}
] |
Check if N can be represented as sum of distinct powers of 3 - GeeksforGeeks
|
16 Nov, 2021
Given a positive integer N, the task is to check whether the given number N can be represented as the sum of the distinct powers of 3. If found to be true, then print “Yes”. Otherwise, “No”.
Examples:
Input: N = 28Output: YesExplanation:The number N(= 28) can be represented (1 + 7) = (30 + 33), which is a perfect power 2.
Input: N = 6Output: No
Approach: The simplest approach to solve the given problem is to generate all possible permutations of all distinct powers of 3 and if there exists any such combination whose sum is a perfect power of 3. As 315 > 107 so there are only 16 distinct powers i.e., [0, 15].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to try all permutations// of distinct powersbool PermuteAndFind(vector<long> power, int idx, long SumSoFar, int target){ // Base Case if (idx == power.size()) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] bool select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] bool notselect = PermuteAndFind( power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect);} // Function to check the N can be// represented as the sum of the// distinct powers of 3void DistinctPowersOf3(int N){ // Stores the all distincts powers // of three to [0, 15] vector<long> power(16); power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call bool found = PermuteAndFind(power, 0, 0L, N); // print if (found == true) { cout << "Yes"; } else { cout << "No"; }} // Driven Codeint main(){ int N = 91; DistinctPowersOf3(N); return 0;}
// Java program for the above approachclass GFG{ // Function to try all permutations // of distinct powers public static boolean PermuteAndFind(int[] power, int idx, int SumSoFar, int target) { // Base Case if (idx == power.length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] boolean select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] boolean notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect); } // Function to check the N can be // represented as the sum of the // distinct powers of 3 public static void DistinctPowersOf3(int N) { // Stores the all distincts powers // of three to [0, 15] int[] power = new int[16]; power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call boolean found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { System.out.println("Yes"); } else { System.out.println("No"); } } // Driven Code public static void main(String args[]) { int N = 91; DistinctPowersOf3(N); }} // This code is contributed by _saurabh_jaiswal.
# Python3 program for the above approach # Function to try all permutations# of distinct powersdef PermuteAndFind(power, idx, SumSoFar, target): # Base Case if (idx == len(power)): # If the distinct powers # sum is obtained if (SumSoFar == target): return True # Otherwise return False # If current element not selected # in power[] select = PermuteAndFind(power, idx + 1, SumSoFar, target) # If current element selected in # power[] notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target) # Return 1 if any permutation # found return(select or notselect) # Function to check the N can be# represented as the sum of the# distinct powers of 3def DistinctPowersOf3(N): # Stores the all distincts powers # of three to[0, 15] power = [0 for x in range(16)] power[0] = 1 for i in range(1, 16): power[i] = 3 * power[i - 1] # Function Call found = PermuteAndFind(power, 0, 0, N) # Print if (found == True): print("Yes") else: print("No") # Driver CodeN = 91 DistinctPowersOf3(N) # This code is contributed by amreshkumar3
// C# program for the above approachusing System; class GFG{ // Function to try all permutations // of distinct powers public static bool PermuteAndFind(int[] power, int idx, int SumSoFar, int target) { // Base Case if (idx == power.Length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] bool select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] bool notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect); } // Function to check the N can be // represented as the sum of the // distinct powers of 3 public static void DistinctPowersOf3(int N) { // Stores the all distincts powers // of three to [0, 15] int[] power = new int[16]; power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call bool found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { Console.Write("Yes"); } else { Console.Write("No"); } } // Driver Codepublic static void Main(){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by avijitmondal1998.
<script>// Javascript program for the above approach // Function to try all permutations// of distinct powersfunction PermuteAndFind(power, idx, SumSoFar, target) { // Base Case if (idx == power.length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] let select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] let notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return select || notselect;} // Function to check the N can be// represented as the sum of the// distinct powers of 3function DistinctPowersOf3(N) { // Stores the all distincts powers // of three to [0, 15] let power = new Array(16); power[0] = 1; for (let i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call let found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { document.write("Yes"); } else { document.write("No"); }} // Driven Code let N = 91;DistinctPowersOf3(N); </script>
Yes
Time Complexity: O(2N)Auxiliary Space: O(2N)
Another Approach: The above approach can also be optimized by observing the fact that N in ternary form (Base 3). Each digit is 3i, and the ternary number(N) is the sum of them.
To have distinct powers of 3, to sum up to N, in ternary form the ith digit can be either 0,1 or 2(In Binary, it is 0 and 1). Thus, there can be three cases for each digit at ith position:
Digit can be 0 i.e. there is No 3i number in N.
Digit can be 1 i.e, there is One 3i number in N.
Digit cannot be 2 because then there are 2 of 3i, therefore, not distinct.
Follow the below steps to solve the problem:
Iterate until N becomes 0 and perform the following steps:If the value of N%3 is 2, then print “No”.Otherwise, divide N by 3.
If the value of N%3 is 2, then print “No”.
Otherwise, divide N by 3.
After completing the above steps, if the value of N is 0 then print “Yes”. Otherwise, “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { cout << "No"; return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 cout << "Yes";} // Driver Codeint main(){ int N = 91; DistinctPowersOf3(N); return 0;}
// Java program for the above approachclass GFG{ // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3public static void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { System.out.println("No"); return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 System.out.println("Yes");} // Driver Codepublic static void main(String args[]){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by _saurabh_jaiswal.
# Python3 program for the above approach # Function to check whether the given# N can be represented as the sum of# the distinct powers of 3def DistinctPowersOf3(N): # Iterate until N is non-zero while (N > 0): # Termination Condition if (N % 3 == 2): cout << "No" return # Right shift ternary bits # by 1 for the next digit N //= 3 # If N can be expressed as the # sum of perfect powers of 3 print ("Yes") # Driver Codeif __name__ == '__main__': N = 91 DistinctPowersOf3(N) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;class GFG{ // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3static void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { Console.Write("No"); return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 Console.Write("Yes");} // Driver Codepublic static void Main(){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript program for the above approach // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3function DistinctPowersOf3(N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { document.write("No"); return; } // Right shift ternary bits // by 1 for the next digit N = Math.floor(N/ 3); } // If N can be expressed as the // sum of perfect powers of 3 document.write("Yes");} // Driver Codelet N = 91;DistinctPowersOf3(N); // This code is contributed by patel2127</script>
Yes
Time Complexity: O(log3N)Auxiliary Space: O(1)
mohit kumar 29
amreshkumar3
patel2127
_saurabh_jaiswal
avijitmondal1998
samim2000
maths-power
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Check whether K-th bit is set or not
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Hamming code Implementation in C/C++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 25014,
"s": 24986,
"text": "\n16 Nov, 2021"
},
{
"code": null,
"e": 25205,
"s": 25014,
"text": "Given a positive integer N, the task is to check whether the given number N can be represented as the sum of the distinct powers of 3. If found to be true, then print “Yes”. Otherwise, “No”."
},
{
"code": null,
"e": 25215,
"s": 25205,
"text": "Examples:"
},
{
"code": null,
"e": 25338,
"s": 25215,
"text": "Input: N = 28Output: YesExplanation:The number N(= 28) can be represented (1 + 7) = (30 + 33), which is a perfect power 2."
},
{
"code": null,
"e": 25361,
"s": 25338,
"text": "Input: N = 6Output: No"
},
{
"code": null,
"e": 25630,
"s": 25361,
"text": "Approach: The simplest approach to solve the given problem is to generate all possible permutations of all distinct powers of 3 and if there exists any such combination whose sum is a perfect power of 3. As 315 > 107 so there are only 16 distinct powers i.e., [0, 15]."
},
{
"code": null,
"e": 25681,
"s": 25630,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25685,
"s": 25681,
"text": "C++"
},
{
"code": null,
"e": 25690,
"s": 25685,
"text": "Java"
},
{
"code": null,
"e": 25698,
"s": 25690,
"text": "Python3"
},
{
"code": null,
"e": 25701,
"s": 25698,
"text": "C#"
},
{
"code": null,
"e": 25712,
"s": 25701,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to try all permutations// of distinct powersbool PermuteAndFind(vector<long> power, int idx, long SumSoFar, int target){ // Base Case if (idx == power.size()) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] bool select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] bool notselect = PermuteAndFind( power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect);} // Function to check the N can be// represented as the sum of the// distinct powers of 3void DistinctPowersOf3(int N){ // Stores the all distincts powers // of three to [0, 15] vector<long> power(16); power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call bool found = PermuteAndFind(power, 0, 0L, N); // print if (found == true) { cout << \"Yes\"; } else { cout << \"No\"; }} // Driven Codeint main(){ int N = 91; DistinctPowersOf3(N); return 0;}",
"e": 27054,
"s": 25712,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to try all permutations // of distinct powers public static boolean PermuteAndFind(int[] power, int idx, int SumSoFar, int target) { // Base Case if (idx == power.length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] boolean select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] boolean notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect); } // Function to check the N can be // represented as the sum of the // distinct powers of 3 public static void DistinctPowersOf3(int N) { // Stores the all distincts powers // of three to [0, 15] int[] power = new int[16]; power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call boolean found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } } // Driven Code public static void main(String args[]) { int N = 91; DistinctPowersOf3(N); }} // This code is contributed by _saurabh_jaiswal.",
"e": 28698,
"s": 27054,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to try all permutations# of distinct powersdef PermuteAndFind(power, idx, SumSoFar, target): # Base Case if (idx == len(power)): # If the distinct powers # sum is obtained if (SumSoFar == target): return True # Otherwise return False # If current element not selected # in power[] select = PermuteAndFind(power, idx + 1, SumSoFar, target) # If current element selected in # power[] notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target) # Return 1 if any permutation # found return(select or notselect) # Function to check the N can be# represented as the sum of the# distinct powers of 3def DistinctPowersOf3(N): # Stores the all distincts powers # of three to[0, 15] power = [0 for x in range(16)] power[0] = 1 for i in range(1, 16): power[i] = 3 * power[i - 1] # Function Call found = PermuteAndFind(power, 0, 0, N) # Print if (found == True): print(\"Yes\") else: print(\"No\") # Driver CodeN = 91 DistinctPowersOf3(N) # This code is contributed by amreshkumar3",
"e": 29994,
"s": 28698,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to try all permutations // of distinct powers public static bool PermuteAndFind(int[] power, int idx, int SumSoFar, int target) { // Base Case if (idx == power.Length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] bool select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] bool notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return (select || notselect); } // Function to check the N can be // represented as the sum of the // distinct powers of 3 public static void DistinctPowersOf3(int N) { // Stores the all distincts powers // of three to [0, 15] int[] power = new int[16]; power[0] = 1; for (int i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call bool found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); } } // Driver Codepublic static void Main(){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by avijitmondal1998.",
"e": 31592,
"s": 29994,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to try all permutations// of distinct powersfunction PermuteAndFind(power, idx, SumSoFar, target) { // Base Case if (idx == power.length) { // If the distinct powers // sum is obtained if (SumSoFar == target) return true; // Otherwise return false; } // If current element not selected // in power[] let select = PermuteAndFind(power, idx + 1, SumSoFar, target); // If current element selected in // power[] let notselect = PermuteAndFind(power, idx + 1, SumSoFar + power[idx], target); // Return 1 if any permutation // found return select || notselect;} // Function to check the N can be// represented as the sum of the// distinct powers of 3function DistinctPowersOf3(N) { // Stores the all distincts powers // of three to [0, 15] let power = new Array(16); power[0] = 1; for (let i = 1; i < 16; i++) power[i] = 3 * power[i - 1]; // Function Call let found = PermuteAndFind(power, 0, 0, N); // print if (found == true) { document.write(\"Yes\"); } else { document.write(\"No\"); }} // Driven Code let N = 91;DistinctPowersOf3(N); </script>",
"e": 32746,
"s": 31592,
"text": null
},
{
"code": null,
"e": 32750,
"s": 32746,
"text": "Yes"
},
{
"code": null,
"e": 32795,
"s": 32750,
"text": "Time Complexity: O(2N)Auxiliary Space: O(2N)"
},
{
"code": null,
"e": 32973,
"s": 32795,
"text": "Another Approach: The above approach can also be optimized by observing the fact that N in ternary form (Base 3). Each digit is 3i, and the ternary number(N) is the sum of them."
},
{
"code": null,
"e": 33163,
"s": 32973,
"text": "To have distinct powers of 3, to sum up to N, in ternary form the ith digit can be either 0,1 or 2(In Binary, it is 0 and 1). Thus, there can be three cases for each digit at ith position: "
},
{
"code": null,
"e": 33211,
"s": 33163,
"text": "Digit can be 0 i.e. there is No 3i number in N."
},
{
"code": null,
"e": 33260,
"s": 33211,
"text": "Digit can be 1 i.e, there is One 3i number in N."
},
{
"code": null,
"e": 33335,
"s": 33260,
"text": "Digit cannot be 2 because then there are 2 of 3i, therefore, not distinct."
},
{
"code": null,
"e": 33381,
"s": 33335,
"text": "Follow the below steps to solve the problem: "
},
{
"code": null,
"e": 33507,
"s": 33381,
"text": "Iterate until N becomes 0 and perform the following steps:If the value of N%3 is 2, then print “No”.Otherwise, divide N by 3."
},
{
"code": null,
"e": 33550,
"s": 33507,
"text": "If the value of N%3 is 2, then print “No”."
},
{
"code": null,
"e": 33576,
"s": 33550,
"text": "Otherwise, divide N by 3."
},
{
"code": null,
"e": 33668,
"s": 33576,
"text": "After completing the above steps, if the value of N is 0 then print “Yes”. Otherwise, “No”."
},
{
"code": null,
"e": 33720,
"s": 33668,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 33724,
"s": 33720,
"text": "C++"
},
{
"code": null,
"e": 33729,
"s": 33724,
"text": "Java"
},
{
"code": null,
"e": 33737,
"s": 33729,
"text": "Python3"
},
{
"code": null,
"e": 33740,
"s": 33737,
"text": "C#"
},
{
"code": null,
"e": 33751,
"s": 33740,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { cout << \"No\"; return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 cout << \"Yes\";} // Driver Codeint main(){ int N = 91; DistinctPowersOf3(N); return 0;}",
"e": 34390,
"s": 33751,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3public static void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { System.out.println(\"No\"); return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 System.out.println(\"Yes\");} // Driver Codepublic static void main(String args[]){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by _saurabh_jaiswal.",
"e": 35103,
"s": 34390,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check whether the given# N can be represented as the sum of# the distinct powers of 3def DistinctPowersOf3(N): # Iterate until N is non-zero while (N > 0): # Termination Condition if (N % 3 == 2): cout << \"No\" return # Right shift ternary bits # by 1 for the next digit N //= 3 # If N can be expressed as the # sum of perfect powers of 3 print (\"Yes\") # Driver Codeif __name__ == '__main__': N = 91 DistinctPowersOf3(N) # This code is contributed by mohit kumar 29.",
"e": 35709,
"s": 35103,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3static void DistinctPowersOf3(int N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { Console.Write(\"No\"); return; } // Right shift ternary bits // by 1 for the next digit N /= 3; } // If N can be expressed as the // sum of perfect powers of 3 Console.Write(\"Yes\");} // Driver Codepublic static void Main(){ int N = 91; DistinctPowersOf3(N);}} // This code is contributed by Samim Hossain Mondal.",
"e": 36414,
"s": 35709,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to check whether the given// N can be represented as the sum of// the distinct powers of 3function DistinctPowersOf3(N){ // Iterate until N is non-zero while (N > 0) { // Termination Condition if (N % 3 == 2) { document.write(\"No\"); return; } // Right shift ternary bits // by 1 for the next digit N = Math.floor(N/ 3); } // If N can be expressed as the // sum of perfect powers of 3 document.write(\"Yes\");} // Driver Codelet N = 91;DistinctPowersOf3(N); // This code is contributed by patel2127</script>",
"e": 37080,
"s": 36414,
"text": null
},
{
"code": null,
"e": 37084,
"s": 37080,
"text": "Yes"
},
{
"code": null,
"e": 37131,
"s": 37084,
"text": "Time Complexity: O(log3N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 37148,
"s": 37133,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37161,
"s": 37148,
"text": "amreshkumar3"
},
{
"code": null,
"e": 37171,
"s": 37161,
"text": "patel2127"
},
{
"code": null,
"e": 37188,
"s": 37171,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 37205,
"s": 37188,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 37215,
"s": 37205,
"text": "samim2000"
},
{
"code": null,
"e": 37227,
"s": 37215,
"text": "maths-power"
},
{
"code": null,
"e": 37237,
"s": 37227,
"text": "Bit Magic"
},
{
"code": null,
"e": 37250,
"s": 37237,
"text": "Mathematical"
},
{
"code": null,
"e": 37263,
"s": 37250,
"text": "Mathematical"
},
{
"code": null,
"e": 37273,
"s": 37263,
"text": "Bit Magic"
},
{
"code": null,
"e": 37371,
"s": 37273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37422,
"s": 37371,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 37459,
"s": 37422,
"text": "Check whether K-th bit is set or not"
},
{
"code": null,
"e": 37482,
"s": 37459,
"text": "Program to find parity"
},
{
"code": null,
"e": 37546,
"s": 37482,
"text": "Write an Efficient Method to Check if a Number is Multiple of 3"
},
{
"code": null,
"e": 37583,
"s": 37546,
"text": "Hamming code Implementation in C/C++"
},
{
"code": null,
"e": 37613,
"s": 37583,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 37673,
"s": 37613,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 37688,
"s": 37673,
"text": "C++ Data Types"
},
{
"code": null,
"e": 37731,
"s": 37688,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
HTML | <form> name Attribute - GeeksforGeeks
|
27 May, 2019
The HTML <form> name Attribute is used to specify the name of a form Element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript.
Syntax:
<form name="name">
Attribute Values: It contains a single value name which describes the name of the <form> element.
Example:
<!DOCTYPE html><html> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2>HTML Form name Attribute.</h2> <form id="users" action="#" name="Geeks"> First name: <input type="text" name="fname" value="Manas"> <br> Last name: <input type="text" name="lname" value="Chhabra"> <br> <input type="submit" value="Submit"> </form></body> </html>
Output:
Supported Browsers:
Google Chrome
Firefox
Edge
Opera
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using HTML and JavaScript
How to position a div at the bottom of its container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24181,
"s": 24153,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 24368,
"s": 24181,
"text": "The HTML <form> name Attribute is used to specify the name of a form Element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript."
},
{
"code": null,
"e": 24376,
"s": 24368,
"text": "Syntax:"
},
{
"code": null,
"e": 24396,
"s": 24376,
"text": "<form name=\"name\"> "
},
{
"code": null,
"e": 24494,
"s": 24396,
"text": "Attribute Values: It contains a single value name which describes the name of the <form> element."
},
{
"code": null,
"e": 24503,
"s": 24494,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2>HTML Form name Attribute.</h2> <form id=\"users\" action=\"#\" name=\"Geeks\"> First name: <input type=\"text\" name=\"fname\" value=\"Manas\"> <br> Last name: <input type=\"text\" name=\"lname\" value=\"Chhabra\"> <br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>",
"e": 24939,
"s": 24503,
"text": null
},
{
"code": null,
"e": 24947,
"s": 24939,
"text": "Output:"
},
{
"code": null,
"e": 24967,
"s": 24947,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 24981,
"s": 24967,
"text": "Google Chrome"
},
{
"code": null,
"e": 24989,
"s": 24981,
"text": "Firefox"
},
{
"code": null,
"e": 24994,
"s": 24989,
"text": "Edge"
},
{
"code": null,
"e": 25000,
"s": 24994,
"text": "Opera"
},
{
"code": null,
"e": 25013,
"s": 25000,
"text": "Apple Safari"
},
{
"code": null,
"e": 25150,
"s": 25013,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25166,
"s": 25150,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25171,
"s": 25166,
"text": "HTML"
},
{
"code": null,
"e": 25188,
"s": 25171,
"text": "Web Technologies"
},
{
"code": null,
"e": 25193,
"s": 25188,
"text": "HTML"
},
{
"code": null,
"e": 25291,
"s": 25193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25300,
"s": 25291,
"text": "Comments"
},
{
"code": null,
"e": 25313,
"s": 25300,
"text": "Old Comments"
},
{
"code": null,
"e": 25363,
"s": 25313,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25387,
"s": 25363,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 25424,
"s": 25387,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 25466,
"s": 25424,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 25530,
"s": 25466,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 25586,
"s": 25530,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25619,
"s": 25586,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 25662,
"s": 25619,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25723,
"s": 25662,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Explain final class and final method in PHP.
|
The final keyword is introduced by PHP5 related to the object-oriented programming concept.
But before we move on to the final, we need to ensure that we have a good understanding of the inheritance concept. In inheritance, we can inherit a class from another class. Also, we can override a function in an inherited class, to replace the behavior originally provided. In some cases, we might need to keep a class from being inherited from or we may need to prevent a function to be overridden. This can be achieved with the final, by prefixing the class and function with the final keyword.which essentially causes PHP to produced an error in the event that anybody attempts to extend a final class or override final function.
we can only use the final keyword with methods and classes.
Let's demonstrate the concept with the help of the below examples.
We can't override the parent class function.
<?php
class BaseClass{
final function calculate($val1,$val2){
$sum = $val1+$val2;
echo "Sum of given no=".$sum;
}
}
class ChildClass extends BaseClass{
function calculate($x,$y){
$mult=$val1*$val2;
echo "Multiplication of given no=".$mult;
}
}
$obj= new ChildClass();
$obj->show(10,10);
?>
PHP Fatal error: Cannot override final method BaseClass::calculate()
In the above example the class BaseClass which is parent class. In which the calculate method is marked as final. It implies that we cannot override the show method in any of its child classes. To identify the error ChildClass is trying to define the final method show (). This will produce a fatal error, It implies that the final method of parent class can't be defined in its child class.
Utilize of "Final" keyword Before The Class
<?php
final Class BaseClass{
function printData($val1,$val2){
$add=$val1+$val2;
echo "Sum of given no=".$s;
}
}
class Child extends BaseClass{
function printData($val1,$val2){
$m=$val1*$val2;
echo "Multiplication of given no=".$m;
}
}
$obj= new Child();
$obj->printData(20,20);
?>
PHP Fatal error: Class Child may not inherit from final class (BaseClass)
In the above example class BaseClass define with the final, that result we can not extend this class. When class Child tries to extend from BaseClass ( which implies Child is the child class of BaseClass). For this situation, PHP throws an error message “Class Child may not inherit from the final class (BaseClass)”.It implies that it won't permit creating any child class of BaseClass.
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "The final keyword is introduced by PHP5 related to the object-oriented programming concept."
},
{
"code": null,
"e": 1789,
"s": 1154,
"text": "But before we move on to the final, we need to ensure that we have a good understanding of the inheritance concept. In inheritance, we can inherit a class from another class. Also, we can override a function in an inherited class, to replace the behavior originally provided. In some cases, we might need to keep a class from being inherited from or we may need to prevent a function to be overridden. This can be achieved with the final, by prefixing the class and function with the final keyword.which essentially causes PHP to produced an error in the event that anybody attempts to extend a final class or override final function."
},
{
"code": null,
"e": 1849,
"s": 1789,
"text": "we can only use the final keyword with methods and classes."
},
{
"code": null,
"e": 1916,
"s": 1849,
"text": "Let's demonstrate the concept with the help of the below examples."
},
{
"code": null,
"e": 1961,
"s": 1916,
"text": "We can't override the parent class function."
},
{
"code": null,
"e": 2341,
"s": 1961,
"text": "<?php\n class BaseClass{\n final function calculate($val1,$val2){\n $sum = $val1+$val2;\n echo \"Sum of given no=\".$sum;\n }\n }\n class ChildClass extends BaseClass{\n function calculate($x,$y){\n $mult=$val1*$val2;\n echo \"Multiplication of given no=\".$mult;\n }\n }\n $obj= new ChildClass();\n $obj->show(10,10);\n?>"
},
{
"code": null,
"e": 2410,
"s": 2341,
"text": "PHP Fatal error: Cannot override final method BaseClass::calculate()"
},
{
"code": null,
"e": 2803,
"s": 2410,
"text": "In the above example the class BaseClass which is parent class. In which the calculate method is marked as final. It implies that we cannot override the show method in any of its child classes. To identify the error ChildClass is trying to define the final method show (). This will produce a fatal error, It implies that the final method of parent class can't be defined in its child class."
},
{
"code": null,
"e": 2847,
"s": 2803,
"text": "Utilize of \"Final\" keyword Before The Class"
},
{
"code": null,
"e": 3218,
"s": 2847,
"text": "<?php\n final Class BaseClass{\n function printData($val1,$val2){\n $add=$val1+$val2;\n echo \"Sum of given no=\".$s;\n }\n }\n class Child extends BaseClass{\n function printData($val1,$val2){\n $m=$val1*$val2;\n echo \"Multiplication of given no=\".$m;\n }\n }\n $obj= new Child();\n $obj->printData(20,20);\n?>"
},
{
"code": null,
"e": 3292,
"s": 3218,
"text": "PHP Fatal error: Class Child may not inherit from final class (BaseClass)"
},
{
"code": null,
"e": 3680,
"s": 3292,
"text": "In the above example class BaseClass define with the final, that result we can not extend this class. When class Child tries to extend from BaseClass ( which implies Child is the child class of BaseClass). For this situation, PHP throws an error message “Class Child may not inherit from the final class (BaseClass)”.It implies that it won't permit creating any child class of BaseClass."
}
] |
Black Hole Machine Learning. Neural Networks vie Theoretical Physics | by Amelie Schreiber | Towards Data Science
|
Hosted on Sketchviz
# http://www.graphviz.org/content/clustergraph G { node [style=filled,color=pink]; q0 -- H0 -- U -- V0 -- W0 -- A; q1 -- H1 -- U -- V1 -- W0 -- B; q2 -- H2 -- U -- V2 -- W1 -- C; q3 -- H3 -- U -- V3 -- W1 -- D; q4 -- H4 -- U -- V4 -- W2 -- E;}
In this article, we provide some links to significant and interesting code and software for using tensor networks, a mathematical tool used in gravitational physics and the study of black holes. The code we will be interested in will involve machine learning and applications to AI. We will go over a brief history of tensor networks and explain a little bit about what they are, and we’ll explain how they connect theoretical physics to machine learning and give some insight into why giants like Google are hiring physicists like Leonard Susskind to consult on their AI and machine learning algorithms. We’ll also show how quantum computing plays a role and how using quantum computers to create quantum enhanced AI and quantum machine learning algorithms forces us to rethink the way we understand information processing.
Earlier this year (June 2019), the AI blog for Google released a post about a library called “TensorNetwork” built for its infamous TensorFlow machine learning platform. It was built for the manipulation of tensor networks (we will go into a brief history of tensor networks and explain what they are below). Google’s work on developing this library was done in conjunction with X, Google’s moonshot factory for innovative tech, and the Perimeter Institute for Theoretical Physics. The Perimeter Institute was involved in the imaging of a black hole earlier this year. Along with their release of the code on Github, they wrote three research paper on applications and performance benchmarks for the TensorNetwork library:
TensorNetwork: A Library for Physics and Machine Learning
TensorNetwork on TensorFlow: A Spin Chain Application Using Tree Tensor Networks
TensorNetwork for Machine Learning
If you are interested in reading the documentation for TensorNetwork and digging into the code you can check out the Read the Docs page. So, why all the fuss? What’s so special about tensor networks, and how do black holes have anything to do with machine learning? What are... tensor networks?
Tensor Networks are a graphical notation for tensors used by physicists at least as far back as the 1970s by Roger Penrose in his graphical notation proposed in the paper in the paper “Applications of negative dimensional tensors”. He also mentions how tensor networks are applied to physics multiple times in his book The Road to Reality. Another somewhat obscure but incredibly thorough text written specifically on the topic of utilizing graphical tensor notation in representation theory is the book Group Theory: Birdtracks, Lie’s, and Exceptional Groups, by Predrag Cvitanovic. This book actually caught my attention years ago as an undergrad, not long after it was first released, specifically because I wanted to understand quantum gravity and how one could use such fascinating visual tools to do some very deep mathematics.
These graphical representations of tensors aren’t just pretty though, they actually form the foundation of some of the deepest and most fundamental ideas in theoretical physics today. They are used by physicists and mathematicians like Leonard Susskind, Roger Penrose, Juan Maldcena, and John Preskill to describe things like quantum information theory, the AdS/CFT correspondence, string theory, and the holographic principle.
Supervised Learning with Quantum-Inspired Tensor Networks
In this paper, E. Miles Stoudenmire, and David J. Schwab use tensor network models to perform machine learning classification of the handwriting data MNIST, using “matrix product states”. They are able to obtain <1% error. They also “ discuss how the tensor network form imparts additional structure to the learned model and suggest a possible generative interpretation”. Their code can be found in the Github repository.
Quimb is a python library for quantum information and many-body calculations, including with tensor networks. It is fast and optimized for efficiency. It is primarily intended for applications to physics problems, but can be adapted to other applications as well. It can run on a GPU and can compute tensor operations and representations in a geometry free way. It can optimize any tensor network with tensorflow or pytorch
It is useful for simulation of quantum computers since it is already setup for computations in IBM Qiskit. For many problems the simulation is efficient, but for high dimensional computations where the solution space of interest is not restricted by some kind of symmetry, quantum computers will of course be required in place of the classical simulations provided by Quimb.
In his article Quantum Computing in the NISQ era and beyond, John Preskill describes the current state of quantum computing on “Noisy Intermediate Scale Quantum (NISQ)” hardware. In his lectures, he discusses a “quantum information theory”, similar to the paper Physics, Topology, Logic and Computation: A Rosetta Stone, written by Google in collaboration with the mathematical physicist John C. Baez, and the computer scientist Mike Stay. One of the running themes in the paper is that we should rethink Information Theory.
In particular, the Google paper explains how to think of information theory in terms of quantum physics via tensor networks. It is not surprising that the standard notation in quantum computing, the quantum circuit diagram, is itself a tensor network.
In a short tutorial on the Google TensorNetwork library, I show how using the simultaneous contraction of edges can provide substantial speedups in computation. The code computes the runtime of a sequential contraction of edges, then a simultaneous contraction of the edges.
def one_edge_at_a_time(a, b): node1 = tn.Node(a) node2 = tn.Node(b) edge1 = node1[0] ^ node2[0] edge2 = node1[1] ^ node2[1] edge3 = node1[2] ^ node2[2] tn.contract(edge1) tn.contract(edge2) result = tn.contract(edge3) return result.tensordef use_contract_between(a, b): node1 = tn.Node(a) node2 = tn.Node(b) node1[0] ^ node2[0] node1[1] ^ node2[1] node1[2] ^ node2[2] # This is the same as # tn.contract_between(node1, node2) result = node1 @ node2 return result.tensora = np.ones((1000, 1000, 10))b = np.ones((1000, 1000, 10))%%timeone_edge_at_a_time(a, b)CPU times: user 15.7 s, sys: 1.88 s, total: 17.6 sWall time: 14.3 s
[29]:
array(10000000.)
This contracts the three edges sequentially, first red, then green, then blue, as visualized in the image generated using Graphviz:
# http://www.graphviz.org/content/clustergraph G0 { node [style=filled,color=pink]; edge [color = red]; a -- b; edge [color = green]; a -- b; edge [color = blue]; a -- b}
Hosted on Sketchviz
%%timeuse_contract_between(a, b)CPU times: user 495 ms, sys: 145 ms, total: 639 msWall time: 1.75 s
[33]:
array(10000000.)
Mathematically this translates into an inner product of rank three tensors:
Having algorithms such as this which perform more efficient computations on high dimensional tensors provides significant speedup (up to 100 times) as mentioned in this article. Add to the mix the new “Tensor Processing Units (TPUs)” that Google has designed to perform more efficient computations with tensors for machine learning purposes, and you have an extremely powerful machine learning framework, from hardware to cloud computing software to end-user application.
So far tensor network methods have found applications in image recognition, multi-class classification problems, computer vision, physics, materials science, bio-tech, quantum chemistry, and biophysics. Since TensorNetwork provides an easy way to integrate tensor networks into layers of standard neural networks, they can be used in any machine learning task involving neural networks.
While these methods may seem new to most of the machine learning community, they have a long history of applications in physics and mathematics, so the theory and conceptual understanding is well established in the mathematics and theoretical physics communities. This offers a new approach to understanding machine learning, and provides new intuition in an area that is plagued with “black box” methodology. Struggling to understand why AI makes certain decisions and comes to particular conclusions is a problem that is leading to concerns on how biased AI can be in certain applications to business solutions such as hiring assisted by AI. With law enforcement now applying AI in many cities, ensuring that AI is fair and is not making inhumane decisions is also becoming a concern on many minds. Add to that the improvements that tensor network methods can provide in machine learning tasks and computational efficiency, and it seems prudent to invest in researching and implementing these methods on a larger scale.
If you have ideas to share, questions, or if you are in need of consulting services for quantum machine learning contact the author via LinkedIn, visit The Singularity website, or checkout the Github tutorials.
|
[
{
"code": null,
"e": 192,
"s": 172,
"text": "Hosted on Sketchviz"
},
{
"code": null,
"e": 454,
"s": 192,
"text": "# http://www.graphviz.org/content/clustergraph G { node [style=filled,color=pink]; q0 -- H0 -- U -- V0 -- W0 -- A; q1 -- H1 -- U -- V1 -- W0 -- B; q2 -- H2 -- U -- V2 -- W1 -- C; q3 -- H3 -- U -- V3 -- W1 -- D; q4 -- H4 -- U -- V4 -- W2 -- E;}"
},
{
"code": null,
"e": 1279,
"s": 454,
"text": "In this article, we provide some links to significant and interesting code and software for using tensor networks, a mathematical tool used in gravitational physics and the study of black holes. The code we will be interested in will involve machine learning and applications to AI. We will go over a brief history of tensor networks and explain a little bit about what they are, and we’ll explain how they connect theoretical physics to machine learning and give some insight into why giants like Google are hiring physicists like Leonard Susskind to consult on their AI and machine learning algorithms. We’ll also show how quantum computing plays a role and how using quantum computers to create quantum enhanced AI and quantum machine learning algorithms forces us to rethink the way we understand information processing."
},
{
"code": null,
"e": 2002,
"s": 1279,
"text": "Earlier this year (June 2019), the AI blog for Google released a post about a library called “TensorNetwork” built for its infamous TensorFlow machine learning platform. It was built for the manipulation of tensor networks (we will go into a brief history of tensor networks and explain what they are below). Google’s work on developing this library was done in conjunction with X, Google’s moonshot factory for innovative tech, and the Perimeter Institute for Theoretical Physics. The Perimeter Institute was involved in the imaging of a black hole earlier this year. Along with their release of the code on Github, they wrote three research paper on applications and performance benchmarks for the TensorNetwork library:"
},
{
"code": null,
"e": 2060,
"s": 2002,
"text": "TensorNetwork: A Library for Physics and Machine Learning"
},
{
"code": null,
"e": 2141,
"s": 2060,
"text": "TensorNetwork on TensorFlow: A Spin Chain Application Using Tree Tensor Networks"
},
{
"code": null,
"e": 2176,
"s": 2141,
"text": "TensorNetwork for Machine Learning"
},
{
"code": null,
"e": 2471,
"s": 2176,
"text": "If you are interested in reading the documentation for TensorNetwork and digging into the code you can check out the Read the Docs page. So, why all the fuss? What’s so special about tensor networks, and how do black holes have anything to do with machine learning? What are... tensor networks?"
},
{
"code": null,
"e": 3305,
"s": 2471,
"text": "Tensor Networks are a graphical notation for tensors used by physicists at least as far back as the 1970s by Roger Penrose in his graphical notation proposed in the paper in the paper “Applications of negative dimensional tensors”. He also mentions how tensor networks are applied to physics multiple times in his book The Road to Reality. Another somewhat obscure but incredibly thorough text written specifically on the topic of utilizing graphical tensor notation in representation theory is the book Group Theory: Birdtracks, Lie’s, and Exceptional Groups, by Predrag Cvitanovic. This book actually caught my attention years ago as an undergrad, not long after it was first released, specifically because I wanted to understand quantum gravity and how one could use such fascinating visual tools to do some very deep mathematics."
},
{
"code": null,
"e": 3733,
"s": 3305,
"text": "These graphical representations of tensors aren’t just pretty though, they actually form the foundation of some of the deepest and most fundamental ideas in theoretical physics today. They are used by physicists and mathematicians like Leonard Susskind, Roger Penrose, Juan Maldcena, and John Preskill to describe things like quantum information theory, the AdS/CFT correspondence, string theory, and the holographic principle."
},
{
"code": null,
"e": 3791,
"s": 3733,
"text": "Supervised Learning with Quantum-Inspired Tensor Networks"
},
{
"code": null,
"e": 4213,
"s": 3791,
"text": "In this paper, E. Miles Stoudenmire, and David J. Schwab use tensor network models to perform machine learning classification of the handwriting data MNIST, using “matrix product states”. They are able to obtain <1% error. They also “ discuss how the tensor network form imparts additional structure to the learned model and suggest a possible generative interpretation”. Their code can be found in the Github repository."
},
{
"code": null,
"e": 4637,
"s": 4213,
"text": "Quimb is a python library for quantum information and many-body calculations, including with tensor networks. It is fast and optimized for efficiency. It is primarily intended for applications to physics problems, but can be adapted to other applications as well. It can run on a GPU and can compute tensor operations and representations in a geometry free way. It can optimize any tensor network with tensorflow or pytorch"
},
{
"code": null,
"e": 5012,
"s": 4637,
"text": "It is useful for simulation of quantum computers since it is already setup for computations in IBM Qiskit. For many problems the simulation is efficient, but for high dimensional computations where the solution space of interest is not restricted by some kind of symmetry, quantum computers will of course be required in place of the classical simulations provided by Quimb."
},
{
"code": null,
"e": 5537,
"s": 5012,
"text": "In his article Quantum Computing in the NISQ era and beyond, John Preskill describes the current state of quantum computing on “Noisy Intermediate Scale Quantum (NISQ)” hardware. In his lectures, he discusses a “quantum information theory”, similar to the paper Physics, Topology, Logic and Computation: A Rosetta Stone, written by Google in collaboration with the mathematical physicist John C. Baez, and the computer scientist Mike Stay. One of the running themes in the paper is that we should rethink Information Theory."
},
{
"code": null,
"e": 5789,
"s": 5537,
"text": "In particular, the Google paper explains how to think of information theory in terms of quantum physics via tensor networks. It is not surprising that the standard notation in quantum computing, the quantum circuit diagram, is itself a tensor network."
},
{
"code": null,
"e": 6064,
"s": 5789,
"text": "In a short tutorial on the Google TensorNetwork library, I show how using the simultaneous contraction of edges can provide substantial speedups in computation. The code computes the runtime of a sequential contraction of edges, then a simultaneous contraction of the edges."
},
{
"code": null,
"e": 6707,
"s": 6064,
"text": "def one_edge_at_a_time(a, b): node1 = tn.Node(a) node2 = tn.Node(b) edge1 = node1[0] ^ node2[0] edge2 = node1[1] ^ node2[1] edge3 = node1[2] ^ node2[2] tn.contract(edge1) tn.contract(edge2) result = tn.contract(edge3) return result.tensordef use_contract_between(a, b): node1 = tn.Node(a) node2 = tn.Node(b) node1[0] ^ node2[0] node1[1] ^ node2[1] node1[2] ^ node2[2] # This is the same as # tn.contract_between(node1, node2) result = node1 @ node2 return result.tensora = np.ones((1000, 1000, 10))b = np.ones((1000, 1000, 10))%%timeone_edge_at_a_time(a, b)CPU times: user 15.7 s, sys: 1.88 s, total: 17.6 sWall time: 14.3 s"
},
{
"code": null,
"e": 6713,
"s": 6707,
"text": "[29]:"
},
{
"code": null,
"e": 6730,
"s": 6713,
"text": "array(10000000.)"
},
{
"code": null,
"e": 6862,
"s": 6730,
"text": "This contracts the three edges sequentially, first red, then green, then blue, as visualized in the image generated using Graphviz:"
},
{
"code": null,
"e": 7054,
"s": 6862,
"text": "# http://www.graphviz.org/content/clustergraph G0 { node [style=filled,color=pink]; edge [color = red]; a -- b; edge [color = green]; a -- b; edge [color = blue]; a -- b}"
},
{
"code": null,
"e": 7074,
"s": 7054,
"text": "Hosted on Sketchviz"
},
{
"code": null,
"e": 7174,
"s": 7074,
"text": "%%timeuse_contract_between(a, b)CPU times: user 495 ms, sys: 145 ms, total: 639 msWall time: 1.75 s"
},
{
"code": null,
"e": 7180,
"s": 7174,
"text": "[33]:"
},
{
"code": null,
"e": 7197,
"s": 7180,
"text": "array(10000000.)"
},
{
"code": null,
"e": 7273,
"s": 7197,
"text": "Mathematically this translates into an inner product of rank three tensors:"
},
{
"code": null,
"e": 7745,
"s": 7273,
"text": "Having algorithms such as this which perform more efficient computations on high dimensional tensors provides significant speedup (up to 100 times) as mentioned in this article. Add to the mix the new “Tensor Processing Units (TPUs)” that Google has designed to perform more efficient computations with tensors for machine learning purposes, and you have an extremely powerful machine learning framework, from hardware to cloud computing software to end-user application."
},
{
"code": null,
"e": 8132,
"s": 7745,
"text": "So far tensor network methods have found applications in image recognition, multi-class classification problems, computer vision, physics, materials science, bio-tech, quantum chemistry, and biophysics. Since TensorNetwork provides an easy way to integrate tensor networks into layers of standard neural networks, they can be used in any machine learning task involving neural networks."
},
{
"code": null,
"e": 9154,
"s": 8132,
"text": "While these methods may seem new to most of the machine learning community, they have a long history of applications in physics and mathematics, so the theory and conceptual understanding is well established in the mathematics and theoretical physics communities. This offers a new approach to understanding machine learning, and provides new intuition in an area that is plagued with “black box” methodology. Struggling to understand why AI makes certain decisions and comes to particular conclusions is a problem that is leading to concerns on how biased AI can be in certain applications to business solutions such as hiring assisted by AI. With law enforcement now applying AI in many cities, ensuring that AI is fair and is not making inhumane decisions is also becoming a concern on many minds. Add to that the improvements that tensor network methods can provide in machine learning tasks and computational efficiency, and it seems prudent to invest in researching and implementing these methods on a larger scale."
}
] |
PHP while Loop
|
The while loop - Loops through
a block of code as long as the specified condition is true.
The while loop executes a block of code as long as the specified condition is true.
The example below displays the numbers from 1 to 5:
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration
This example counts to 100 by tens:
$x = 0; - Initialize the loop counter ($x), and set the start value to 0
$x <= 100 - Continue the loop as long as $x is less than or equal to 100
$x+=10; - Increase the loop counter value by 10 for each iteration
Output $i as long as $i is less than 6.
$i = 1;
($i < 6)
echo $i;
$i++;
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 92,
"s": 0,
"text": "The while loop - Loops through \na block of code as long as the specified condition is true."
},
{
"code": null,
"e": 176,
"s": 92,
"text": "The while loop executes a block of code as long as the specified condition is true."
},
{
"code": null,
"e": 228,
"s": 176,
"text": "The example below displays the numbers from 1 to 5:"
},
{
"code": null,
"e": 301,
"s": 228,
"text": "$x = 1; - Initialize the loop counter ($x), and set the start value to 1"
},
{
"code": null,
"e": 370,
"s": 301,
"text": "$x <= 5 - Continue the loop as long as $x is less than or equal to 5"
},
{
"code": null,
"e": 434,
"s": 370,
"text": "$x++; - Increase the loop counter value by 1 for each iteration"
},
{
"code": null,
"e": 470,
"s": 434,
"text": "This example counts to 100 by tens:"
},
{
"code": null,
"e": 543,
"s": 470,
"text": "$x = 0; - Initialize the loop counter ($x), and set the start value to 0"
},
{
"code": null,
"e": 616,
"s": 543,
"text": "$x <= 100 - Continue the loop as long as $x is less than or equal to 100"
},
{
"code": null,
"e": 683,
"s": 616,
"text": "$x+=10; - Increase the loop counter value by 10 for each iteration"
},
{
"code": null,
"e": 723,
"s": 683,
"text": "Output $i as long as $i is less than 6."
},
{
"code": null,
"e": 765,
"s": 723,
"text": "$i = 1; \n\n ($i < 6) \n echo $i;\n $i++;\n\n"
},
{
"code": null,
"e": 798,
"s": 765,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 840,
"s": 798,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 947,
"s": 840,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 966,
"s": 947,
"text": "help@w3schools.com"
}
] |
Puppet - Resource
|
Resources are one of the key fundamental units of Puppet used to design and build any particular infrastructure or a machine. They are mainly used for modeling and maintaining system configurations. Puppet has multiple type of resources, which can be used to define the system architecture or the user has the leverage to build and define a new resource.
The block of Puppet code in manifest file or any other file is called a resource declaration. The block of code is written in a language called Declarative Modelling Language (DML). Following is an example of how it looks like.
user { 'vipin':
ensure => present,
uid => '552',
shell => '/bin/bash',
home => '/home/vipin',
}
In Puppet, resource declaration for any particular resource type is done in code block. In the following example, the user is made up of mainly four pre-defined parameters.
Resource Type − In the above code snippet, it is the user.
Resource Type − In the above code snippet, it is the user.
Resource Parameter − In the above code snippet, it is Vipin.
Resource Parameter − In the above code snippet, it is Vipin.
Attributes − In the above code snippet, it is ensure, uid, shell, home.
Attributes − In the above code snippet, it is ensure, uid, shell, home.
Values − These are the values that correspond to each property.
Values − These are the values that correspond to each property.
Each resource type has its own way of defining definitions and parameters, and the user has the privilege to pick and choose the way he wants his resource to look like.
There are different types of resources available in Puppet which have their own way of functionality. These resource types can be viewed using the “describe” command along with the “-list” option.
[root@puppetmaster ~]# puppet describe --list
These are the types known to puppet:
augeas - Apply a change or an array of changes to the ...
computer - Computer object management using DirectorySer ...
cron - Installs and manages cron jobs
exec - Executes external commands
file - Manages files, including their content, owner ...
filebucket - A repository for storing and retrieving file ...
group - Manage groups
host - Installs and manages host entries
interface - This represents a router or switch interface
k5login - Manage the ‘.k5login’ file for a user
macauthorization - Manage the Mac OS X authorization database
mailalias - .. no documentation ..
maillist - Manage email lists
mcx - MCX object management using DirectoryService ...
mount - Manages mounted filesystems, including puttin ...
nagios_command - The Nagios type command
nagios_contact - The Nagios type contact
nagios_contactgroup - The Nagios type contactgroup
nagios_host - The Nagios type host
nagios_hostdependency - The Nagios type hostdependency
nagios_hostescalation - The Nagios type hostescalation
nagios_hostextinfo - The Nagios type hostextinfo
nagios_hostgroup - The Nagios type hostgroup
nagios_service - The Nagios type service
nagios_servicedependency - The Nagios type servicedependency
nagios_serviceescalation - The Nagios type serviceescalation
nagios_serviceextinfo - The Nagios type serviceextinfo
nagios_servicegroup - The Nagios type servicegroup
nagios_timeperiod - The Nagios type timeperiod
notify - .. no documentation ..
package - Manage packages
resources - This is a metatype that can manage other reso ...
router - .. no documentation ..
schedule - Define schedules for Puppet
scheduled_task - Installs and manages Windows Scheduled Tasks
selboolean - Manages SELinux booleans on systems with SELi ...
service - Manage running services
ssh_authorized_key - Manages SSH authorized keys
sshkey - Installs and manages ssh host keys
stage - A resource type for creating new run stages
tidy - Remove unwanted files based on specific crite ...
user - Manage users
vlan - .. no documentation ..
whit - Whits are internal artifacts of Puppet's curr ...
yumrepo - The client-side description of a yum reposito ...
zfs - Manage zfs
zone - Manages Solaris zones
zpool - Manage zpools
In the above code snippet, we have resource title as vipin which is unique for each resource used in the same file of the code. This is a unique title for this user resource type. We cannot have a resource with the same name because it will cause conflicts.
Resource command can be used to view the list of all the resources using type user.
[root@puppetmaster ~]# puppet resource user
user { 'abrt':
ensure => 'present',
gid => '173',
home => '/etc/abrt',
password => '!!',
password_max_age => '-1',
password_min_age => '-1',
shell => '/sbin/nologin',
uid => '173',
}
user { 'admin':
ensure => 'present',
comment => 'admin',
gid => '444',
groups => ['sys', 'admin'],
home => '/var/admin',
password => '*',
password_max_age => '99999',
password_min_age => '0',
shell => '/sbin/nologin',
uid => '55',
}
user { 'tomcat':
ensure => 'present',
comment => 'tomcat',
gid => '100',
home => '/var/www',
password => '!!',
password_max_age => '-1',
password_min_age => '-1',
shell => '/sbin/nologin',
uid => '100',
}
[root@puppetmaster ~]# puppet resource user tomcat
user { 'apache':
ensure => 'present',
comment => 'tomcat',
gid => '100',
home => '/var/www',
password => '!!',
password_max_age => '-1',
password_min_age => '-1',
shell => '/sbin/nologin',
uid => '100’,
}
The main body of any resource is made up of a collection of attribute-value pairs. Here one can specify the values for a given resource’s property. Each resource type has its own set of attributes that can be configured with the key-value pairs.
Describe the sub-command that can be used to get more details about a particular resources attribute. In the following example, we have the details about the user resource along with all its configurable attributes.
[root@puppetmaster ~]# puppet describe user
user
====
Manage users. This type is mostly built to manage system users,
so it is lacking some features useful for managing normal users.
This resource type uses the prescribed native tools for creating groups
and generally uses POSIX APIs for retrieving information about them.
It does not directly modify ‘/etc/passwd’ or anything.
**Autorequires:** If Puppet is managing the user's primary group
(as provided in the ‘gid’ attribute),
the user resource will autorequire that group.
If Puppet is managing any role accounts corresponding to the user's roles,
the user resource will autorequire those role accounts.
Parameters
----------
- **allowdupe**
Whether to allow duplicate UIDs. Defaults to ‘false’.
Valid values are ‘true’, ‘false’, ‘yes’, ‘no’.
- **attribute_membership**
Whether specified attribute value pairs should be treated as the
**complete list** (‘inclusive’) or the **minimum list** (‘minimum’) of
attribute/value pairs for the user. Defaults to ‘minimum’.
Valid values are ‘inclusive’, ‘minimum’.
- **auths**
The auths the user has. Multiple auths should be
specified as an array.
Requires features manages_solaris_rbac.
- **comment**
A description of the user. Generally the user's full name.
- **ensure**
The basic state that the object should be in.
Valid values are ‘present’, ‘absent’, ‘role’.
- **expiry**
The expiry date for this user. Must be provided in
a zero-padded YYYY-MM-DD format --- e.g. 2010-02-19.
If you want to make sure the user account does never
expire, you can pass the special value ‘absent’.
Valid values are ‘absent’. Values can match ‘/^\d{4}-\d{2}-\d{2}$/’.
Requires features manages_expiry.
- **forcelocal**
Forces the mangement of local accounts when accounts are also
being managed by some other NSS
- **gid**
The user's primary group. Can be specified numerically or by name.
This attribute is not supported on Windows systems; use the ‘groups’
attribute instead. (On Windows, designating a primary group is only
meaningful for domain accounts, which Puppet does not currently manage.)
- **groups**
The groups to which the user belongs. The primary group should
not be listed, and groups should be identified by name rather than by
GID. Multiple groups should be specified as an array.
- **home**
The home directory of the user. The directory must be created
separately and is not currently checked for existence.
- **ia_load_module**
The name of the I&A module to use to manage this user.
Requires features manages_aix_lam.
- **iterations**
This is the number of iterations of a chained computation of the
password hash (http://en.wikipedia.org/wiki/PBKDF2). This parameter
is used in OS X. This field is required for managing passwords on OS X
>= 10.8.
Requires features manages_password_salt.
- **key_membership**
- **managehome**
Whether to manage the home directory when managing the user.
This will create the home directory when ‘ensure => present’, and
delete the home directory when ‘ensure => absent’. Defaults to ‘false’.
Valid values are ‘true’, ‘false’, ‘yes’, ‘no’.
- **membership**
Whether specified groups should be considered the **complete list**
(‘inclusive’) or the **minimum list** (‘minimum’) of groups to which
the user belongs. Defaults to ‘minimum’.
Valid values are ‘inclusive’, ‘minimum’.
- **name**
The user name. While naming limitations vary by operating system,
it is advisable to restrict names to the lowest common denominator,
which is a maximum of 8 characters beginning with a letter.
Note that Puppet considers user names to be case-sensitive, regardless
of the platform's own rules; be sure to always use the same case when
referring to a given user.
- **password**
The user's password, in whatever encrypted format the local
system requires.
* Most modern Unix-like systems use salted SHA1 password hashes. You can use
Puppet's built-in ‘sha1’ function to generate a hash from a password.
* Mac OS X 10.5 and 10.6 also use salted SHA1 hashes.
Windows API
for setting the password hash.
[stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/
Be sure to enclose any value that includes a dollar sign ($) in single
quotes (') to avoid accidental variable interpolation.
Requires features manages_passwords.
- **password_max_age**
The maximum number of days a password may be used before it must be changed.
Requires features manages_password_age.
- **password_min_age**
The minimum number of days a password must be used before it may be changed.
Requires features manages_password_age.
- **profile_membership**
Whether specified roles should be treated as the **complete list**
(‘inclusive’) or the **minimum list** (‘minimum’) of roles
of which the user is a member. Defaults to ‘minimum’.
Valid values are ‘inclusive’, ‘minimum’.
- **profiles**
The profiles the user has. Multiple profiles should be
specified as an array.
Requires features manages_solaris_rbac.
- **project**
The name of the project associated with a user.
Requires features manages_solaris_rbac.
- **uid**
The user ID; must be specified numerically. If no user ID is
specified when creating a new user, then one will be chosen
automatically. This will likely result in the same user having
different UIDs on different systems, which is not recommended. This is
especially noteworthy when managing the same user on both Darwin and
other platforms, since Puppet does UID generation on Darwin, but
the underlying tools do so on other platforms.
On Windows, this property is read-only and will return the user's
security identifier (SID).
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2528,
"s": 2173,
"text": "Resources are one of the key fundamental units of Puppet used to design and build any particular infrastructure or a machine. They are mainly used for modeling and maintaining system configurations. Puppet has multiple type of resources, which can be used to define the system architecture or the user has the leverage to build and define a new resource."
},
{
"code": null,
"e": 2756,
"s": 2528,
"text": "The block of Puppet code in manifest file or any other file is called a resource declaration. The block of code is written in a language called Declarative Modelling Language (DML). Following is an example of how it looks like."
},
{
"code": null,
"e": 2875,
"s": 2756,
"text": "user { 'vipin': \n ensure => present, \n uid => '552', \n shell => '/bin/bash', \n home => '/home/vipin', \n}"
},
{
"code": null,
"e": 3048,
"s": 2875,
"text": "In Puppet, resource declaration for any particular resource type is done in code block. In the following example, the user is made up of mainly four pre-defined parameters."
},
{
"code": null,
"e": 3107,
"s": 3048,
"text": "Resource Type − In the above code snippet, it is the user."
},
{
"code": null,
"e": 3166,
"s": 3107,
"text": "Resource Type − In the above code snippet, it is the user."
},
{
"code": null,
"e": 3227,
"s": 3166,
"text": "Resource Parameter − In the above code snippet, it is Vipin."
},
{
"code": null,
"e": 3288,
"s": 3227,
"text": "Resource Parameter − In the above code snippet, it is Vipin."
},
{
"code": null,
"e": 3360,
"s": 3288,
"text": "Attributes − In the above code snippet, it is ensure, uid, shell, home."
},
{
"code": null,
"e": 3432,
"s": 3360,
"text": "Attributes − In the above code snippet, it is ensure, uid, shell, home."
},
{
"code": null,
"e": 3496,
"s": 3432,
"text": "Values − These are the values that correspond to each property."
},
{
"code": null,
"e": 3560,
"s": 3496,
"text": "Values − These are the values that correspond to each property."
},
{
"code": null,
"e": 3729,
"s": 3560,
"text": "Each resource type has its own way of defining definitions and parameters, and the user has the privilege to pick and choose the way he wants his resource to look like."
},
{
"code": null,
"e": 3926,
"s": 3729,
"text": "There are different types of resources available in Puppet which have their own way of functionality. These resource types can be viewed using the “describe” command along with the “-list” option."
},
{
"code": null,
"e": 6546,
"s": 3926,
"text": "[root@puppetmaster ~]# puppet describe --list \nThese are the types known to puppet: \naugeas - Apply a change or an array of changes to the ... \ncomputer - Computer object management using DirectorySer ... \ncron - Installs and manages cron jobs \nexec - Executes external commands \nfile - Manages files, including their content, owner ... \nfilebucket - A repository for storing and retrieving file ... \ngroup - Manage groups \nhost - Installs and manages host entries \ninterface - This represents a router or switch interface \nk5login - Manage the ‘.k5login’ file for a user \nmacauthorization - Manage the Mac OS X authorization database \nmailalias - .. no documentation .. \nmaillist - Manage email lists \nmcx - MCX object management using DirectoryService ... \nmount - Manages mounted filesystems, including puttin ... \nnagios_command - The Nagios type command \nnagios_contact - The Nagios type contact \nnagios_contactgroup - The Nagios type contactgroup \nnagios_host - The Nagios type host \nnagios_hostdependency - The Nagios type hostdependency \nnagios_hostescalation - The Nagios type hostescalation \nnagios_hostextinfo - The Nagios type hostextinfo \nnagios_hostgroup - The Nagios type hostgroup \n\nnagios_service - The Nagios type service \nnagios_servicedependency - The Nagios type servicedependency \nnagios_serviceescalation - The Nagios type serviceescalation \nnagios_serviceextinfo - The Nagios type serviceextinfo \nnagios_servicegroup - The Nagios type servicegroup \nnagios_timeperiod - The Nagios type timeperiod \nnotify - .. no documentation .. \npackage - Manage packages \nresources - This is a metatype that can manage other reso ... \nrouter - .. no documentation .. \nschedule - Define schedules for Puppet \nscheduled_task - Installs and manages Windows Scheduled Tasks \nselboolean - Manages SELinux booleans on systems with SELi ... \nservice - Manage running services \nssh_authorized_key - Manages SSH authorized keys \nsshkey - Installs and manages ssh host keys \nstage - A resource type for creating new run stages \ntidy - Remove unwanted files based on specific crite ... \nuser - Manage users \nvlan - .. no documentation .. \nwhit - Whits are internal artifacts of Puppet's curr ... \nyumrepo - The client-side description of a yum reposito ... \nzfs - Manage zfs \nzone - Manages Solaris zones \nzpool - Manage zpools \n"
},
{
"code": null,
"e": 6805,
"s": 6546,
"text": "In the above code snippet, we have resource title as vipin which is unique for each resource used in the same file of the code. This is a unique title for this user resource type. We cannot have a resource with the same name because it will cause conflicts."
},
{
"code": null,
"e": 6889,
"s": 6805,
"text": "Resource command can be used to view the list of all the resources using type user."
},
{
"code": null,
"e": 7900,
"s": 6889,
"text": "[root@puppetmaster ~]# puppet resource user \nuser { 'abrt': \n ensure => 'present', \n gid => '173', \n home => '/etc/abrt', \n password => '!!', \n password_max_age => '-1', \n password_min_age => '-1', \n shell => '/sbin/nologin', \n uid => '173', \n} \n\nuser { 'admin': \n ensure => 'present', \n comment => 'admin', \n gid => '444', \n groups => ['sys', 'admin'], \n home => '/var/admin', \n password => '*', \n password_max_age => '99999', \n password_min_age => '0', \n shell => '/sbin/nologin', \n uid => '55', \n} \n\nuser { 'tomcat': \n ensure => 'present', \n comment => 'tomcat', \n gid => '100', \n home => '/var/www', \n password => '!!', \n password_max_age => '-1', \n password_min_age => '-1', \n shell => '/sbin/nologin', \n uid => '100', \n} "
},
{
"code": null,
"e": 8270,
"s": 7900,
"text": "[root@puppetmaster ~]# puppet resource user tomcat \nuser { 'apache': \n ensure => 'present', \n comment => 'tomcat', \n gid => '100', \n home => '/var/www', \n password => '!!', \n password_max_age => '-1', \n password_min_age => '-1', \n shell => '/sbin/nologin', \n uid => '100’, \n}"
},
{
"code": null,
"e": 8516,
"s": 8270,
"text": "The main body of any resource is made up of a collection of attribute-value pairs. Here one can specify the values for a given resource’s property. Each resource type has its own set of attributes that can be configured with the key-value pairs."
},
{
"code": null,
"e": 8732,
"s": 8516,
"text": "Describe the sub-command that can be used to get more details about a particular resources attribute. In the following example, we have the details about the user resource along with all its configurable attributes."
},
{
"code": null,
"e": 14701,
"s": 8732,
"text": "[root@puppetmaster ~]# puppet describe user \nuser \n==== \nManage users. This type is mostly built to manage system users, \nso it is lacking some features useful for managing normal users. \n\nThis resource type uses the prescribed native tools for creating groups \nand generally uses POSIX APIs for retrieving information about them.\nIt does not directly modify ‘/etc/passwd’ or anything. \n\n**Autorequires:** If Puppet is managing the user's primary group \n(as provided in the ‘gid’ attribute), \nthe user resource will autorequire that group. \nIf Puppet is managing any role accounts corresponding to the user's roles, \nthe user resource will autorequire those role accounts. \n\nParameters \n---------- \n- **allowdupe** \n Whether to allow duplicate UIDs. Defaults to ‘false’. \n Valid values are ‘true’, ‘false’, ‘yes’, ‘no’. \n\n- **attribute_membership** \n Whether specified attribute value pairs should be treated as the \n **complete list** (‘inclusive’) or the **minimum list** (‘minimum’) of \n attribute/value pairs for the user. Defaults to ‘minimum’. \n Valid values are ‘inclusive’, ‘minimum’. \n\n- **auths** \n The auths the user has. Multiple auths should be \n specified as an array. \n Requires features manages_solaris_rbac. \n\n- **comment** \n A description of the user. Generally the user's full name. \n\n- **ensure** \n The basic state that the object should be in. \n Valid values are ‘present’, ‘absent’, ‘role’. \n\n- **expiry**\n The expiry date for this user. Must be provided in \n a zero-padded YYYY-MM-DD format --- e.g. 2010-02-19. \n If you want to make sure the user account does never \n expire, you can pass the special value ‘absent’. \n Valid values are ‘absent’. Values can match ‘/^\\d{4}-\\d{2}-\\d{2}$/’. \n Requires features manages_expiry. \n\n- **forcelocal** \n Forces the mangement of local accounts when accounts are also \n being managed by some other NSS \n\n- **gid** \n The user's primary group. Can be specified numerically or by name. \n This attribute is not supported on Windows systems; use the ‘groups’ \n attribute instead. (On Windows, designating a primary group is only \n meaningful for domain accounts, which Puppet does not currently manage.) \n\n- **groups** \n The groups to which the user belongs. The primary group should \n not be listed, and groups should be identified by name rather than by \n GID. Multiple groups should be specified as an array. \n\n- **home** \n The home directory of the user. The directory must be created \n separately and is not currently checked for existence. \n\n- **ia_load_module** \n The name of the I&A module to use to manage this user. \n Requires features manages_aix_lam. \n\n- **iterations** \n This is the number of iterations of a chained computation of the \n password hash (http://en.wikipedia.org/wiki/PBKDF2). This parameter \n is used in OS X. This field is required for managing passwords on OS X \n >= 10.8. \n Requires features manages_password_salt. \n\n- **key_membership** \n\n- **managehome** \n Whether to manage the home directory when managing the user. \n This will create the home directory when ‘ensure => present’, and \n delete the home directory when ‘ensure => absent’. Defaults to ‘false’. \n Valid values are ‘true’, ‘false’, ‘yes’, ‘no’. \n\n- **membership** \n Whether specified groups should be considered the **complete list** \n (‘inclusive’) or the **minimum list** (‘minimum’) of groups to which \n the user belongs. Defaults to ‘minimum’. \n Valid values are ‘inclusive’, ‘minimum’. \n\n- **name** \n The user name. While naming limitations vary by operating system, \n it is advisable to restrict names to the lowest common denominator, \n which is a maximum of 8 characters beginning with a letter. \n Note that Puppet considers user names to be case-sensitive, regardless \n of the platform's own rules; be sure to always use the same case when \n referring to a given user. \n\n- **password** \n The user's password, in whatever encrypted format the local \n system requires. \n * Most modern Unix-like systems use salted SHA1 password hashes. You can use \n Puppet's built-in ‘sha1’ function to generate a hash from a password. \n * Mac OS X 10.5 and 10.6 also use salted SHA1 hashes. \n\nWindows API \n for setting the password hash. \n [stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/ \n Be sure to enclose any value that includes a dollar sign ($) in single \n quotes (') to avoid accidental variable interpolation. \n Requires features manages_passwords. \n\n- **password_max_age** \n The maximum number of days a password may be used before it must be changed. \n Requires features manages_password_age. \n\n- **password_min_age** \n The minimum number of days a password must be used before it may be changed. \n Requires features manages_password_age. \n\n- **profile_membership** \n Whether specified roles should be treated as the **complete list** \n (‘inclusive’) or the **minimum list** (‘minimum’) of roles \n of which the user is a member. Defaults to ‘minimum’. \n Valid values are ‘inclusive’, ‘minimum’. \n\n- **profiles** \n The profiles the user has. Multiple profiles should be \n specified as an array. \n Requires features manages_solaris_rbac. \n\n- **project** \n The name of the project associated with a user. \n Requires features manages_solaris_rbac. \n\n- **uid** \n The user ID; must be specified numerically. If no user ID is \n specified when creating a new user, then one will be chosen \n automatically. This will likely result in the same user having \n different UIDs on different systems, which is not recommended. This is \n especially noteworthy when managing the same user on both Darwin and \n other platforms, since Puppet does UID generation on Darwin, but \n the underlying tools do so on other platforms. \n On Windows, this property is read-only and will return the user's \n security identifier (SID). "
},
{
"code": null,
"e": 14708,
"s": 14701,
"text": " Print"
},
{
"code": null,
"e": 14719,
"s": 14708,
"text": " Add Notes"
}
] |
Difference Between for and while loop
|
In this post, we will understand the difference between the ‘for’ and the ‘while’ loop.
The initialization, condition checking, and the iteration statements are written at the beginning of the loop.
The initialization, condition checking, and the iteration statements are written at the beginning of the loop.
It is used only when the number of iterations is known beforehand.
It is used only when the number of iterations is known beforehand.
If the condition is not mentioned in the 'for' loop, then the loop iterates infinite number of times.
If the condition is not mentioned in the 'for' loop, then the loop iterates infinite number of times.
The initialization is done only once, and it is never repeated.
The initialization is done only once, and it is never repeated.
The iteration statement is written at the beginning.
The iteration statement is written at the beginning.
Hence, it executes once all statements in loop have been executed.
Hence, it executes once all statements in loop have been executed.
for(initialization; condition; iteration){
//body of the 'for' loop
}
Following is the flowchart of for loop −
The initialization and the condition checking is done at the beginning of the loop.
The initialization and the condition checking is done at the beginning of the loop.
It is used only when the number of iterations isn’t known.
It is used only when the number of iterations isn’t known.
If the condition is not mentioned in the 'while' loop, it results in a compilation error.
If the condition is not mentioned in the 'while' loop, it results in a compilation error.
If the initialization is done when the condition is being checked, then initialization occurs every time the loop is iterated through.
If the initialization is done when the condition is being checked, then initialization occurs every time the loop is iterated through.
The iteration statement can be written within any point inside the loop.
The iteration statement can be written within any point inside the loop.
while ( condition) {
statements;
//body of the loop
}
Following is the flowchart of while loop −
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In this post, we will understand the difference between the ‘for’ and the ‘while’ loop."
},
{
"code": null,
"e": 1261,
"s": 1150,
"text": "The initialization, condition checking, and the iteration statements are written at the beginning of the loop."
},
{
"code": null,
"e": 1372,
"s": 1261,
"text": "The initialization, condition checking, and the iteration statements are written at the beginning of the loop."
},
{
"code": null,
"e": 1439,
"s": 1372,
"text": "It is used only when the number of iterations is known beforehand."
},
{
"code": null,
"e": 1506,
"s": 1439,
"text": "It is used only when the number of iterations is known beforehand."
},
{
"code": null,
"e": 1608,
"s": 1506,
"text": "If the condition is not mentioned in the 'for' loop, then the loop iterates infinite number of times."
},
{
"code": null,
"e": 1710,
"s": 1608,
"text": "If the condition is not mentioned in the 'for' loop, then the loop iterates infinite number of times."
},
{
"code": null,
"e": 1774,
"s": 1710,
"text": "The initialization is done only once, and it is never repeated."
},
{
"code": null,
"e": 1838,
"s": 1774,
"text": "The initialization is done only once, and it is never repeated."
},
{
"code": null,
"e": 1891,
"s": 1838,
"text": "The iteration statement is written at the beginning."
},
{
"code": null,
"e": 1944,
"s": 1891,
"text": "The iteration statement is written at the beginning."
},
{
"code": null,
"e": 2011,
"s": 1944,
"text": "Hence, it executes once all statements in loop have been executed."
},
{
"code": null,
"e": 2078,
"s": 2011,
"text": "Hence, it executes once all statements in loop have been executed."
},
{
"code": null,
"e": 2151,
"s": 2078,
"text": "for(initialization; condition; iteration){\n //body of the 'for' loop\n}"
},
{
"code": null,
"e": 2192,
"s": 2151,
"text": "Following is the flowchart of for loop −"
},
{
"code": null,
"e": 2276,
"s": 2192,
"text": "The initialization and the condition checking is done at the beginning of the loop."
},
{
"code": null,
"e": 2360,
"s": 2276,
"text": "The initialization and the condition checking is done at the beginning of the loop."
},
{
"code": null,
"e": 2419,
"s": 2360,
"text": "It is used only when the number of iterations isn’t known."
},
{
"code": null,
"e": 2478,
"s": 2419,
"text": "It is used only when the number of iterations isn’t known."
},
{
"code": null,
"e": 2568,
"s": 2478,
"text": "If the condition is not mentioned in the 'while' loop, it results in a compilation error."
},
{
"code": null,
"e": 2658,
"s": 2568,
"text": "If the condition is not mentioned in the 'while' loop, it results in a compilation error."
},
{
"code": null,
"e": 2793,
"s": 2658,
"text": "If the initialization is done when the condition is being checked, then initialization occurs every time the loop is iterated through."
},
{
"code": null,
"e": 2928,
"s": 2793,
"text": "If the initialization is done when the condition is being checked, then initialization occurs every time the loop is iterated through."
},
{
"code": null,
"e": 3001,
"s": 2928,
"text": "The iteration statement can be written within any point inside the loop."
},
{
"code": null,
"e": 3074,
"s": 3001,
"text": "The iteration statement can be written within any point inside the loop."
},
{
"code": null,
"e": 3134,
"s": 3074,
"text": "while ( condition) {\n statements;\n //body of the loop\n}"
},
{
"code": null,
"e": 3177,
"s": 3134,
"text": "Following is the flowchart of while loop −"
}
] |
How to calculate transpose of a matrix using C program?
|
The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A.
The logic used to change m(i,j) matrix to m(j,i) is as follows −
for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
In this example, we shall print the transpose of a matrix using for loop.
Live Demo
#include <stdio.h>
int main(){
int m, n, i, j, matrix[10][10], transpose[10][10];
printf("Enter rows and columns :\n");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (i= 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &matrix[i][j]);
for (i = 0;i < m;i++)
for (j = 0; j < n; j++)
transpose[j][i] = matrix[i][j];
printf("Transpose of the matrix:\n");
for (i = 0; i< n; i++) {
for (j = 0; j < m; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
return 0;
}
Enter rows and columns :
2 3
Enter elements of the matrix
1 2 3
2 4 5
Transpose of the matrix:
1 2
2 4
3 5
Live Demo
#include<stdio.h>
#define ROW 2
#define COL 5
int main(){
int i, j, mat[ROW][COL], trans[COL][ROW];
printf("Enter matrix: \n");
// input matrix
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
scanf("%d", &mat[i][j]);
}
}
// create transpose
for(i = 0; i < ROW; i++){
for(j = 0; j < COL; j++){
trans[j][i] = mat[i][j];
}
}
printf("\nTranspose matrix: \n");
// print transpose
for(i = 0; i < COL; i++){
for(j = 0; j < ROW; j++){
printf("%d ", trans[i][j]);
}
printf("\n");
}
return 0;
}
Enter matrix:
1 2 3 4 5
5 4 3 2 1
Transpose matrix:
1 5
2 4
3 3
4 2
5 1
|
[
{
"code": null,
"e": 1301,
"s": 1062,
"text": "The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A."
},
{
"code": null,
"e": 1366,
"s": 1301,
"text": "The logic used to change m(i,j) matrix to m(j,i) is as follows −"
},
{
"code": null,
"e": 1453,
"s": 1366,
"text": "for (i = 0;i < m;i++)\n for (j = 0; j < n; j++)\n transpose[j][i] = matrix[i][j];"
},
{
"code": null,
"e": 1527,
"s": 1453,
"text": "In this example, we shall print the transpose of a matrix using for loop."
},
{
"code": null,
"e": 1538,
"s": 1527,
"text": " Live Demo"
},
{
"code": null,
"e": 2105,
"s": 1538,
"text": "#include <stdio.h>\nint main(){\n int m, n, i, j, matrix[10][10], transpose[10][10];\n printf(\"Enter rows and columns :\\n\");\n scanf(\"%d%d\", &m, &n);\n printf(\"Enter elements of the matrix\\n\");\n for (i= 0; i < m; i++)\n for (j = 0; j < n; j++)\n scanf(\"%d\", &matrix[i][j]);\n for (i = 0;i < m;i++)\n for (j = 0; j < n; j++)\n transpose[j][i] = matrix[i][j];\n printf(\"Transpose of the matrix:\\n\");\n for (i = 0; i< n; i++) {\n for (j = 0; j < m; j++)\n printf(\"%d\\t\", transpose[i][j]);\n printf(\"\\n\");\n }\n return 0;\n}"
},
{
"code": null,
"e": 2221,
"s": 2105,
"text": "Enter rows and columns :\n2 3\nEnter elements of the matrix\n1 2 3\n2 4 5\nTranspose of the matrix:\n1 2\n2 4\n3 5"
},
{
"code": null,
"e": 2232,
"s": 2221,
"text": " Live Demo"
},
{
"code": null,
"e": 2829,
"s": 2232,
"text": "#include<stdio.h>\n#define ROW 2\n#define COL 5\nint main(){\n int i, j, mat[ROW][COL], trans[COL][ROW];\n printf(\"Enter matrix: \\n\");\n // input matrix\n for(i = 0; i < ROW; i++){\n for(j = 0; j < COL; j++){\n scanf(\"%d\", &mat[i][j]);\n }\n }\n // create transpose\n for(i = 0; i < ROW; i++){\n for(j = 0; j < COL; j++){\n trans[j][i] = mat[i][j];\n }\n }\n printf(\"\\nTranspose matrix: \\n\");\n // print transpose\n for(i = 0; i < COL; i++){\n for(j = 0; j < ROW; j++){\n printf(\"%d \", trans[i][j]);\n }\n printf(\"\\n\");\n }\n return 0;\n}"
},
{
"code": null,
"e": 2902,
"s": 2829,
"text": "Enter matrix:\n1 2 3 4 5\n5 4 3 2 1\n\nTranspose matrix:\n1 5\n2 4\n3 3\n4 2\n5 1"
}
] |
Align gathered items at the end in Bootstrap 4
|
Use .align-content-end class to align gathered items at the end in Bootstrap 4.
To set the items at the end −
<div class="d-flex flex-wrap align-content-end”>
You need to now add the flex items as shown below −
<div class="d-flex flex-wrap align-content-end bg-primary" style="height:250px">
<div class="p-2 border">One</div>
<div class="p-2 border">Two</div>
<div class="p-2 border">Three</div>
<div class="p-2 border">Four</div>
<div class="p-2 border">Five</div>
<div class="p-2 border">Six</div>
</div>
Let us see an example to learn how to align gathered items at the end in Bootstrap 4 −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h2>Example</h2>
<div class="d-flex flex-wrap align-content-end bg-primary" style="height:250px">
<div class="p-2 border">One</div>
<div class="p-2 border">Two</div>
<div class="p-2 border">Three</div>
<div class="p-2 border">Four</div>
<div class="p-2 border">Five</div>
<div class="p-2 border">Six</div>
<div class="p-2 border">Seven</div>
<div class="p-2 border">Eight</div>
<div class="p-2 border">Nine</div>
<div class="p-2 border">Ten</div>
<div class="p-2 border">Eleven</div>
<div class="p-2 border">Twelve</div>
<div class="p-2 border">Thirteen</div>
<div class="p-2 border">Fourteen</div>
</div>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1142,
"s": 1062,
"text": "Use .align-content-end class to align gathered items at the end in Bootstrap 4."
},
{
"code": null,
"e": 1172,
"s": 1142,
"text": "To set the items at the end −"
},
{
"code": null,
"e": 1221,
"s": 1172,
"text": "<div class=\"d-flex flex-wrap align-content-end”>"
},
{
"code": null,
"e": 1273,
"s": 1221,
"text": "You need to now add the flex items as shown below −"
},
{
"code": null,
"e": 1581,
"s": 1273,
"text": "<div class=\"d-flex flex-wrap align-content-end bg-primary\" style=\"height:250px\">\n <div class=\"p-2 border\">One</div>\n <div class=\"p-2 border\">Two</div>\n <div class=\"p-2 border\">Three</div>\n <div class=\"p-2 border\">Four</div>\n <div class=\"p-2 border\">Five</div>\n <div class=\"p-2 border\">Six</div>\n</div>"
},
{
"code": null,
"e": 1668,
"s": 1581,
"text": "Let us see an example to learn how to align gathered items at the end in Bootstrap 4 −"
},
{
"code": null,
"e": 1678,
"s": 1668,
"text": "Live Demo"
},
{
"code": null,
"e": 2889,
"s": 1678,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n<div class=\"container mt-3\">\n <h2>Example</h2>\n <div class=\"d-flex flex-wrap align-content-end bg-primary\" style=\"height:250px\">\n <div class=\"p-2 border\">One</div>\n <div class=\"p-2 border\">Two</div>\n <div class=\"p-2 border\">Three</div>\n <div class=\"p-2 border\">Four</div>\n <div class=\"p-2 border\">Five</div>\n <div class=\"p-2 border\">Six</div>\n <div class=\"p-2 border\">Seven</div>\n <div class=\"p-2 border\">Eight</div>\n <div class=\"p-2 border\">Nine</div>\n <div class=\"p-2 border\">Ten</div>\n <div class=\"p-2 border\">Eleven</div>\n <div class=\"p-2 border\">Twelve</div>\n <div class=\"p-2 border\">Thirteen</div>\n <div class=\"p-2 border\">Fourteen</div>\n </div>\n </div>\n</body>\n</html>"
}
] |
Initialization of variables sized arrays in C - GeeksforGeeks
|
28 Sep, 2018
The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized.
For example, the following program compiles and runs fine on a C99 compatible compiler.
#include<stdio.h> int main(){ int M = 2; int arr[M][M]; int i, j; for (i = 0; i < M; i++) { for (j = 0; j < M; j++) { arr[i][j] = 0; printf ("%d ", arr[i][j]); } printf("\n"); } return 0;}
Output:
0 0
0 0
But the following fails with compilation error.
#include<stdio.h> int main(){ int M = 2; int arr[M][M] = {0}; // Trying to initialize all values as 0 int i, j; for (i = 0; i < M; i++) { for (j = 0; j < M; j++) printf ("%d ", arr[i][j]); printf("\n"); } return 0;}
Output:
Compiler Error: variable-sized object may not be initialized
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Array and String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
Different methods to reverse a string in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Structures in C
|
[
{
"code": null,
"e": 24654,
"s": 24626,
"text": "\n28 Sep, 2018"
},
{
"code": null,
"e": 24788,
"s": 24654,
"text": "The C99 standard allows variable sized arrays (see this). But, unlike the normal arrays, variable sized arrays cannot be initialized."
},
{
"code": null,
"e": 24876,
"s": 24788,
"text": "For example, the following program compiles and runs fine on a C99 compatible compiler."
},
{
"code": "#include<stdio.h> int main(){ int M = 2; int arr[M][M]; int i, j; for (i = 0; i < M; i++) { for (j = 0; j < M; j++) { arr[i][j] = 0; printf (\"%d \", arr[i][j]); } printf(\"\\n\"); } return 0;}",
"e": 25097,
"s": 24876,
"text": null
},
{
"code": null,
"e": 25105,
"s": 25097,
"text": "Output:"
},
{
"code": null,
"e": 25114,
"s": 25105,
"text": "0 0\n0 0\n"
},
{
"code": null,
"e": 25162,
"s": 25114,
"text": "But the following fails with compilation error."
},
{
"code": "#include<stdio.h> int main(){ int M = 2; int arr[M][M] = {0}; // Trying to initialize all values as 0 int i, j; for (i = 0; i < M; i++) { for (j = 0; j < M; j++) printf (\"%d \", arr[i][j]); printf(\"\\n\"); } return 0;}",
"e": 25398,
"s": 25162,
"text": null
},
{
"code": null,
"e": 25406,
"s": 25398,
"text": "Output:"
},
{
"code": null,
"e": 25468,
"s": 25406,
"text": "Compiler Error: variable-sized object may not be initialized\n"
},
{
"code": null,
"e": 25593,
"s": 25468,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25612,
"s": 25593,
"text": "C Array and String"
},
{
"code": null,
"e": 25623,
"s": 25612,
"text": "C Language"
},
{
"code": null,
"e": 25721,
"s": 25623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25730,
"s": 25721,
"text": "Comments"
},
{
"code": null,
"e": 25743,
"s": 25730,
"text": "Old Comments"
},
{
"code": null,
"e": 25771,
"s": 25743,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25783,
"s": 25771,
"text": "fork() in C"
},
{
"code": null,
"e": 25829,
"s": 25783,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 25861,
"s": 25829,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 25908,
"s": 25861,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 25925,
"s": 25908,
"text": "Substring in C++"
},
{
"code": null,
"e": 25947,
"s": 25925,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 25985,
"s": 25947,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26012,
"s": 25985,
"text": "Enumeration (or enum) in C"
}
] |
A Beginner’s Tutorial on Building an AI Image Classifier using PyTorch | by Alexander Wu | Towards Data Science
|
This is a step-by-step guide to build an image classifier. The AI model will be able to learn to label images. I use Python and Pytorch.
When we write a program, it is a huge hassle manually coding every small action we perform. Sometimes, we want to use packages of code other people have already written. These packaged routines are called Libraries and can be added into our program by importing them and then referencing the library later in the code.
We usually import all the libraries at the beginning of the program.
Instead of typing the library’s long name whenever we reference it, we can shorten it to a name of our choice using “as”.
# Import Librariesimport torchimport torchvision.transforms as transformsimport torchvision.datasets as datasetsimport torchvision.models as modelsimport torch.nn as nnimport torch.optim as optimimport numpy as npfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as plt
Next, we want to import the picture data our AI model will learn from.
But before that, we need to specify the alterations we want to perform on these pictures — since the same command that imports them also transforms the data.
These transforms are made using the torchvision.transforms library. The best way to understand the transforms is to read the documentation here. But I’ll give a brief of what each command is doing.
transforms.Compose lets us compose multiple transforms together so we can use more than one transformation.
transforms.Resize((255)) resizes the images so the shortest side has a length of 255 pixels. The other side is scaled to maintain the aspect ratio of the image.
transforms.CenterCrop(224) crops the center of the image so it is a 224 by 224 pixels square image.
We do these two steps so all the images going into our AI model have the same size (AI models can’t handle inputs with varying sizes)
transforms.ToTensor() converts our image into numbers. How does it do that?
It separates the three colors that every pixel of our picture is comprised of: red, green & blue. This essentially turns one image into three images (one tinted red, one green, one blue).
Then, it converts the pixels of each tinted image into the brightness of their color, from 0 to 255. These values are divided by 255, so they can be in a range of 0 to 1. Our image is now a Torch Tensor (a data structure that stores lots of numbers).
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) subtracts the mean from each value and then divides by the standard deviation.
We will be using a pre-trained model, so we need to use the means and standard deviations the Pytorch specifies. There are three values in the mean and standard deviation to match each RGB picture.
# Specify transforms using torchvision.transforms as transforms# librarytransformations = transforms.Compose([ transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
Finally, we can import our pictures into the program. We use the torchvision.datasets library.
Read about it here.
We specify two different data sets, one for the images that the AI learns from (the training set) and the other for the dataset we use to test the AI model (the validation set).
The datasets.ImageFolder() command expects our data to be organized in the following way: root/label/picture.png. In other words, the images should be sorted into folders. For example, all the pictures of bees should be in one folder, all the pictures of ants should be in another etc.
We give the command
the path to all the folders andthe transforms that we specified in the previous step.
the path to all the folders and
the transforms that we specified in the previous step.
# Load in each dataset and apply transformations using# the torchvision.datasets as datasets librarytrain_set = datasets.ImageFolder("root/label/train", transform = transformations)val_set = datasets.ImageFolder("root/label/valid", transform = transformations)
Then we want to put our imported images into a Dataloader.
Dataloader is able to spit out random samples of our data, so our model won’t have to deal with the entire dataset every time. This makes training more efficient.
We specify how many images we want at once as our batch_size (so 32 means we want to get 32 images at one time). We also want to shuffle our images so it gets inputted randomly into our AI model.
Read about the DataLoader here.
# Put into a Dataloader using torch librarytrain_loader = torch.utils.data.DataLoader(train_set, batch_size=32, shuffle=True)val_loader = torch.utils.data.DataLoader(val_set, batch_size =32, shuffle=True)
AI models need to be trained on a lot of data to be effective. Since we don’t have that much data, we want to take a pre-trained model (a model that has been previously trained on many images) but tailor it to recognize our specific images. This process is called transfer learning.
Image recognition models have two parts:
the convolutional part andthe classifier part
the convolutional part and
the classifier part
We want to keep the pre-trained convolutional part but put in our own classifier. Here’s why:
The convolution/pooling section of our model is used to recognize the features inside an image. It first identifies edges, then using the edges it identifies shapes, and using the shapes it can identify objects.
But it takes A LOT of data to train this section — probably more than we have — so instead, we can use the default, pre-trained convolutional layers. These pre-trained convolutional layers were trained to identify these feature very well, regardless of what kind of image you have.
There are also pooling layers in between convolutional layers that distill an image to a smaller size so it can be easily inputted to our classifier.
The last part of the model is the classifier. The classifier takes all the information extracted from the photo in the convolution part, and uses it to identify the image. This is the part of the pre-trained model we want to replace and to train on our own images. This makes the model tailored to identify the images we give it.
We use the torchvision.models library to download a pre-trained model. There are many different models we can download, and more info can be found here. I chose a model called densenet161 and specified that we want it to be pre-trained by setting pretrained=True.
Then, we want to make sure we don’t train this model since it is already trained, and we only want to train the classifier we will put in next. We tell the model not to calculate the gradients of any parameter since that is only done for training.
# Get pretrained model using torchvision.models as models librarymodel = models.densenet161(pretrained=True)# Turn off training for their parametersfor param in model.parameters(): param.requires_grad = False
Now we want to replace the default classifier of the model with our own classifier. Classifiers are fully connected neural networks, so to do this, we must first build our own neural network.
A neural network is just a method to find complex patterns and connections between numbers of the input and the output. In this case, it takes the features of the image that were highlighted by the convolution section to determine how likely the image is a certain label.
The first thing we want to do is to determine the amount of numbers inputted to our neural network. This has to match the amount of numbers that is outputted from the section before (the convolutional section). Since we didn’t change the convolutional section at all, the amount of numbers inputted in our classifier should be the same as the model’s default classifier.
Next, we want to determine the number of outputs. This number should match how many types of images you have. The model will give you a list of percentages, each corresponding to how certain the picture is to that label. So if you have images of bees, ants, and flies, there are 3 labels. and there should be 3 numbers in the output layer each corresponding to the probability of the input being a bee, ant, or fly.
Once we have those details, we use the torch.nn library to create the classifier. Information can be found here.
nn.Sequential can help us group multiple modules together.
nn.Linear specifies the interaction between two layers. We give it 2 numbers, specifying the number of nodes in the two layer.
For example, in the first nn.Linear, the first layer is the input layer, and we can choose how many numbers we want in the second layer (I went with 1024).
nn.ReLU is an activation function for hidden layers. Activation functions helps the model learn complex relationships between the input and the output. We use ReLU on all layers except for the output.
We repeat this for as many hidden layers as you want, with as many nodes as you want in each layer.
nn.LogSoftmax is the activation function for the output. The softmax function turns the outputted numbers into percentages for each label, and the log function is applied to make it computationally faster. We must specify that the output layer is a column, so we set dimension equal to 1.
After creating our own classifier, we replace the model’s default one.
# Create new classifier for model using torch.nn as nn libraryclassifier_input = model.classifier.in_featuresnum_labels = #PUT IN THE NUMBER OF LABELS IN YOUR DATAclassifier = nn.Sequential(nn.Linear(classifier_input, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, num_labels), nn.LogSoftmax(dim=1))# Replace default classifier with new classifiermodel.classifier = classifier
Now the model is created! Next, we just need to train it.
Training a model on a GPU is a lot faster than a CPU. So to determine which device is available for you, we use Torch to check. If there is a compatible GPU, we set the variable to GPU, if not, it sticks with CPU. We then move our model to this device.
# Find the device available to use using torch librarydevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Move model to the device specified abovemodel.to(device)
While training, we need to determine how “off” our model is. To evaluate the amount of error our model has, we use nn.NLLLoss. This function takes in the output of our model, for which we used the nn.LogSoftmax function.
To train our model, we take our error and see how we can adjust the weights we multiplied our numbers by to get the smallest error. The method of calculating how we adjust our weights and applying it to our weights is called Adam. We use the torch.optim library to use this method and give it our parameters.
# Set the error function using torch.nn as nn librarycriterion = nn.NLLLoss()# Set the optimizer function using torch.optim as optim libraryoptimizer = optim.Adam(model.classifier.parameters())
Now we train. We want our model to go through the entire dataset multiple times, so we use a for loop. Every time it has gone over the entire set of images, it is called an epoch. In one epoch we want the model to go through both the training set and the validation set.
We first set the model to training mode and we use a for-loop to go through every image.
After moving the images and the labels to the appropriate device, we need to clear the adjustments of the weights by declaring optimizer.zero_grad().
We can then compute the output of our model given our images and how “off” our model is given its output and the correct answers.
Then we can find the adjustments we need to make to decreases this error by calling loss.backward() and use our optimizer to adjust the weights by calling optimizer.step().
As we train, we want to know how things are going, so we keep track of the total errors we calculated and print out the progress of the training.
We set our model to evaluation mode and use a for-loop to iterate over all the images in our set.
We repeat the steps we took for the training set to get the output of our model and how much our model is “off” from the real labels.
Our model used the LogSoftmax function in order to increase computation speed, but now we want the real percentages, not the log percentages. So we use torch.exp to reverse the log function. We then want to see which class the model guessed for our images. .topk gives us the top class that was guessed, and what percentage it guessed it at — we only care about the class so we can ignore the percentage.
To determine how many images it guessed right, we check which guessed classes are equal to the real classes. Then we can average over the entire batch to determine the accuracy of our model (how many images it guessed right divided by the total amount of images).
After going through both the training and validation set, we want to print the errors for both and the accuracy of the validation set.
epochs = 10for epoch in range(epochs): train_loss = 0 val_loss = 0 accuracy = 0 # Training the model model.train() counter = 0 for inputs, labels in train_loader: # Move to device inputs, labels = inputs.to(device), labels.to(device) # Clear optimizers optimizer.zero_grad() # Forward pass output = model.forward(inputs) # Loss loss = criterion(output, labels) # Calculate gradients (backpropogation) loss.backward() # Adjust parameters based on gradients optimizer.step() # Add the loss to the training set's rnning loss train_loss += loss.item()*inputs.size(0) # Print the progress of our training counter += 1 print(counter, "/", len(train_loader)) # Evaluating the model model.eval() counter = 0 # Tell torch not to calculate gradients with torch.no_grad(): for inputs, labels in val_loader: # Move to device inputs, labels = inputs.to(device), labels.to(device) # Forward pass output = model.forward(inputs) # Calculate Loss valloss = criterion(output, labels) # Add loss to the validation set's running loss val_loss += valloss.item()*inputs.size(0) # Since our model outputs a LogSoftmax, find the real # percentages by reversing the log function output = torch.exp(output) # Get the top class of the output top_p, top_class = output.topk(1, dim=1) # See how many of the classes were correct? equals = top_class == labels.view(*top_class.shape) # Calculate the mean (get the accuracy for this batch) # and add it to the running accuracy for this epoch accuracy += torch.mean(equals.type(torch.FloatTensor)).item() # Print the progress of our evaluation counter += 1 print(counter, "/", len(val_loader)) # Get the average loss for the entire epoch train_loss = train_loss/len(train_loader.dataset) valid_loss = val_loss/len(val_loader.dataset) # Print out the information print('Accuracy: ', accuracy/len(val_loader)) print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(epoch, train_loss, valid_loss))
That was great! You’ve just built an AI image classifier. But, now we want to actually use it — we want to give it a random image and see which label it thinks it is.
First, we set the model for evaluation mode.
model.eval()
Then we create a function that can process the image so it can be inputted into our model.
We open the image, resize it by keeping the aspect ratio but making the shortest side only 255 px, and crop the center 224px by 224px. We then turn the picture into an array and make sure that the number of color channels is the first dimension instead of the last dimension by transposing the array. Next, we convert each value between 0 and 1 by dividing by 255. We then normalize the values by subtracting the mean and dividing by the standard deviation. Lastly, we convert the array into a Torch tensor and convert the values to float.
These steps are the same steps we specified in Step 2, but this time we must manually code the commands instead of relying on the transforms library.
# Process our imagedef process_image(image_path): # Load Image img = Image.open(image_path) # Get the dimensions of the image width, height = img.size # Resize by keeping the aspect ratio, but changing the dimension # so the shortest size is 255px img = img.resize((255, int(255*(height/width))) if width < height else (int(255*(width/height)), 255)) # Get the dimensions of the new image size width, height = img.size # Set the coordinates to do a center crop of 224 x 224 left = (width - 224)/2 top = (height - 224)/2 right = (width + 224)/2 bottom = (height + 224)/2 img = img.crop((left, top, right, bottom)) # Turn image into numpy array img = np.array(img) # Make the color channel dimension first instead of last img = img.transpose((2, 0, 1)) # Make all values between 0 and 1 img = img/255 # Normalize based on the preset mean and standard deviation img[0] = (img[0] - 0.485)/0.229 img[1] = (img[1] - 0.456)/0.224 img[2] = (img[2] - 0.406)/0.225 # Add a fourth dimension to the beginning to indicate batch size img = img[np.newaxis,:] # Turn into a torch tensor image = torch.from_numpy(img) image = image.float() return image
After processing the image, we can build a function to use our model to predict the label. We input the image into our model and obtain the output. We then reverse the log in the LogSoftmax function that we applied in the output layer and return the top class the model predicted and how certain it is of its guess.
# Using our model to predict the labeldef predict(image, model): # Pass the image through our model output = model.forward(image) # Reverse the log function in our output output = torch.exp(output) # Get the top predicted class, and the output percentage for # that class probs, classes = output.topk(1, dim=1) return probs.item(), classes.item()
Lastly, we want to display the image. We turn the image back into an array, and un-normalize it by multiplying by the standard deviation and adding back the mean. We then use the matplotlib.pyplot library to plot the picture.
# Show Imagedef show_image(image): # Convert image to numpy image = image.numpy() # Un-normalize the image image[0] = image[0] * 0.226 + 0.445 # Print the image fig = plt.figure(figsize=(25, 4)) plt.imshow(np.transpose(image[0], (1, 2, 0)))
Now, we can use all these functions to print our model’s guess and how sure it was!
# Process Imageimage = process_image("root/image1234.jpg")# Give image to model to predict outputtop_prob, top_class = predict(image, model)# Show the imageshow_image(image)# Print the resultsprint("The model is ", top_prob*100, "% certain that the image has a predicted class of ", top_class )
|
[
{
"code": null,
"e": 308,
"s": 171,
"text": "This is a step-by-step guide to build an image classifier. The AI model will be able to learn to label images. I use Python and Pytorch."
},
{
"code": null,
"e": 627,
"s": 308,
"text": "When we write a program, it is a huge hassle manually coding every small action we perform. Sometimes, we want to use packages of code other people have already written. These packaged routines are called Libraries and can be added into our program by importing them and then referencing the library later in the code."
},
{
"code": null,
"e": 696,
"s": 627,
"text": "We usually import all the libraries at the beginning of the program."
},
{
"code": null,
"e": 818,
"s": 696,
"text": "Instead of typing the library’s long name whenever we reference it, we can shorten it to a name of our choice using “as”."
},
{
"code": null,
"e": 1102,
"s": 818,
"text": "# Import Librariesimport torchimport torchvision.transforms as transformsimport torchvision.datasets as datasetsimport torchvision.models as modelsimport torch.nn as nnimport torch.optim as optimimport numpy as npfrom PIL import Imageimport numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 1173,
"s": 1102,
"text": "Next, we want to import the picture data our AI model will learn from."
},
{
"code": null,
"e": 1331,
"s": 1173,
"text": "But before that, we need to specify the alterations we want to perform on these pictures — since the same command that imports them also transforms the data."
},
{
"code": null,
"e": 1529,
"s": 1331,
"text": "These transforms are made using the torchvision.transforms library. The best way to understand the transforms is to read the documentation here. But I’ll give a brief of what each command is doing."
},
{
"code": null,
"e": 1637,
"s": 1529,
"text": "transforms.Compose lets us compose multiple transforms together so we can use more than one transformation."
},
{
"code": null,
"e": 1798,
"s": 1637,
"text": "transforms.Resize((255)) resizes the images so the shortest side has a length of 255 pixels. The other side is scaled to maintain the aspect ratio of the image."
},
{
"code": null,
"e": 1898,
"s": 1798,
"text": "transforms.CenterCrop(224) crops the center of the image so it is a 224 by 224 pixels square image."
},
{
"code": null,
"e": 2032,
"s": 1898,
"text": "We do these two steps so all the images going into our AI model have the same size (AI models can’t handle inputs with varying sizes)"
},
{
"code": null,
"e": 2108,
"s": 2032,
"text": "transforms.ToTensor() converts our image into numbers. How does it do that?"
},
{
"code": null,
"e": 2296,
"s": 2108,
"text": "It separates the three colors that every pixel of our picture is comprised of: red, green & blue. This essentially turns one image into three images (one tinted red, one green, one blue)."
},
{
"code": null,
"e": 2547,
"s": 2296,
"text": "Then, it converts the pixels of each tinted image into the brightness of their color, from 0 to 255. These values are divided by 255, so they can be in a range of 0 to 1. Our image is now a Torch Tensor (a data structure that stores lots of numbers)."
},
{
"code": null,
"e": 2702,
"s": 2547,
"text": "transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) subtracts the mean from each value and then divides by the standard deviation."
},
{
"code": null,
"e": 2900,
"s": 2702,
"text": "We will be using a pre-trained model, so we need to use the means and standard deviations the Pytorch specifies. There are three values in the mean and standard deviation to match each RGB picture."
},
{
"code": null,
"e": 3176,
"s": 2900,
"text": "# Specify transforms using torchvision.transforms as transforms# librarytransformations = transforms.Compose([ transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])"
},
{
"code": null,
"e": 3271,
"s": 3176,
"text": "Finally, we can import our pictures into the program. We use the torchvision.datasets library."
},
{
"code": null,
"e": 3291,
"s": 3271,
"text": "Read about it here."
},
{
"code": null,
"e": 3469,
"s": 3291,
"text": "We specify two different data sets, one for the images that the AI learns from (the training set) and the other for the dataset we use to test the AI model (the validation set)."
},
{
"code": null,
"e": 3755,
"s": 3469,
"text": "The datasets.ImageFolder() command expects our data to be organized in the following way: root/label/picture.png. In other words, the images should be sorted into folders. For example, all the pictures of bees should be in one folder, all the pictures of ants should be in another etc."
},
{
"code": null,
"e": 3775,
"s": 3755,
"text": "We give the command"
},
{
"code": null,
"e": 3861,
"s": 3775,
"text": "the path to all the folders andthe transforms that we specified in the previous step."
},
{
"code": null,
"e": 3893,
"s": 3861,
"text": "the path to all the folders and"
},
{
"code": null,
"e": 3948,
"s": 3893,
"text": "the transforms that we specified in the previous step."
},
{
"code": null,
"e": 4209,
"s": 3948,
"text": "# Load in each dataset and apply transformations using# the torchvision.datasets as datasets librarytrain_set = datasets.ImageFolder(\"root/label/train\", transform = transformations)val_set = datasets.ImageFolder(\"root/label/valid\", transform = transformations)"
},
{
"code": null,
"e": 4268,
"s": 4209,
"text": "Then we want to put our imported images into a Dataloader."
},
{
"code": null,
"e": 4431,
"s": 4268,
"text": "Dataloader is able to spit out random samples of our data, so our model won’t have to deal with the entire dataset every time. This makes training more efficient."
},
{
"code": null,
"e": 4627,
"s": 4431,
"text": "We specify how many images we want at once as our batch_size (so 32 means we want to get 32 images at one time). We also want to shuffle our images so it gets inputted randomly into our AI model."
},
{
"code": null,
"e": 4659,
"s": 4627,
"text": "Read about the DataLoader here."
},
{
"code": null,
"e": 4864,
"s": 4659,
"text": "# Put into a Dataloader using torch librarytrain_loader = torch.utils.data.DataLoader(train_set, batch_size=32, shuffle=True)val_loader = torch.utils.data.DataLoader(val_set, batch_size =32, shuffle=True)"
},
{
"code": null,
"e": 5147,
"s": 4864,
"text": "AI models need to be trained on a lot of data to be effective. Since we don’t have that much data, we want to take a pre-trained model (a model that has been previously trained on many images) but tailor it to recognize our specific images. This process is called transfer learning."
},
{
"code": null,
"e": 5188,
"s": 5147,
"text": "Image recognition models have two parts:"
},
{
"code": null,
"e": 5234,
"s": 5188,
"text": "the convolutional part andthe classifier part"
},
{
"code": null,
"e": 5261,
"s": 5234,
"text": "the convolutional part and"
},
{
"code": null,
"e": 5281,
"s": 5261,
"text": "the classifier part"
},
{
"code": null,
"e": 5375,
"s": 5281,
"text": "We want to keep the pre-trained convolutional part but put in our own classifier. Here’s why:"
},
{
"code": null,
"e": 5587,
"s": 5375,
"text": "The convolution/pooling section of our model is used to recognize the features inside an image. It first identifies edges, then using the edges it identifies shapes, and using the shapes it can identify objects."
},
{
"code": null,
"e": 5869,
"s": 5587,
"text": "But it takes A LOT of data to train this section — probably more than we have — so instead, we can use the default, pre-trained convolutional layers. These pre-trained convolutional layers were trained to identify these feature very well, regardless of what kind of image you have."
},
{
"code": null,
"e": 6019,
"s": 5869,
"text": "There are also pooling layers in between convolutional layers that distill an image to a smaller size so it can be easily inputted to our classifier."
},
{
"code": null,
"e": 6349,
"s": 6019,
"text": "The last part of the model is the classifier. The classifier takes all the information extracted from the photo in the convolution part, and uses it to identify the image. This is the part of the pre-trained model we want to replace and to train on our own images. This makes the model tailored to identify the images we give it."
},
{
"code": null,
"e": 6613,
"s": 6349,
"text": "We use the torchvision.models library to download a pre-trained model. There are many different models we can download, and more info can be found here. I chose a model called densenet161 and specified that we want it to be pre-trained by setting pretrained=True."
},
{
"code": null,
"e": 6861,
"s": 6613,
"text": "Then, we want to make sure we don’t train this model since it is already trained, and we only want to train the classifier we will put in next. We tell the model not to calculate the gradients of any parameter since that is only done for training."
},
{
"code": null,
"e": 7073,
"s": 6861,
"text": "# Get pretrained model using torchvision.models as models librarymodel = models.densenet161(pretrained=True)# Turn off training for their parametersfor param in model.parameters(): param.requires_grad = False"
},
{
"code": null,
"e": 7265,
"s": 7073,
"text": "Now we want to replace the default classifier of the model with our own classifier. Classifiers are fully connected neural networks, so to do this, we must first build our own neural network."
},
{
"code": null,
"e": 7537,
"s": 7265,
"text": "A neural network is just a method to find complex patterns and connections between numbers of the input and the output. In this case, it takes the features of the image that were highlighted by the convolution section to determine how likely the image is a certain label."
},
{
"code": null,
"e": 7908,
"s": 7537,
"text": "The first thing we want to do is to determine the amount of numbers inputted to our neural network. This has to match the amount of numbers that is outputted from the section before (the convolutional section). Since we didn’t change the convolutional section at all, the amount of numbers inputted in our classifier should be the same as the model’s default classifier."
},
{
"code": null,
"e": 8324,
"s": 7908,
"text": "Next, we want to determine the number of outputs. This number should match how many types of images you have. The model will give you a list of percentages, each corresponding to how certain the picture is to that label. So if you have images of bees, ants, and flies, there are 3 labels. and there should be 3 numbers in the output layer each corresponding to the probability of the input being a bee, ant, or fly."
},
{
"code": null,
"e": 8437,
"s": 8324,
"text": "Once we have those details, we use the torch.nn library to create the classifier. Information can be found here."
},
{
"code": null,
"e": 8496,
"s": 8437,
"text": "nn.Sequential can help us group multiple modules together."
},
{
"code": null,
"e": 8623,
"s": 8496,
"text": "nn.Linear specifies the interaction between two layers. We give it 2 numbers, specifying the number of nodes in the two layer."
},
{
"code": null,
"e": 8779,
"s": 8623,
"text": "For example, in the first nn.Linear, the first layer is the input layer, and we can choose how many numbers we want in the second layer (I went with 1024)."
},
{
"code": null,
"e": 8980,
"s": 8779,
"text": "nn.ReLU is an activation function for hidden layers. Activation functions helps the model learn complex relationships between the input and the output. We use ReLU on all layers except for the output."
},
{
"code": null,
"e": 9080,
"s": 8980,
"text": "We repeat this for as many hidden layers as you want, with as many nodes as you want in each layer."
},
{
"code": null,
"e": 9369,
"s": 9080,
"text": "nn.LogSoftmax is the activation function for the output. The softmax function turns the outputted numbers into percentages for each label, and the log function is applied to make it computationally faster. We must specify that the output layer is a column, so we set dimension equal to 1."
},
{
"code": null,
"e": 9440,
"s": 9369,
"text": "After creating our own classifier, we replace the model’s default one."
},
{
"code": null,
"e": 9966,
"s": 9440,
"text": "# Create new classifier for model using torch.nn as nn libraryclassifier_input = model.classifier.in_featuresnum_labels = #PUT IN THE NUMBER OF LABELS IN YOUR DATAclassifier = nn.Sequential(nn.Linear(classifier_input, 1024), nn.ReLU(), nn.Linear(1024, 512), nn.ReLU(), nn.Linear(512, num_labels), nn.LogSoftmax(dim=1))# Replace default classifier with new classifiermodel.classifier = classifier"
},
{
"code": null,
"e": 10024,
"s": 9966,
"text": "Now the model is created! Next, we just need to train it."
},
{
"code": null,
"e": 10277,
"s": 10024,
"text": "Training a model on a GPU is a lot faster than a CPU. So to determine which device is available for you, we use Torch to check. If there is a compatible GPU, we set the variable to GPU, if not, it sticks with CPU. We then move our model to this device."
},
{
"code": null,
"e": 10459,
"s": 10277,
"text": "# Find the device available to use using torch librarydevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")# Move model to the device specified abovemodel.to(device)"
},
{
"code": null,
"e": 10680,
"s": 10459,
"text": "While training, we need to determine how “off” our model is. To evaluate the amount of error our model has, we use nn.NLLLoss. This function takes in the output of our model, for which we used the nn.LogSoftmax function."
},
{
"code": null,
"e": 10989,
"s": 10680,
"text": "To train our model, we take our error and see how we can adjust the weights we multiplied our numbers by to get the smallest error. The method of calculating how we adjust our weights and applying it to our weights is called Adam. We use the torch.optim library to use this method and give it our parameters."
},
{
"code": null,
"e": 11183,
"s": 10989,
"text": "# Set the error function using torch.nn as nn librarycriterion = nn.NLLLoss()# Set the optimizer function using torch.optim as optim libraryoptimizer = optim.Adam(model.classifier.parameters())"
},
{
"code": null,
"e": 11454,
"s": 11183,
"text": "Now we train. We want our model to go through the entire dataset multiple times, so we use a for loop. Every time it has gone over the entire set of images, it is called an epoch. In one epoch we want the model to go through both the training set and the validation set."
},
{
"code": null,
"e": 11543,
"s": 11454,
"text": "We first set the model to training mode and we use a for-loop to go through every image."
},
{
"code": null,
"e": 11693,
"s": 11543,
"text": "After moving the images and the labels to the appropriate device, we need to clear the adjustments of the weights by declaring optimizer.zero_grad()."
},
{
"code": null,
"e": 11823,
"s": 11693,
"text": "We can then compute the output of our model given our images and how “off” our model is given its output and the correct answers."
},
{
"code": null,
"e": 11996,
"s": 11823,
"text": "Then we can find the adjustments we need to make to decreases this error by calling loss.backward() and use our optimizer to adjust the weights by calling optimizer.step()."
},
{
"code": null,
"e": 12142,
"s": 11996,
"text": "As we train, we want to know how things are going, so we keep track of the total errors we calculated and print out the progress of the training."
},
{
"code": null,
"e": 12240,
"s": 12142,
"text": "We set our model to evaluation mode and use a for-loop to iterate over all the images in our set."
},
{
"code": null,
"e": 12374,
"s": 12240,
"text": "We repeat the steps we took for the training set to get the output of our model and how much our model is “off” from the real labels."
},
{
"code": null,
"e": 12779,
"s": 12374,
"text": "Our model used the LogSoftmax function in order to increase computation speed, but now we want the real percentages, not the log percentages. So we use torch.exp to reverse the log function. We then want to see which class the model guessed for our images. .topk gives us the top class that was guessed, and what percentage it guessed it at — we only care about the class so we can ignore the percentage."
},
{
"code": null,
"e": 13043,
"s": 12779,
"text": "To determine how many images it guessed right, we check which guessed classes are equal to the real classes. Then we can average over the entire batch to determine the accuracy of our model (how many images it guessed right divided by the total amount of images)."
},
{
"code": null,
"e": 13178,
"s": 13043,
"text": "After going through both the training and validation set, we want to print the errors for both and the accuracy of the validation set."
},
{
"code": null,
"e": 15569,
"s": 13178,
"text": "epochs = 10for epoch in range(epochs): train_loss = 0 val_loss = 0 accuracy = 0 # Training the model model.train() counter = 0 for inputs, labels in train_loader: # Move to device inputs, labels = inputs.to(device), labels.to(device) # Clear optimizers optimizer.zero_grad() # Forward pass output = model.forward(inputs) # Loss loss = criterion(output, labels) # Calculate gradients (backpropogation) loss.backward() # Adjust parameters based on gradients optimizer.step() # Add the loss to the training set's rnning loss train_loss += loss.item()*inputs.size(0) # Print the progress of our training counter += 1 print(counter, \"/\", len(train_loader)) # Evaluating the model model.eval() counter = 0 # Tell torch not to calculate gradients with torch.no_grad(): for inputs, labels in val_loader: # Move to device inputs, labels = inputs.to(device), labels.to(device) # Forward pass output = model.forward(inputs) # Calculate Loss valloss = criterion(output, labels) # Add loss to the validation set's running loss val_loss += valloss.item()*inputs.size(0) # Since our model outputs a LogSoftmax, find the real # percentages by reversing the log function output = torch.exp(output) # Get the top class of the output top_p, top_class = output.topk(1, dim=1) # See how many of the classes were correct? equals = top_class == labels.view(*top_class.shape) # Calculate the mean (get the accuracy for this batch) # and add it to the running accuracy for this epoch accuracy += torch.mean(equals.type(torch.FloatTensor)).item() # Print the progress of our evaluation counter += 1 print(counter, \"/\", len(val_loader)) # Get the average loss for the entire epoch train_loss = train_loss/len(train_loader.dataset) valid_loss = val_loss/len(val_loader.dataset) # Print out the information print('Accuracy: ', accuracy/len(val_loader)) print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(epoch, train_loss, valid_loss))"
},
{
"code": null,
"e": 15736,
"s": 15569,
"text": "That was great! You’ve just built an AI image classifier. But, now we want to actually use it — we want to give it a random image and see which label it thinks it is."
},
{
"code": null,
"e": 15781,
"s": 15736,
"text": "First, we set the model for evaluation mode."
},
{
"code": null,
"e": 15794,
"s": 15781,
"text": "model.eval()"
},
{
"code": null,
"e": 15885,
"s": 15794,
"text": "Then we create a function that can process the image so it can be inputted into our model."
},
{
"code": null,
"e": 16425,
"s": 15885,
"text": "We open the image, resize it by keeping the aspect ratio but making the shortest side only 255 px, and crop the center 224px by 224px. We then turn the picture into an array and make sure that the number of color channels is the first dimension instead of the last dimension by transposing the array. Next, we convert each value between 0 and 1 by dividing by 255. We then normalize the values by subtracting the mean and dividing by the standard deviation. Lastly, we convert the array into a Torch tensor and convert the values to float."
},
{
"code": null,
"e": 16575,
"s": 16425,
"text": "These steps are the same steps we specified in Step 2, but this time we must manually code the commands instead of relying on the transforms library."
},
{
"code": null,
"e": 17844,
"s": 16575,
"text": "# Process our imagedef process_image(image_path): # Load Image img = Image.open(image_path) # Get the dimensions of the image width, height = img.size # Resize by keeping the aspect ratio, but changing the dimension # so the shortest size is 255px img = img.resize((255, int(255*(height/width))) if width < height else (int(255*(width/height)), 255)) # Get the dimensions of the new image size width, height = img.size # Set the coordinates to do a center crop of 224 x 224 left = (width - 224)/2 top = (height - 224)/2 right = (width + 224)/2 bottom = (height + 224)/2 img = img.crop((left, top, right, bottom)) # Turn image into numpy array img = np.array(img) # Make the color channel dimension first instead of last img = img.transpose((2, 0, 1)) # Make all values between 0 and 1 img = img/255 # Normalize based on the preset mean and standard deviation img[0] = (img[0] - 0.485)/0.229 img[1] = (img[1] - 0.456)/0.224 img[2] = (img[2] - 0.406)/0.225 # Add a fourth dimension to the beginning to indicate batch size img = img[np.newaxis,:] # Turn into a torch tensor image = torch.from_numpy(img) image = image.float() return image"
},
{
"code": null,
"e": 18160,
"s": 17844,
"text": "After processing the image, we can build a function to use our model to predict the label. We input the image into our model and obtain the output. We then reverse the log in the LogSoftmax function that we applied in the output layer and return the top class the model predicted and how certain it is of its guess."
},
{
"code": null,
"e": 18539,
"s": 18160,
"text": "# Using our model to predict the labeldef predict(image, model): # Pass the image through our model output = model.forward(image) # Reverse the log function in our output output = torch.exp(output) # Get the top predicted class, and the output percentage for # that class probs, classes = output.topk(1, dim=1) return probs.item(), classes.item()"
},
{
"code": null,
"e": 18765,
"s": 18539,
"text": "Lastly, we want to display the image. We turn the image back into an array, and un-normalize it by multiplying by the standard deviation and adding back the mean. We then use the matplotlib.pyplot library to plot the picture."
},
{
"code": null,
"e": 19035,
"s": 18765,
"text": "# Show Imagedef show_image(image): # Convert image to numpy image = image.numpy() # Un-normalize the image image[0] = image[0] * 0.226 + 0.445 # Print the image fig = plt.figure(figsize=(25, 4)) plt.imshow(np.transpose(image[0], (1, 2, 0)))"
},
{
"code": null,
"e": 19119,
"s": 19035,
"text": "Now, we can use all these functions to print our model’s guess and how sure it was!"
}
] |
How to simulate trades in Python. We always see, so called traders claim... | by Atilla Yurtseven | Towards Data Science
|
We always see, so called traders claim that they have a strategy with more than 70% win rate and their risk to reward ratio is above 1:2 (risk 1%, win 2%). Do you think it’s possible? Let’s find out!
I have a 70% win-rate with 1:2 risk-to-reward ratio
ROFL! Are you sure you didn’t miss the math class in high school (maybe primary?!)? Just keep in mind that, in 2019, hedge funds returns are average 6%. Here is the link of the source.
Now let’s start talking Python.
We only need two libraries
import numpy as npimport matplotlib.pyplot as plt
Now we need to write a function to simulate trades. Not actual ones of course.
def simulate(account_size, total_trades, risk_per_trade, win_rate, risk_reward): account = account_size accounts = [account] profits = [] loss = [] wins = [] total_win = 0 max_con_l = 0 max_con_w = 0 con_l = 0 con_w = 0 pre = 0 rnd = list(np.round(np.random.uniform(1, 101, total_trades), 2)) for i in range(len(rnd)): r = rnd[i] win = r <= win_rate risk = -np.round(account * risk_per_trade / 100, 2) profit_per_trade = abs(risk) * risk_reward profit = profit_per_trade if win else risk profits.append(profit) account += profit accounts.append(account) if profit > 0: total_win += 1 wins.append(profit) con_l = 0 if pre == 1: con_w += 1 if con_w > max_con_w: max_con_w = con_w pre = 1 else: # 0 is also a loss (spread + commissions) loss.append(abs(profit)) con_w = 0 if pre == -1: con_l += 1 if con_l > max_con_l: max_con_l = con_l pre = -1 avg_win = np.mean(wins) avg_loss = np.mean(loss) max_win = np.max(wins) max_loss = np.max(loss) win_r = np.round(total_win / total_trades * 100, 2) rrr = np.round(avg_win / avg_loss, 2) profit_factor = np.round(np.sum(wins) / np.sum(loss), 2) net_profits = np.cumsum(profits) gain = np.round(accounts[-1] - account_size, 2) growth_rate = np.round((accounts[-1] - account_size) / account_size * 100, 2) print("--- Trading Results ---\n") print("Total trades : {}".format(total_trades)) print("Wins : {} / {}%".format(total_win, win_r)) print("Average Win : {}".format(np.round(avg_win, 2))) print("Average Loss : {}".format(np.round(avg_loss, 2))) print("Max Win : {}".format(np.round(max_win, 2))) print("Max Loss : {}".format(np.round(max_loss, 2))) print("Max Cons. Wins : {}".format(max_con_w)) print("Max Cons. Loss : {}".format(max_con_l)) print("Risk Reward Ratio : {}".format(rrr)) print("Profit Factor : {}".format(profit_factor)) print("Risk per trade : {}%".format(risk_per_trade)) print("---") print("Initial Account : {}".format(account_size)) print("Profit : {} / {}%".format(gain, growth_rate)) print("Final Account : {}".format(np.round(account, 2))) print() print("Results are compounded. Spread and commissions are not calculated.") fig, ax = plt.subplots(2, 1, figsize=(16, 10)) ax[0].plot(net_profits) ax[1].plot(accounts) ax[1].axhline(account_size, color="#000000", ls="-.", linewidth=0.5) ax[0].set_title("Equirty Curve") ax[1].set_title("Account Growth") plt.show()
Let’s define this guy’s claims
account_size = 10000total_trades = 200 #trades per year maybe?risk_per_trade = 2 #risk 2% of your account per tradewin_rate = 70 # in percentagerisk_reward = 2 # risk 1% profit 2%
OMG! This is going to be crazy. Let’s run if you are ready? :)
simulate(account_size, total_trades, risk_per_trade, win_rate, risk_reward)
And Oscar goes to this guy!!!!
He can make 8025% per year and still tries to sell you a product?! Come on!!!!
Ok; now let’s try to be more realistic. I am going to use the following params:
account_size = 10000total_trades = 200 #trades per year maybe?risk_per_trade = 2 #risk 2% of your account per tradewin_rate = 52risk_reward = 1.4
And the result
Even with 52% winrate with 1.4 risk to reward ratio makes 193% per year! However, this is not that easy.
Please just stop believing in all these so called traders out there. Most of social media traders are nothing but cons. They are only trying to sell you a dream and their so called holy-grail products. There’s no holy-grail and you don’t need a 70% win-rate.
Disclaimer
I’m not a professional financial advisor. This article and codes, shared for educational purposes only and not financial advice. You are responsible your own losses or wins.
The whole code of this article can be found on this repository:
github.com
Ah also; remember to follow me on the following social channels:
MediumTwitterYouTube!TradingView
Until next time; stay safe, trade safe!!!
Image from: https://hackernoon.com/algo-trading-for-dummies-implementing-an-actual-trading-strategy-part-4-acec5543052b
Atilla Yurtseven
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
|
[
{
"code": null,
"e": 372,
"s": 172,
"text": "We always see, so called traders claim that they have a strategy with more than 70% win rate and their risk to reward ratio is above 1:2 (risk 1%, win 2%). Do you think it’s possible? Let’s find out!"
},
{
"code": null,
"e": 424,
"s": 372,
"text": "I have a 70% win-rate with 1:2 risk-to-reward ratio"
},
{
"code": null,
"e": 609,
"s": 424,
"text": "ROFL! Are you sure you didn’t miss the math class in high school (maybe primary?!)? Just keep in mind that, in 2019, hedge funds returns are average 6%. Here is the link of the source."
},
{
"code": null,
"e": 641,
"s": 609,
"text": "Now let’s start talking Python."
},
{
"code": null,
"e": 668,
"s": 641,
"text": "We only need two libraries"
},
{
"code": null,
"e": 718,
"s": 668,
"text": "import numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 797,
"s": 718,
"text": "Now we need to write a function to simulate trades. Not actual ones of course."
},
{
"code": null,
"e": 3632,
"s": 797,
"text": "def simulate(account_size, total_trades, risk_per_trade, win_rate, risk_reward): account = account_size accounts = [account] profits = [] loss = [] wins = [] total_win = 0 max_con_l = 0 max_con_w = 0 con_l = 0 con_w = 0 pre = 0 rnd = list(np.round(np.random.uniform(1, 101, total_trades), 2)) for i in range(len(rnd)): r = rnd[i] win = r <= win_rate risk = -np.round(account * risk_per_trade / 100, 2) profit_per_trade = abs(risk) * risk_reward profit = profit_per_trade if win else risk profits.append(profit) account += profit accounts.append(account) if profit > 0: total_win += 1 wins.append(profit) con_l = 0 if pre == 1: con_w += 1 if con_w > max_con_w: max_con_w = con_w pre = 1 else: # 0 is also a loss (spread + commissions) loss.append(abs(profit)) con_w = 0 if pre == -1: con_l += 1 if con_l > max_con_l: max_con_l = con_l pre = -1 avg_win = np.mean(wins) avg_loss = np.mean(loss) max_win = np.max(wins) max_loss = np.max(loss) win_r = np.round(total_win / total_trades * 100, 2) rrr = np.round(avg_win / avg_loss, 2) profit_factor = np.round(np.sum(wins) / np.sum(loss), 2) net_profits = np.cumsum(profits) gain = np.round(accounts[-1] - account_size, 2) growth_rate = np.round((accounts[-1] - account_size) / account_size * 100, 2) print(\"--- Trading Results ---\\n\") print(\"Total trades : {}\".format(total_trades)) print(\"Wins : {} / {}%\".format(total_win, win_r)) print(\"Average Win : {}\".format(np.round(avg_win, 2))) print(\"Average Loss : {}\".format(np.round(avg_loss, 2))) print(\"Max Win : {}\".format(np.round(max_win, 2))) print(\"Max Loss : {}\".format(np.round(max_loss, 2))) print(\"Max Cons. Wins : {}\".format(max_con_w)) print(\"Max Cons. Loss : {}\".format(max_con_l)) print(\"Risk Reward Ratio : {}\".format(rrr)) print(\"Profit Factor : {}\".format(profit_factor)) print(\"Risk per trade : {}%\".format(risk_per_trade)) print(\"---\") print(\"Initial Account : {}\".format(account_size)) print(\"Profit : {} / {}%\".format(gain, growth_rate)) print(\"Final Account : {}\".format(np.round(account, 2))) print() print(\"Results are compounded. Spread and commissions are not calculated.\") fig, ax = plt.subplots(2, 1, figsize=(16, 10)) ax[0].plot(net_profits) ax[1].plot(accounts) ax[1].axhline(account_size, color=\"#000000\", ls=\"-.\", linewidth=0.5) ax[0].set_title(\"Equirty Curve\") ax[1].set_title(\"Account Growth\") plt.show()"
},
{
"code": null,
"e": 3663,
"s": 3632,
"text": "Let’s define this guy’s claims"
},
{
"code": null,
"e": 3843,
"s": 3663,
"text": "account_size = 10000total_trades = 200 #trades per year maybe?risk_per_trade = 2 #risk 2% of your account per tradewin_rate = 70 # in percentagerisk_reward = 2 # risk 1% profit 2%"
},
{
"code": null,
"e": 3906,
"s": 3843,
"text": "OMG! This is going to be crazy. Let’s run if you are ready? :)"
},
{
"code": null,
"e": 3982,
"s": 3906,
"text": "simulate(account_size, total_trades, risk_per_trade, win_rate, risk_reward)"
},
{
"code": null,
"e": 4013,
"s": 3982,
"text": "And Oscar goes to this guy!!!!"
},
{
"code": null,
"e": 4092,
"s": 4013,
"text": "He can make 8025% per year and still tries to sell you a product?! Come on!!!!"
},
{
"code": null,
"e": 4172,
"s": 4092,
"text": "Ok; now let’s try to be more realistic. I am going to use the following params:"
},
{
"code": null,
"e": 4318,
"s": 4172,
"text": "account_size = 10000total_trades = 200 #trades per year maybe?risk_per_trade = 2 #risk 2% of your account per tradewin_rate = 52risk_reward = 1.4"
},
{
"code": null,
"e": 4333,
"s": 4318,
"text": "And the result"
},
{
"code": null,
"e": 4438,
"s": 4333,
"text": "Even with 52% winrate with 1.4 risk to reward ratio makes 193% per year! However, this is not that easy."
},
{
"code": null,
"e": 4697,
"s": 4438,
"text": "Please just stop believing in all these so called traders out there. Most of social media traders are nothing but cons. They are only trying to sell you a dream and their so called holy-grail products. There’s no holy-grail and you don’t need a 70% win-rate."
},
{
"code": null,
"e": 4708,
"s": 4697,
"text": "Disclaimer"
},
{
"code": null,
"e": 4882,
"s": 4708,
"text": "I’m not a professional financial advisor. This article and codes, shared for educational purposes only and not financial advice. You are responsible your own losses or wins."
},
{
"code": null,
"e": 4946,
"s": 4882,
"text": "The whole code of this article can be found on this repository:"
},
{
"code": null,
"e": 4957,
"s": 4946,
"text": "github.com"
},
{
"code": null,
"e": 5022,
"s": 4957,
"text": "Ah also; remember to follow me on the following social channels:"
},
{
"code": null,
"e": 5055,
"s": 5022,
"text": "MediumTwitterYouTube!TradingView"
},
{
"code": null,
"e": 5097,
"s": 5055,
"text": "Until next time; stay safe, trade safe!!!"
},
{
"code": null,
"e": 5217,
"s": 5097,
"text": "Image from: https://hackernoon.com/algo-trading-for-dummies-implementing-an-actual-trading-strategy-part-4-acec5543052b"
},
{
"code": null,
"e": 5234,
"s": 5217,
"text": "Atilla Yurtseven"
}
] |
W3.CSS - Containers
|
HTML5 has the following container elements −
<div> − Provides a generic container to HTML content.
<div> − Provides a generic container to HTML content.
<header> − Represents the header section.
<header> − Represents the header section.
<footer> − Represents the footer section.
<footer> − Represents the footer section.
<article> − Represents articles.
<article> − Represents articles.
<section> − Provides a generic container for various types of sections.
<section> − Provides a generic container for various types of sections.
W3.CSS provides w3-container as a primary class to style all the above-mentioned containers. W3.CSS also has other classes like w3-border, w3-red, w3-teal, w3-padding-32 to add further styling attributes to the containers.
The following example showcases the use of w3-container class to style various containers.
<html>
<head>
<title>The W3.CSS Containers</title>
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
</head>
<body>
<header class = "w3-container w3-red">
<h1>HTML5 Tutorial</h1>
</header>
<div class = "w3-container w3-border w3-teal">
<p>HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a mark up language.</p>
</div>
<article class = "w3-container">
<p>The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.</p>
</article>
<section class = "w3-container">
<p>HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers.</p>
</section>
<footer class = "w3-container w3-red">
<p>Copyright @TutorialsPoint.COM</p>
</footer>
</body>
</html>
Verify the result.
HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a mark up language.
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.
HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers.
|
[
{
"code": null,
"e": 1954,
"s": 1909,
"text": "HTML5 has the following container elements −"
},
{
"code": null,
"e": 2008,
"s": 1954,
"text": "<div> − Provides a generic container to HTML content."
},
{
"code": null,
"e": 2062,
"s": 2008,
"text": "<div> − Provides a generic container to HTML content."
},
{
"code": null,
"e": 2104,
"s": 2062,
"text": "<header> − Represents the header section."
},
{
"code": null,
"e": 2146,
"s": 2104,
"text": "<header> − Represents the header section."
},
{
"code": null,
"e": 2188,
"s": 2146,
"text": "<footer> − Represents the footer section."
},
{
"code": null,
"e": 2230,
"s": 2188,
"text": "<footer> − Represents the footer section."
},
{
"code": null,
"e": 2263,
"s": 2230,
"text": "<article> − Represents articles."
},
{
"code": null,
"e": 2296,
"s": 2263,
"text": "<article> − Represents articles."
},
{
"code": null,
"e": 2368,
"s": 2296,
"text": "<section> − Provides a generic container for various types of sections."
},
{
"code": null,
"e": 2440,
"s": 2368,
"text": "<section> − Provides a generic container for various types of sections."
},
{
"code": null,
"e": 2663,
"s": 2440,
"text": "W3.CSS provides w3-container as a primary class to style all the above-mentioned containers. W3.CSS also has other classes like w3-border, w3-red, w3-teal, w3-padding-32 to add further styling attributes to the containers."
},
{
"code": null,
"e": 2754,
"s": 2663,
"text": "The following example showcases the use of w3-container class to style various containers."
},
{
"code": null,
"e": 4119,
"s": 2754,
"text": "<html>\n <head>\n <title>The W3.CSS Containers</title>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://www.w3schools.com/lib/w3.css\">\n </head>\n \n <body>\n <header class = \"w3-container w3-red\">\n <h1>HTML5 Tutorial</h1>\n </header>\n \n <div class = \"w3-container w3-border w3-teal\">\n <p>HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a mark up language.</p>\n </div>\n \n <article class = \"w3-container\">\n <p>The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.</p>\n </article>\n \n <section class = \"w3-container\">\n <p>HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers.</p>\n </section>\n \n <footer class = \"w3-container w3-red\">\n <p>Copyright @TutorialsPoint.COM</p>\n </footer>\n </body>\n</html>"
},
{
"code": null,
"e": 4138,
"s": 4119,
"text": "Verify the result."
},
{
"code": null,
"e": 4273,
"s": 4138,
"text": "HTML5 is the latest and most enhanced version of HTML. Technically, HTML is not a programming language, but rather a mark up language."
},
{
"code": null,
"e": 4587,
"s": 4273,
"text": "The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5."
}
] |
SQL - AVG Function
|
SQL AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having the following records −
SQL> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
| id | name | work_date | daily_typing_pages |
+------+------+------------+--------------------+
| 1 | John | 2007-01-24 | 250 |
| 2 | Ram | 2007-05-27 | 220 |
| 3 | Jack | 2007-05-06 | 170 |
| 3 | Jack | 2007-04-06 | 100 |
| 4 | Jill | 2007-04-06 | 220 |
| 5 | Zara | 2007-06-06 | 300 |
| 5 | Zara | 2007-02-06 | 350 |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −
SQL> SELECT AVG(daily_typing_pages)
-> FROM employee_tbl;
+-------------------------+
| AVG(daily_typing_pages) |
+-------------------------+
| 230.0000 |
+-------------------------+
1 row in set (0.03 sec)
You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.
SQL> SELECT name, AVG(daily_typing_pages)
-> FROM employee_tbl GROUP BY name;
+------+-------------------------+
| name | AVG(daily_typing_pages) |
+------+-------------------------+
| Jack | 135.0000 |
| Jill | 220.0000 |
| John | 250.0000 |
| Ram | 220.0000 |
| Zara | 325.0000 |
+------+-------------------------+
5 rows in set (0.20 sec)
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2533,
"s": 2453,
"text": "SQL AVG function is used to find out the average of a field in various records."
},
{
"code": null,
"e": 2633,
"s": 2533,
"text": "To understand AVG function, consider an employee_tbl table, which is having the following records −"
},
{
"code": null,
"e": 3241,
"s": 2633,
"text": "SQL> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3391,
"s": 3241,
"text": "Now suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −"
},
{
"code": null,
"e": 3617,
"s": 3391,
"text": "SQL> SELECT AVG(daily_typing_pages)\n -> FROM employee_tbl;\n+-------------------------+\n| AVG(daily_typing_pages) |\n+-------------------------+\n| 230.0000 |\n+-------------------------+\n1 row in set (0.03 sec)"
},
{
"code": null,
"e": 3818,
"s": 3617,
"text": "You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person."
},
{
"code": null,
"e": 4239,
"s": 3818,
"text": "SQL> SELECT name, AVG(daily_typing_pages)\n -> FROM employee_tbl GROUP BY name;\n+------+-------------------------+\n| name | AVG(daily_typing_pages) |\n+------+-------------------------+\n| Jack | 135.0000 |\n| Jill | 220.0000 |\n| John | 250.0000 |\n| Ram | 220.0000 |\n| Zara | 325.0000 |\n+------+-------------------------+\n5 rows in set (0.20 sec)"
},
{
"code": null,
"e": 4272,
"s": 4239,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4286,
"s": 4272,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4319,
"s": 4286,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4333,
"s": 4319,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4368,
"s": 4333,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4382,
"s": 4368,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4415,
"s": 4382,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4437,
"s": 4415,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 4472,
"s": 4437,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 4526,
"s": 4472,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 4559,
"s": 4526,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4587,
"s": 4559,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4594,
"s": 4587,
"text": " Print"
},
{
"code": null,
"e": 4605,
"s": 4594,
"text": " Add Notes"
}
] |
java.util.regex.Pattern.compile() Method
|
The java.util.regex.Pattern.compile(String regex, int flags) method compiles the given regular expression into a pattern.
Following is the declaration for java.util.regex.Pattern.compile(String regex, int flags) method.
public static Pattern compile(String regex, int flags)
regex − The expression to be compiled.
regex − The expression to be compiled.
flags − Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS.
flags − Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS.
IllegalArgumentException − If bit values other than those corresponding to the defined match flags are set in flags.
IllegalArgumentException − If bit values other than those corresponding to the defined match flags are set in flags.
PatternSyntaxException − If the expression's syntax is invalid.
PatternSyntaxException − If the expression's syntax is invalid.
The following example shows the usage of java.util.regex.Pattern.compile(String regex, int flags) method.
package com.tutorialspoint;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternDemo {
private static final String REGEX = "(.*)(\\d+)(.*)?# 3 capturing groups";
private static final String INPUT = "This is a sample Text, 1234, with numbers in between.";
public static void main(String[] args) {
// create a pattern
Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);
// get a matcher object
Matcher matcher = pattern.matcher(INPUT);
if(matcher.find()) {
//get the MatchResult Object
MatchResult result = matcher.toMatchResult();
//Prints the offset after the last character matched.
System.out.println("First Capturing Group - Match String end(): "+result.end());
}
}
}
Let us compile and run the above program, this will produce the following result −
First Capturing Group - Match String end(): 53
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2246,
"s": 2124,
"text": "The java.util.regex.Pattern.compile(String regex, int flags) method compiles the given regular expression into a pattern."
},
{
"code": null,
"e": 2344,
"s": 2246,
"text": "Following is the declaration for java.util.regex.Pattern.compile(String regex, int flags) method."
},
{
"code": null,
"e": 2400,
"s": 2344,
"text": "public static Pattern compile(String regex, int flags)\n"
},
{
"code": null,
"e": 2439,
"s": 2400,
"text": "regex − The expression to be compiled."
},
{
"code": null,
"e": 2478,
"s": 2439,
"text": "regex − The expression to be compiled."
},
{
"code": null,
"e": 2647,
"s": 2478,
"text": "flags − Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS."
},
{
"code": null,
"e": 2816,
"s": 2647,
"text": "flags − Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS."
},
{
"code": null,
"e": 2933,
"s": 2816,
"text": "IllegalArgumentException − If bit values other than those corresponding to the defined match flags are set in flags."
},
{
"code": null,
"e": 3050,
"s": 2933,
"text": "IllegalArgumentException − If bit values other than those corresponding to the defined match flags are set in flags."
},
{
"code": null,
"e": 3114,
"s": 3050,
"text": "PatternSyntaxException − If the expression's syntax is invalid."
},
{
"code": null,
"e": 3178,
"s": 3114,
"text": "PatternSyntaxException − If the expression's syntax is invalid."
},
{
"code": null,
"e": 3284,
"s": 3178,
"text": "The following example shows the usage of java.util.regex.Pattern.compile(String regex, int flags) method."
},
{
"code": null,
"e": 4137,
"s": 3284,
"text": "package com.tutorialspoint;\n\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class PatternDemo {\n private static final String REGEX = \"(.*)(\\\\d+)(.*)?# 3 capturing groups\";\n private static final String INPUT = \"This is a sample Text, 1234, with numbers in between.\";\n\n public static void main(String[] args) {\n // create a pattern\n Pattern pattern = Pattern.compile(REGEX,Pattern.COMMENTS);\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n\n if(matcher.find()) {\n //get the MatchResult Object \n MatchResult result = matcher.toMatchResult();\n\n //Prints the offset after the last character matched.\n System.out.println(\"First Capturing Group - Match String end(): \"+result.end()); \n }\n }\n}"
},
{
"code": null,
"e": 4220,
"s": 4137,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 4268,
"s": 4220,
"text": "First Capturing Group - Match String end(): 53\n"
},
{
"code": null,
"e": 4275,
"s": 4268,
"text": " Print"
},
{
"code": null,
"e": 4286,
"s": 4275,
"text": " Add Notes"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.