title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Inner reducing pattern printing - GeeksforGeeks | 27 Dec, 2018
Given a number N, print the following pattern.
Examples :
Input : 4
Output : 4444444
4333334
4322234
4321234
4322234
4333334
4444444
Explanation:
(1) Given value of n forms the outer-most
rectangular box layer.
(2) Value of n reduces by 1 and forms an
inner rectangular box layer.
(3) The step (2) is repeated until n
reduces to 1.
Input : 3
Output : 33333
32223
32123
32223
33333
C++
Java
Python3
C#
PHP
// C++ Program to print rectangular// inner reducing pattern#include <bits/stdc++.h>using namespace std; #define max 100 // function to Print patternvoid print(int a[][max], int size) {for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << a[i][j]; } cout << endl;}} // function to compute patternvoid innerPattern(int n) { // Pattern Sizeint size = 2 * n - 1;int front = 0;int back = size - 1;int a[max][max];while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i][j] = n; } } ++front; --back; --n;}print(a, size);} // Driver codeint main(){ // Input int n = 4; // function calling innerPattern(n); return 0;} // This code is contributed by Anant Agarwal.
// Java Program to print rectangular// inner reducing patternpublic class Pattern { // function to compute pattern public static void innerPattern(int n) { // Pattern Size int size = 2 * n - 1; int front = 0; int back = size - 1; int a[][] = new int[size][size]; while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i][j] = n; } } ++front; --back; --n; } print(a, size); } // function to Print pattern public static void print(int a[][], int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(a[i][j]); } System.out.println(); } } // Main Method public static void main(String[] args) { int n = 4; // Input innerPattern(n); }}
# Python3 Program to print rectangular # inner reducing pattern MAX = 100 # function to Print pattern def prints(a, size): for i in range(size): for j in range(size): print(a[i][j], end = '') print() # function to compute pattern def innerPattern(n): # Pattern Size size = 2 * n - 1 front = 0 back = size - 1 a = [[0 for i in range(MAX)] for i in range(MAX)] while (n != 0): for i in range(front, back + 1): for j in range(front, back + 1): if (i == front or i == back or j == front or j == back): a[i][j] = n front += 1 back -= 1 n -= 1 prints(a, size); # Driver code # Input n = 4 # function calling innerPattern(n) # This code is contributed # by sahishelangia
// C# Program to print rectangular// inner reducing patternusing System;public class Pattern { // function to compute pattern public static void innerPattern(int n) { // Pattern Size int size = 2 * n - 1; int front = 0; int back = size - 1; int [ ,]a = new int[size,size]; while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i,j] = n; } } ++front; --back; --n; } print(a, size); } // function to Print pattern public static void print(int [ ,]a , int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Console.Write(a[i,j]); } Console.WriteLine(); } } // Main Method public static void Main() { int n = 4; // Input innerPattern(n); }}/*This code is contributed by vt_m.*/
<?php// PHP implementation to print // rectangular inner reducing pattern $max=100; // function to Print patternfunction print1($a, $size) {for ($i = 0; $i < $size; $i++) { for ($j = 0; $j < $size; $j++) { echo $a[$i][$j]; } echo "\n"; }} // function to compute patternfunction innerPattern($n) { // Pattern Size $size = 2 * $n - 1; $front = 0; $back = $size - 1; $a; while ($n != 0) { for ($i = $front; $i <= $back; $i++) { for ($j = $front; $j <= $back; $j++) { if ($i == $front || $i == $back || $j == $front || $j == $back) $a[$i][$j] = $n; } } ++$front; --$back; --$n; } print1($a, $size);} // Driver code$n = 4; innerPattern($n); // This code is contributed by mits ?>
4444444
4333334
4322234
4321234
4322234
4333334
4444444
This article is contributed by Vigneshwaran Kannan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
sahilshelangia
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Data Types
Inline Functions in C++
Pure Virtual Functions and Abstract Classes in C++
Difference between Abstract Class and Interface in Java
Destructors in C++
Python Exception Handling
Exception Handling in C++
Input and Output | [
{
"code": null,
"e": 25465,
"s": 25437,
"text": "\n27 Dec, 2018"
},
{
"code": null,
"e": 25512,
"s": 25465,
"text": "Given a number N, print the following pattern."
},
{
"code": null,
"e": 25523,
"s": 25512,
"text": "Examples :"
},
{
"code": null,
"e": 25941,
"s": 25523,
"text": "Input : 4\nOutput : 4444444\n 4333334\n 4322234\n 4321234\n 4322234\n 4333334\n 4444444\nExplanation:\n(1) Given value of n forms the outer-most\n rectangular box layer.\n(2) Value of n reduces by 1 and forms an \ninner rectangular box layer.\n(3) The step (2) is repeated until n \nreduces to 1.\n\nInput : 3\nOutput : 33333\n 32223\n 32123\n 32223\n 33333\n"
},
{
"code": null,
"e": 25945,
"s": 25941,
"text": "C++"
},
{
"code": null,
"e": 25950,
"s": 25945,
"text": "Java"
},
{
"code": null,
"e": 25958,
"s": 25950,
"text": "Python3"
},
{
"code": null,
"e": 25961,
"s": 25958,
"text": "C#"
},
{
"code": null,
"e": 25965,
"s": 25961,
"text": "PHP"
},
{
"code": "// C++ Program to print rectangular// inner reducing pattern#include <bits/stdc++.h>using namespace std; #define max 100 // function to Print patternvoid print(int a[][max], int size) {for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << a[i][j]; } cout << endl;}} // function to compute patternvoid innerPattern(int n) { // Pattern Sizeint size = 2 * n - 1;int front = 0;int back = size - 1;int a[max][max];while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i][j] = n; } } ++front; --back; --n;}print(a, size);} // Driver codeint main(){ // Input int n = 4; // function calling innerPattern(n); return 0;} // This code is contributed by Anant Agarwal.",
"e": 26831,
"s": 25965,
"text": null
},
{
"code": "// Java Program to print rectangular// inner reducing patternpublic class Pattern { // function to compute pattern public static void innerPattern(int n) { // Pattern Size int size = 2 * n - 1; int front = 0; int back = size - 1; int a[][] = new int[size][size]; while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i][j] = n; } } ++front; --back; --n; } print(a, size); } // function to Print pattern public static void print(int a[][], int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.print(a[i][j]); } System.out.println(); } } // Main Method public static void main(String[] args) { int n = 4; // Input innerPattern(n); }}",
"e": 27968,
"s": 26831,
"text": null
},
{
"code": "# Python3 Program to print rectangular # inner reducing pattern MAX = 100 # function to Print pattern def prints(a, size): for i in range(size): for j in range(size): print(a[i][j], end = '') print() # function to compute pattern def innerPattern(n): # Pattern Size size = 2 * n - 1 front = 0 back = size - 1 a = [[0 for i in range(MAX)] for i in range(MAX)] while (n != 0): for i in range(front, back + 1): for j in range(front, back + 1): if (i == front or i == back or j == front or j == back): a[i][j] = n front += 1 back -= 1 n -= 1 prints(a, size); # Driver code # Input n = 4 # function calling innerPattern(n) # This code is contributed # by sahishelangia",
"e": 28805,
"s": 27968,
"text": null
},
{
"code": "// C# Program to print rectangular// inner reducing patternusing System;public class Pattern { // function to compute pattern public static void innerPattern(int n) { // Pattern Size int size = 2 * n - 1; int front = 0; int back = size - 1; int [ ,]a = new int[size,size]; while (n != 0) { for (int i = front; i <= back; i++) { for (int j = front; j <= back; j++) { if (i == front || i == back || j == front || j == back) a[i,j] = n; } } ++front; --back; --n; } print(a, size); } // function to Print pattern public static void print(int [ ,]a , int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { Console.Write(a[i,j]); } Console.WriteLine(); } } // Main Method public static void Main() { int n = 4; // Input innerPattern(n); }}/*This code is contributed by vt_m.*/",
"e": 29968,
"s": 28805,
"text": null
},
{
"code": "<?php// PHP implementation to print // rectangular inner reducing pattern $max=100; // function to Print patternfunction print1($a, $size) {for ($i = 0; $i < $size; $i++) { for ($j = 0; $j < $size; $j++) { echo $a[$i][$j]; } echo \"\\n\"; }} // function to compute patternfunction innerPattern($n) { // Pattern Size $size = 2 * $n - 1; $front = 0; $back = $size - 1; $a; while ($n != 0) { for ($i = $front; $i <= $back; $i++) { for ($j = $front; $j <= $back; $j++) { if ($i == $front || $i == $back || $j == $front || $j == $back) $a[$i][$j] = $n; } } ++$front; --$back; --$n; } print1($a, $size);} // Driver code$n = 4; innerPattern($n); // This code is contributed by mits ?>",
"e": 30967,
"s": 29968,
"text": null
},
{
"code": null,
"e": 31024,
"s": 30967,
"text": "4444444\n4333334\n4322234\n4321234\n4322234\n4333334\n4444444\n"
},
{
"code": null,
"e": 31331,
"s": 31024,
"text": "This article is contributed by Vigneshwaran Kannan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 31456,
"s": 31331,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31469,
"s": 31456,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31484,
"s": 31469,
"text": "sahilshelangia"
},
{
"code": null,
"e": 31501,
"s": 31484,
"text": "pattern-printing"
},
{
"code": null,
"e": 31520,
"s": 31501,
"text": "School Programming"
},
{
"code": null,
"e": 31537,
"s": 31520,
"text": "pattern-printing"
},
{
"code": null,
"e": 31635,
"s": 31537,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31656,
"s": 31635,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31675,
"s": 31656,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31686,
"s": 31675,
"text": "Data Types"
},
{
"code": null,
"e": 31710,
"s": 31686,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 31761,
"s": 31710,
"text": "Pure Virtual Functions and Abstract Classes in C++"
},
{
"code": null,
"e": 31817,
"s": 31761,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 31836,
"s": 31817,
"text": "Destructors in C++"
},
{
"code": null,
"e": 31862,
"s": 31836,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 31888,
"s": 31862,
"text": "Exception Handling in C++"
}
]
|
EnumSet in Java - GeeksforGeeks | 17 Jan, 2022
Enumerations or popularly known as enum serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. A few important features of EnumSet are as follows:
It extends AbstractSet class and implements Set Interface in Java.
EnumSet class is a member of the Java Collections Framework & is not synchronized.
It’s a high-performance set implementation, much faster than HashSet.
All of the elements in an EnumSet must come from a single enumeration type that is specified when the set is created either explicitly or implicitly.
It does not allow null Objects and throws NullPointerException if we do so.
It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating.
The Hierarchy of EnumSet is as follows:
java.lang.Object
↳ java.util.AbstractCollection<E>
↳ java.util.AbstractSet<E>
↳ java.util.EnumSet<E>
Here, E is the type of elements stored.
Syntax: Declaration
public abstract class EnumSet<E extends Enum<E>>
Here, E specifies the elements. E must extend Enum, which enforces the requirement that the elements must be of the specified enum type.
Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in an EnumSet are implemented using bitwise arithmetic operations.
EnumSet is faster than HashSet because we no need to compute any hashCode to find the right bucket.
The computations are executed in constant time and the space required is very little.
Method
Action Performed
Implementation:
Java
// Java Program to Illustrate Working// of EnumSet and its functions // Importing required classesimport java.util.EnumSet; // Enumenum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }; // Main class// EnumSetExamplepublic class GFG { // Main driver method public static void main(String[] args) { // Creating a set EnumSet<Gfg> set1, set2, set3, set4; // Adding elements set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE, Gfg.LEARN, Gfg.CODE); set2 = EnumSet.complementOf(set1); set3 = EnumSet.allOf(Gfg.class); set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE); // Printing corresponding elements in Sets System.out.println("Set 1: " + set1); System.out.println("Set 2: " + set2); System.out.println("Set 3: " + set3); System.out.println("Set 4: " + set4); }}
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]
Operation 1: Creating an EnumSet Object
Since EnumSet is an abstract class, we cannot directly create an instance of it. It has many static factory methods that allow us to create an instance. There are two different implementations of EnumSet provided by JDK
RegularEnumSet
JumboEnumSet
Note: These are package-private and backed by a bit vector.
RegularEnumSet uses a single long object to store elements of the EnumSet. Each bit of the long element represents an Enum value. Since the size of the long is 64 bits, it can store up to 64 different elements.
JumboEnumSet uses an array of long elements to store elements of the EnumSet. The only difference from RegularEnumSet is JumboEnumSet uses a long array to store the bit vector thereby allowing more than 64 values.
The factory methods create an instance based on the number of elements, EnumSet does not provide any public constructors, instances are created using static factory methods as listed below as follows:
allOf(size)
noneOf(size)
range(e1, e2)
of()
Illustration:
if (universe.length <= 64)
return new RegularEnumSet<>(elementType, universe);
else
return new JumboEnumSet<>(elementType, universe);
Example:
Java
// Java Program to illustrate Creation an EnumSet // Importing required classesimport java.util.*; // Main class// CreateEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating an EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Printing EnumSet elements to the console System.out.println("EnumSet: " + games); }}
EnumSet: [CRICKET, HOCKEY, TENNIS]
Operation 2: Adding Elements
We can add elements to an EnumSet using add() and addAll() methods.
Example:
Java
// Java program to illustrate Addition of Elements// to an EnumSet // Importing required classesimport java.util.EnumSet; // Main classclass AddElementsToEnumSet { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating an EnumSet // using allOf() EnumSet<Game> games1 = EnumSet.allOf(Game.class); // Creating an EnumSet // using noneOf() EnumSet<Game> games2 = EnumSet.noneOf(Game.class); // Using add() method games2.add(Game.HOCKEY); // Printing the elements to the console System.out.println("EnumSet Using add(): " + games2); // Using addAll() method games2.addAll(games1); // Printing the elements to the console System.out.println("EnumSet Using addAll(): " + games2); }}
EnumSet Using add(): [HOCKEY]
EnumSet Using addAll(): [CRICKET, HOCKEY, TENNIS]
Operation 3: Accessing Elements
We can access the EnumSet elements by using the iterator() method.
Example:
Java
// Java program to Access Elements of EnumSet // Importing required classesimport java.util.EnumSet;import java.util.Iterator; // Main class// AccessingElementsOfEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // MAin driver method public static void main(String[] args) { // Creating an EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Creating an iterator on games Iterator<Game> iterate = games.iterator(); // Display message System.out.print("EnumSet: "); while (iterate.hasNext()) { // Iterating and printing elements to // the console using next() method System.out.print(iterate.next()); System.out.print(", "); } }}
EnumSet: CRICKET, HOCKEY, TENNIS,
Operation 4: Removing elements
We can remove the elements using remove() and removeAll() methods.
Example:
Java
// Java program to Remove Elements// from a EnumSet // Importing required classesimport java.util.EnumSet; // Main class// RemovingElementsOfEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Printing the EnumSet System.out.println("EnumSet: " + games); // Using remove() boolean value1 = games.remove(Game.CRICKET); // Printing elements to the console System.out.println("Is CRICKET removed? " + value1); // Using removeAll() and storing the boolean result boolean value2 = games.removeAll(games); // Printing elements to the console System.out.println("Are all elements removed? " + value2); }}
EnumSet: [CRICKET, HOCKEY, TENNIS]
Is CRICKET removed? true
Are all elements removed? true
Some other methods of classes or interfaces are defined below that somehow helps us to get a better understanding of AbstractSet Class as follows:
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on GeeksforGeek’s 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.
Chinmoy Lenka
vogtlcc
Ganeshchowdharysadanala
solankimayank
simranarora5sos
Java-Collections
java-EnumSet
Java-Library
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
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 | [
{
"code": null,
"e": 23830,
"s": 23802,
"text": "\n17 Jan, 2022"
},
{
"code": null,
"e": 24114,
"s": 23830,
"text": "Enumerations or popularly known as enum serve the purpose of representing a group of named constants in a programming language. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit."
},
{
"code": null,
"e": 24276,
"s": 24114,
"text": "The EnumSet is one of the specialized implementations of the Set interface for use with the enumeration type. A few important features of EnumSet are as follows:"
},
{
"code": null,
"e": 24343,
"s": 24276,
"text": "It extends AbstractSet class and implements Set Interface in Java."
},
{
"code": null,
"e": 24426,
"s": 24343,
"text": "EnumSet class is a member of the Java Collections Framework & is not synchronized."
},
{
"code": null,
"e": 24496,
"s": 24426,
"text": "It’s a high-performance set implementation, much faster than HashSet."
},
{
"code": null,
"e": 24646,
"s": 24496,
"text": "All of the elements in an EnumSet must come from a single enumeration type that is specified when the set is created either explicitly or implicitly."
},
{
"code": null,
"e": 24722,
"s": 24646,
"text": "It does not allow null Objects and throws NullPointerException if we do so."
},
{
"code": null,
"e": 24849,
"s": 24722,
"text": "It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating."
},
{
"code": null,
"e": 24889,
"s": 24849,
"text": "The Hierarchy of EnumSet is as follows:"
},
{
"code": null,
"e": 25014,
"s": 24889,
"text": "java.lang.Object\n ↳ java.util.AbstractCollection<E>\n ↳ java.util.AbstractSet<E>\n ↳ java.util.EnumSet<E>"
},
{
"code": null,
"e": 25054,
"s": 25014,
"text": "Here, E is the type of elements stored."
},
{
"code": null,
"e": 25075,
"s": 25054,
"text": "Syntax: Declaration "
},
{
"code": null,
"e": 25125,
"s": 25075,
"text": "public abstract class EnumSet<E extends Enum<E>> "
},
{
"code": null,
"e": 25262,
"s": 25125,
"text": "Here, E specifies the elements. E must extend Enum, which enforces the requirement that the elements must be of the specified enum type."
},
{
"code": null,
"e": 25410,
"s": 25262,
"text": "Due to its implementation using RegularEnumSet and JumboEnumSet, all the methods in an EnumSet are implemented using bitwise arithmetic operations."
},
{
"code": null,
"e": 25510,
"s": 25410,
"text": "EnumSet is faster than HashSet because we no need to compute any hashCode to find the right bucket."
},
{
"code": null,
"e": 25596,
"s": 25510,
"text": "The computations are executed in constant time and the space required is very little."
},
{
"code": null,
"e": 25603,
"s": 25596,
"text": "Method"
},
{
"code": null,
"e": 25621,
"s": 25603,
"text": "Action Performed "
},
{
"code": null,
"e": 25637,
"s": 25621,
"text": "Implementation:"
},
{
"code": null,
"e": 25642,
"s": 25637,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Working// of EnumSet and its functions // Importing required classesimport java.util.EnumSet; // Enumenum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ }; // Main class// EnumSetExamplepublic class GFG { // Main driver method public static void main(String[] args) { // Creating a set EnumSet<Gfg> set1, set2, set3, set4; // Adding elements set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE, Gfg.LEARN, Gfg.CODE); set2 = EnumSet.complementOf(set1); set3 = EnumSet.allOf(Gfg.class); set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE); // Printing corresponding elements in Sets System.out.println(\"Set 1: \" + set1); System.out.println(\"Set 2: \" + set2); System.out.println(\"Set 3: \" + set3); System.out.println(\"Set 4: \" + set4); }}",
"e": 26510,
"s": 25642,
"text": null
},
{
"code": null,
"e": 26639,
"s": 26510,
"text": "Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]\nSet 2: [MCQ]\nSet 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]\nSet 4: [CODE, LEARN, CONTRIBUTE]"
},
{
"code": null,
"e": 26679,
"s": 26639,
"text": "Operation 1: Creating an EnumSet Object"
},
{
"code": null,
"e": 26900,
"s": 26679,
"text": "Since EnumSet is an abstract class, we cannot directly create an instance of it. It has many static factory methods that allow us to create an instance. There are two different implementations of EnumSet provided by JDK "
},
{
"code": null,
"e": 26915,
"s": 26900,
"text": "RegularEnumSet"
},
{
"code": null,
"e": 26930,
"s": 26915,
"text": "JumboEnumSet "
},
{
"code": null,
"e": 26990,
"s": 26930,
"text": "Note: These are package-private and backed by a bit vector."
},
{
"code": null,
"e": 27201,
"s": 26990,
"text": "RegularEnumSet uses a single long object to store elements of the EnumSet. Each bit of the long element represents an Enum value. Since the size of the long is 64 bits, it can store up to 64 different elements."
},
{
"code": null,
"e": 27415,
"s": 27201,
"text": "JumboEnumSet uses an array of long elements to store elements of the EnumSet. The only difference from RegularEnumSet is JumboEnumSet uses a long array to store the bit vector thereby allowing more than 64 values."
},
{
"code": null,
"e": 27616,
"s": 27415,
"text": "The factory methods create an instance based on the number of elements, EnumSet does not provide any public constructors, instances are created using static factory methods as listed below as follows:"
},
{
"code": null,
"e": 27628,
"s": 27616,
"text": "allOf(size)"
},
{
"code": null,
"e": 27641,
"s": 27628,
"text": "noneOf(size)"
},
{
"code": null,
"e": 27655,
"s": 27641,
"text": "range(e1, e2)"
},
{
"code": null,
"e": 27672,
"s": 27655,
"text": "of() "
},
{
"code": null,
"e": 27686,
"s": 27672,
"text": "Illustration:"
},
{
"code": null,
"e": 27828,
"s": 27686,
"text": "if (universe.length <= 64)\n return new RegularEnumSet<>(elementType, universe);\nelse\n return new JumboEnumSet<>(elementType, universe);"
},
{
"code": null,
"e": 27837,
"s": 27828,
"text": "Example:"
},
{
"code": null,
"e": 27842,
"s": 27837,
"text": "Java"
},
{
"code": "// Java Program to illustrate Creation an EnumSet // Importing required classesimport java.util.*; // Main class// CreateEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating an EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Printing EnumSet elements to the console System.out.println(\"EnumSet: \" + games); }}",
"e": 28315,
"s": 27842,
"text": null
},
{
"code": null,
"e": 28350,
"s": 28315,
"text": "EnumSet: [CRICKET, HOCKEY, TENNIS]"
},
{
"code": null,
"e": 28379,
"s": 28350,
"text": "Operation 2: Adding Elements"
},
{
"code": null,
"e": 28448,
"s": 28379,
"text": "We can add elements to an EnumSet using add() and addAll() methods. "
},
{
"code": null,
"e": 28457,
"s": 28448,
"text": "Example:"
},
{
"code": null,
"e": 28462,
"s": 28457,
"text": "Java"
},
{
"code": "// Java program to illustrate Addition of Elements// to an EnumSet // Importing required classesimport java.util.EnumSet; // Main classclass AddElementsToEnumSet { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating an EnumSet // using allOf() EnumSet<Game> games1 = EnumSet.allOf(Game.class); // Creating an EnumSet // using noneOf() EnumSet<Game> games2 = EnumSet.noneOf(Game.class); // Using add() method games2.add(Game.HOCKEY); // Printing the elements to the console System.out.println(\"EnumSet Using add(): \" + games2); // Using addAll() method games2.addAll(games1); // Printing the elements to the console System.out.println(\"EnumSet Using addAll(): \" + games2); }}",
"e": 29382,
"s": 28462,
"text": null
},
{
"code": null,
"e": 29462,
"s": 29382,
"text": "EnumSet Using add(): [HOCKEY]\nEnumSet Using addAll(): [CRICKET, HOCKEY, TENNIS]"
},
{
"code": null,
"e": 29495,
"s": 29462,
"text": " Operation 3: Accessing Elements"
},
{
"code": null,
"e": 29562,
"s": 29495,
"text": "We can access the EnumSet elements by using the iterator() method."
},
{
"code": null,
"e": 29571,
"s": 29562,
"text": "Example:"
},
{
"code": null,
"e": 29576,
"s": 29571,
"text": "Java"
},
{
"code": "// Java program to Access Elements of EnumSet // Importing required classesimport java.util.EnumSet;import java.util.Iterator; // Main class// AccessingElementsOfEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // MAin driver method public static void main(String[] args) { // Creating an EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Creating an iterator on games Iterator<Game> iterate = games.iterator(); // Display message System.out.print(\"EnumSet: \"); while (iterate.hasNext()) { // Iterating and printing elements to // the console using next() method System.out.print(iterate.next()); System.out.print(\", \"); } }}",
"e": 30366,
"s": 29576,
"text": null
},
{
"code": null,
"e": 30400,
"s": 30366,
"text": "EnumSet: CRICKET, HOCKEY, TENNIS,"
},
{
"code": null,
"e": 30431,
"s": 30400,
"text": "Operation 4: Removing elements"
},
{
"code": null,
"e": 30498,
"s": 30431,
"text": "We can remove the elements using remove() and removeAll() methods."
},
{
"code": null,
"e": 30507,
"s": 30498,
"text": "Example:"
},
{
"code": null,
"e": 30512,
"s": 30507,
"text": "Java"
},
{
"code": "// Java program to Remove Elements// from a EnumSet // Importing required classesimport java.util.EnumSet; // Main class// RemovingElementsOfEnumSetclass GFG { // Enum enum Game { CRICKET, HOCKEY, TENNIS } // Main driver method public static void main(String[] args) { // Creating EnumSet using allOf() EnumSet<Game> games = EnumSet.allOf(Game.class); // Printing the EnumSet System.out.println(\"EnumSet: \" + games); // Using remove() boolean value1 = games.remove(Game.CRICKET); // Printing elements to the console System.out.println(\"Is CRICKET removed? \" + value1); // Using removeAll() and storing the boolean result boolean value2 = games.removeAll(games); // Printing elements to the console System.out.println(\"Are all elements removed? \" + value2); }}",
"e": 31407,
"s": 30512,
"text": null
},
{
"code": null,
"e": 31498,
"s": 31407,
"text": "EnumSet: [CRICKET, HOCKEY, TENNIS]\nIs CRICKET removed? true\nAre all elements removed? true"
},
{
"code": null,
"e": 31645,
"s": 31498,
"text": "Some other methods of classes or interfaces are defined below that somehow helps us to get a better understanding of AbstractSet Class as follows:"
},
{
"code": null,
"e": 31652,
"s": 31645,
"text": "METHOD"
},
{
"code": null,
"e": 31664,
"s": 31652,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 31671,
"s": 31664,
"text": "METHOD"
},
{
"code": null,
"e": 31683,
"s": 31671,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 31690,
"s": 31683,
"text": "METHOD"
},
{
"code": null,
"e": 31702,
"s": 31690,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 31709,
"s": 31702,
"text": "METHOD"
},
{
"code": null,
"e": 31721,
"s": 31709,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 31728,
"s": 31721,
"text": "METHOD"
},
{
"code": null,
"e": 31740,
"s": 31728,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 32160,
"s": 31740,
"text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on GeeksforGeek’s 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": 32174,
"s": 32160,
"text": "Chinmoy Lenka"
},
{
"code": null,
"e": 32182,
"s": 32174,
"text": "vogtlcc"
},
{
"code": null,
"e": 32206,
"s": 32182,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 32220,
"s": 32206,
"text": "solankimayank"
},
{
"code": null,
"e": 32236,
"s": 32220,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32253,
"s": 32236,
"text": "Java-Collections"
},
{
"code": null,
"e": 32266,
"s": 32253,
"text": "java-EnumSet"
},
{
"code": null,
"e": 32279,
"s": 32266,
"text": "Java-Library"
},
{
"code": null,
"e": 32284,
"s": 32279,
"text": "Java"
},
{
"code": null,
"e": 32289,
"s": 32284,
"text": "Java"
},
{
"code": null,
"e": 32306,
"s": 32289,
"text": "Java-Collections"
},
{
"code": null,
"e": 32404,
"s": 32306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32419,
"s": 32404,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32463,
"s": 32419,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 32485,
"s": 32463,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 32510,
"s": 32485,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 32546,
"s": 32510,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 32578,
"s": 32546,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32629,
"s": 32578,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32659,
"s": 32629,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32678,
"s": 32659,
"text": "Interfaces in Java"
}
]
|
Animations of Multiple Linear Regression with Python | by Tobias Roeschl | Towards Data Science | In this article, we aim to expand our capabilities in visualizing gradient descent to Multiple Linear Regression. This is the follow-up article to “Gradient Descent Animation: 1. Simple linear regression”. Just as we did before, our goal is to set up a model, fit the model to our training data using batch gradient descent while storing the parameter values for each epoch. Afterwards, we can use our stored data to create animations with Python’s celluloid module.
This is the revised version of an article about the same topic I uploaded on July 20th. Key improvements include the cover photo and some of the animations.
Multiple linear regression is an extended version of simple linear regression in which more than one predictor variable X is used to predict a single dependent variable Y. With n predictor variables, this can be mathematically expressed as
with
and b representing the y-intercept (‘bias’) of our regression plane. Our objective is to find the hyperplane which minimizes the mean squared distance between the training data points and that hyperplane. Gradient descent enables us to determine the optimal values for our model parameters θ, consisting of our weights w and our bias term b, to minimize the mean squared error between observed data points y and data points we predicted with our regression model (ŷ). During training, we aim to update our parameter values according to the following formula until we reach convergence:
with ∇J(θ) representing the gradient of our cost function J with respect to our model parameters θ. The learning rate is represented by α. The partial derivatives for each weight and the bias term are the same as in our simple linear regression model. This time, however, we want to set up a (multi-)linear regression model which is flexible to the number of predictor variables and introduce a weight matrix to adjust all weights simultaneously. Additionally, we store our parameter values in arrays directly during the fitting process itself, which is computationally faster than using for-loops and lists, as we did in the last article. I decided to arbitrarily set the initial parameter values for the weight(s) to 3 and to -1 for the bias. In Python, we import some libraries and set up our model:
After that, we intend to fit our model to some arbitrary training data. Although our model can theoretically handle any number of predictor variables, I chose a training dataset with two predictor variables. We intentionally use a particularly small learning rate, α=0.001, to avoid overly large steps in our animations. Since this article focuses on animations rather than statistical inference, we simply ignore the assumptions of linear regression (e.g. absence of multicollinearity, etc.) for now.
x_train = np.array([ # two independent variables
[1,-2],
[2,1],
[4,1],
[5,-3],
[6,4],
[7,5]
])
y_train = np.array([
[14],
[-12],
[-31],
[-21],
[-51],
[-37]
])
model=LinearRegression(x_train,y_train, lr=0.001) # set learning rate
model.fit(x_train,y_train, numberOfEpochs=100000) # set number of epochs
# Stored parameter values:
w0=model.AllWeights.T[0]
w1=model.AllWeights.T[1]
b= model.AllBiases
c=model.AllCosts
cl=model.cl
print("Final weights: "+ str(model.w)) # print final model parameters
print("Final bias: "+ str(model.b))
print("Final costs: " + str(model.cost(x_train,y_train)))
Final weights: [[-6.75922888]
[-2.07075472]]
Final bias: [[7.23420837]]
Final costs: 75.63518594476348
To ensure our fitted parameters converged to their true values, we verify our results with sklearn’s inborn linear regression model:
# cross-check results with sklearn's linear regression model:
import sklearn
from sklearn.linear_model import LinearRegression
reg = LinearRegression().fit(x_train, y_train)
print(reg.coef_)
print(reg.intercept_)
[[-6.75922888 -2.07075472]]
[7.23420837]
Now, we can finally create our first animation. Like before, we want to begin with visualizing values our cost function and parameters take on with respect to the epoch while plotting the corresponding regression plane in 3-D. As described previously, we intend to only plot values for selected epochs, since the largest steps are usually observed at the beginning of gradient descent. After each for-loop, we take snapshots of our plots. Via Camera’s animate-function we can turn snapshots into animations. In order to get the desired regression plane, we introduce a coordinate grid (M1, M2) via numpy.meshgrid and define a function “pred_meshgrid( )” to calculate the respective z-values with respect to the model parameters at a certain epoch. The dashed connecting lines seen in the following animations can be obtained through line plots between training data points and predicted points. By returning the final parameter values (see commented-out code!) we obtained in our animation, we ensure that we roughly visualized model convergence despite not using the full range of parameter values, we stored during the fitting process.
Despite its simplicity, plotting the values parameters take on for each epoch separately is actually the most informative and most realistic way of visualizing gradient descent with more than two model parameters. This is because we can only witness changes in costs and all model parameters involved simultaneously this way.
When creating more sophisticated animations of gradient descent, especially in 3-D, we have to focus on two model parameters while keeping the third parameter ‘fixed’. We are generally more interested in the weights rather than the bias term of our multiple linear regression model. In order to visualize how costs steadily decrease with our adjusted weights (w0, w1), we have to set up a new linear regression model where the bias term b is fixed. This can easily be done by setting the initial value for b to a predefined value b_fixed and remove the part of code where b is being updated in the new model. b_fixed can take on any value. In this case, we just set it to the y-intercept value the former model converged to:
# set b to the y-intercept value we previously observed.
b_fixed= float(model.b)
# Define new model with fixed intercept:
class LinearRegression_fixed_b(object):
def __init__(self,x,y,b,lr=0.01):
self.lr=lr
self.b=np.array([[b]]) # set fixed(!) starting value for b
self.w=np.ones((1, x.shape[1])).T *3 # set starting weights to 3.
def cost(self,x,y):
pred = [email protected]+self.b
e=y-pred
return np.mean(e**2)
def step(self, x,y):
pred = [email protected]+self.b
e=y-pred
self.w = (self.w.T-self.lr*(np.mean(e*(-2*x), axis=0))).T
def fit(self, x,y, numberOfEpochs=1000000):
self.AllWeights= np.zeros((numberOfEpochs, x.shape[1]))
self.AllBiases= np.zeros(numberOfEpochs)
self.AllCosts= np.zeros(numberOfEpochs)
self.cl= np.zeros((numberOfEpochs,len(x)))
for step in range(numberOfEpochs):
self.AllWeights[step]=self.w.T
self.AllCosts[step]=self.cost(x,y)
self.cl[step]=(self.predict(x)).T.flatten()
self.step(x,y)
def predict(self, x):
return (x @ self.w + self.b)
model=LinearRegression_fixed_b(x_train,y_train,b_fixed, lr=0.001) # set learning rate
model.fit(x_train,y_train, numberOfEpochs=100000) # set number of epochs
w0=model.AllWeights.T[0]
w1=model.AllWeights.T[1]
c=model.AllCosts
cl=model.cl
print("Final weights (fixed-intercept model): "+ str(model.w))
print("Final bias (fixed-intercept model): "+ str(float(model.b)))
print("Final costs (fixed-intercept model): " + str(float(model.cost(x_train,y_train))))
Final weights (fixed-intercept model): [[-6.75922888]
[-2.07075472]]
Final bias (fixed-intercept model): 7.234208367512638
Final costs (fixed-intercept model): 75.63518594476345
After accumulating new data with our new model, we yet again create another coordinate grid (N1, N2) for the following animations. This coordinate grid enables us to plot the costs for every possible pair of w0 and w1 within the given range of numbers.
Contour plots allow us to visualize three-dimensional surfaces on two-dimensional planes via contour lines and filled contours (= contourfs). In our case, we want to plot w0 and w1 on the x-axis and y-axis respectively with the costs J as contours. We can label specific contour levels within the graph with Matplotlib’s contour-function. Since we know that our final costs are roughly 76, we can set our last contour level to 80.
When the y-intercept was allowed to vary, we saw significant changes of parameter values and costs with later epochs, that we did not want to miss out in our regression- and parameter plots. However, with b being fixed, most of the ‘action’ appears to be confined to the first 400 epochs. Thus, we limit the epochs we intend to visualize in the following animations to 400, which is less computationally expensive and results in more appealing animations. To confirm this impression, we can compare the final parameter values, the fixed intercept model returned after 100,000 epochs, to the parameter values we obtain after 400 epochs (see commented-out code below!). Since parameter- and cost values generally match up, it is fair to say that we visualized model convergence despite restricting the number of epochs being visualized.
For the last plot, we want to incorporate the same epochs as we did with the contour plot. This time, however, we want to visualize gradient descent in three dimensions using a surface plot.
Theoretically, plotting the trajectory of gradient descent in the x-y-plane - as we did with the contour plot - corresponds to the ‘real’ trajectory of gradient descent. In contrast to the surface plot above, gradient descent actually does not involve moving in the z-direction at all since only parameters are free to vary. For a more in-depth explanation see here. Lastly, I want to point out that creating animations with Celluloid can be very time-consuming. Especially animations involving surface plots can take up to 40 minutes to return the desired result. Nevertheless, I preferred Celluloid over other packages (e.g. matplotlib.animation) due to its simplicity and clarity. As always, creative input and constructive criticism is appreciated!
I hope you found this article informative and useful. Should any questions arise or if you noticed any mistakes, feel free to leave a comment. In the next article of this series, I will dedicate myself to animations of Gradient Descent on the example of Logistic Regression. The complete notebook can be found on my GitHub.
Thank you for your interest! | [
{
"code": null,
"e": 638,
"s": 171,
"text": "In this article, we aim to expand our capabilities in visualizing gradient descent to Multiple Linear Regression. This is the follow-up article to “Gradient Descent Animation: 1. Simple linear regression”. Just as we did before, our goal is to set up a model, fit the model to our training data using batch gradient descent while storing the parameter values for each epoch. Afterwards, we can use our stored data to create animations with Python’s celluloid module."
},
{
"code": null,
"e": 795,
"s": 638,
"text": "This is the revised version of an article about the same topic I uploaded on July 20th. Key improvements include the cover photo and some of the animations."
},
{
"code": null,
"e": 1035,
"s": 795,
"text": "Multiple linear regression is an extended version of simple linear regression in which more than one predictor variable X is used to predict a single dependent variable Y. With n predictor variables, this can be mathematically expressed as"
},
{
"code": null,
"e": 1040,
"s": 1035,
"text": "with"
},
{
"code": null,
"e": 1627,
"s": 1040,
"text": "and b representing the y-intercept (‘bias’) of our regression plane. Our objective is to find the hyperplane which minimizes the mean squared distance between the training data points and that hyperplane. Gradient descent enables us to determine the optimal values for our model parameters θ, consisting of our weights w and our bias term b, to minimize the mean squared error between observed data points y and data points we predicted with our regression model (ŷ). During training, we aim to update our parameter values according to the following formula until we reach convergence:"
},
{
"code": null,
"e": 2430,
"s": 1627,
"text": "with ∇J(θ) representing the gradient of our cost function J with respect to our model parameters θ. The learning rate is represented by α. The partial derivatives for each weight and the bias term are the same as in our simple linear regression model. This time, however, we want to set up a (multi-)linear regression model which is flexible to the number of predictor variables and introduce a weight matrix to adjust all weights simultaneously. Additionally, we store our parameter values in arrays directly during the fitting process itself, which is computationally faster than using for-loops and lists, as we did in the last article. I decided to arbitrarily set the initial parameter values for the weight(s) to 3 and to -1 for the bias. In Python, we import some libraries and set up our model:"
},
{
"code": null,
"e": 2932,
"s": 2430,
"text": "After that, we intend to fit our model to some arbitrary training data. Although our model can theoretically handle any number of predictor variables, I chose a training dataset with two predictor variables. We intentionally use a particularly small learning rate, α=0.001, to avoid overly large steps in our animations. Since this article focuses on animations rather than statistical inference, we simply ignore the assumptions of linear regression (e.g. absence of multicollinearity, etc.) for now."
},
{
"code": null,
"e": 3577,
"s": 2932,
"text": "x_train = np.array([ # two independent variables\n [1,-2],\n [2,1],\n [4,1],\n [5,-3],\n [6,4],\n [7,5]\n])\n\ny_train = np.array([ \n [14],\n [-12],\n [-31],\n [-21],\n [-51],\n [-37]\n])\n\nmodel=LinearRegression(x_train,y_train, lr=0.001) # set learning rate\nmodel.fit(x_train,y_train, numberOfEpochs=100000) # set number of epochs\n\n# Stored parameter values:\nw0=model.AllWeights.T[0]\nw1=model.AllWeights.T[1]\nb= model.AllBiases\nc=model.AllCosts\ncl=model.cl\n\nprint(\"Final weights: \"+ str(model.w)) # print final model parameters\nprint(\"Final bias: \"+ str(model.b))\nprint(\"Final costs: \" + str(model.cost(x_train,y_train)))\n"
},
{
"code": null,
"e": 3682,
"s": 3577,
"text": "Final weights: [[-6.75922888]\n [-2.07075472]]\nFinal bias: [[7.23420837]]\nFinal costs: 75.63518594476348\n"
},
{
"code": null,
"e": 3815,
"s": 3682,
"text": "To ensure our fitted parameters converged to their true values, we verify our results with sklearn’s inborn linear regression model:"
},
{
"code": null,
"e": 4030,
"s": 3815,
"text": "# cross-check results with sklearn's linear regression model:\nimport sklearn\nfrom sklearn.linear_model import LinearRegression\n\nreg = LinearRegression().fit(x_train, y_train)\nprint(reg.coef_)\nprint(reg.intercept_)\n"
},
{
"code": null,
"e": 4072,
"s": 4030,
"text": "[[-6.75922888 -2.07075472]]\n[7.23420837]\n"
},
{
"code": null,
"e": 5210,
"s": 4072,
"text": "Now, we can finally create our first animation. Like before, we want to begin with visualizing values our cost function and parameters take on with respect to the epoch while plotting the corresponding regression plane in 3-D. As described previously, we intend to only plot values for selected epochs, since the largest steps are usually observed at the beginning of gradient descent. After each for-loop, we take snapshots of our plots. Via Camera’s animate-function we can turn snapshots into animations. In order to get the desired regression plane, we introduce a coordinate grid (M1, M2) via numpy.meshgrid and define a function “pred_meshgrid( )” to calculate the respective z-values with respect to the model parameters at a certain epoch. The dashed connecting lines seen in the following animations can be obtained through line plots between training data points and predicted points. By returning the final parameter values (see commented-out code!) we obtained in our animation, we ensure that we roughly visualized model convergence despite not using the full range of parameter values, we stored during the fitting process."
},
{
"code": null,
"e": 5536,
"s": 5210,
"text": "Despite its simplicity, plotting the values parameters take on for each epoch separately is actually the most informative and most realistic way of visualizing gradient descent with more than two model parameters. This is because we can only witness changes in costs and all model parameters involved simultaneously this way."
},
{
"code": null,
"e": 6261,
"s": 5536,
"text": "When creating more sophisticated animations of gradient descent, especially in 3-D, we have to focus on two model parameters while keeping the third parameter ‘fixed’. We are generally more interested in the weights rather than the bias term of our multiple linear regression model. In order to visualize how costs steadily decrease with our adjusted weights (w0, w1), we have to set up a new linear regression model where the bias term b is fixed. This can easily be done by setting the initial value for b to a predefined value b_fixed and remove the part of code where b is being updated in the new model. b_fixed can take on any value. In this case, we just set it to the y-intercept value the former model converged to:"
},
{
"code": null,
"e": 7931,
"s": 6261,
"text": "# set b to the y-intercept value we previously observed. \nb_fixed= float(model.b) \n\n# Define new model with fixed intercept:\nclass LinearRegression_fixed_b(object): \n def __init__(self,x,y,b,lr=0.01):\n self.lr=lr\n self.b=np.array([[b]]) # set fixed(!) starting value for b\n self.w=np.ones((1, x.shape[1])).T *3 # set starting weights to 3.\n \n def cost(self,x,y): \n pred = [email protected]+self.b \n e=y-pred \n return np.mean(e**2) \n\n def step(self, x,y):\n pred = [email protected]+self.b\n e=y-pred\n self.w = (self.w.T-self.lr*(np.mean(e*(-2*x), axis=0))).T \n \n def fit(self, x,y, numberOfEpochs=1000000):\n self.AllWeights= np.zeros((numberOfEpochs, x.shape[1]))\n self.AllBiases= np.zeros(numberOfEpochs)\n self.AllCosts= np.zeros(numberOfEpochs)\n self.cl= np.zeros((numberOfEpochs,len(x)))\n \n for step in range(numberOfEpochs):\n self.AllWeights[step]=self.w.T\n self.AllCosts[step]=self.cost(x,y)\n self.cl[step]=(self.predict(x)).T.flatten()\n self.step(x,y)\n\n def predict(self, x):\n return (x @ self.w + self.b) \n\n \nmodel=LinearRegression_fixed_b(x_train,y_train,b_fixed, lr=0.001) # set learning rate\nmodel.fit(x_train,y_train, numberOfEpochs=100000) # set number of epochs\n \nw0=model.AllWeights.T[0]\nw1=model.AllWeights.T[1]\nc=model.AllCosts\ncl=model.cl\n\nprint(\"Final weights (fixed-intercept model): \"+ str(model.w))\nprint(\"Final bias (fixed-intercept model): \"+ str(float(model.b)))\nprint(\"Final costs (fixed-intercept model): \" + str(float(model.cost(x_train,y_train))))\n"
},
{
"code": null,
"e": 8111,
"s": 7931,
"text": "Final weights (fixed-intercept model): [[-6.75922888]\n [-2.07075472]]\nFinal bias (fixed-intercept model): 7.234208367512638\nFinal costs (fixed-intercept model): 75.63518594476345\n"
},
{
"code": null,
"e": 8364,
"s": 8111,
"text": "After accumulating new data with our new model, we yet again create another coordinate grid (N1, N2) for the following animations. This coordinate grid enables us to plot the costs for every possible pair of w0 and w1 within the given range of numbers."
},
{
"code": null,
"e": 8795,
"s": 8364,
"text": "Contour plots allow us to visualize three-dimensional surfaces on two-dimensional planes via contour lines and filled contours (= contourfs). In our case, we want to plot w0 and w1 on the x-axis and y-axis respectively with the costs J as contours. We can label specific contour levels within the graph with Matplotlib’s contour-function. Since we know that our final costs are roughly 76, we can set our last contour level to 80."
},
{
"code": null,
"e": 9630,
"s": 8795,
"text": "When the y-intercept was allowed to vary, we saw significant changes of parameter values and costs with later epochs, that we did not want to miss out in our regression- and parameter plots. However, with b being fixed, most of the ‘action’ appears to be confined to the first 400 epochs. Thus, we limit the epochs we intend to visualize in the following animations to 400, which is less computationally expensive and results in more appealing animations. To confirm this impression, we can compare the final parameter values, the fixed intercept model returned after 100,000 epochs, to the parameter values we obtain after 400 epochs (see commented-out code below!). Since parameter- and cost values generally match up, it is fair to say that we visualized model convergence despite restricting the number of epochs being visualized."
},
{
"code": null,
"e": 9821,
"s": 9630,
"text": "For the last plot, we want to incorporate the same epochs as we did with the contour plot. This time, however, we want to visualize gradient descent in three dimensions using a surface plot."
},
{
"code": null,
"e": 10574,
"s": 9821,
"text": "Theoretically, plotting the trajectory of gradient descent in the x-y-plane - as we did with the contour plot - corresponds to the ‘real’ trajectory of gradient descent. In contrast to the surface plot above, gradient descent actually does not involve moving in the z-direction at all since only parameters are free to vary. For a more in-depth explanation see here. Lastly, I want to point out that creating animations with Celluloid can be very time-consuming. Especially animations involving surface plots can take up to 40 minutes to return the desired result. Nevertheless, I preferred Celluloid over other packages (e.g. matplotlib.animation) due to its simplicity and clarity. As always, creative input and constructive criticism is appreciated!"
},
{
"code": null,
"e": 10898,
"s": 10574,
"text": "I hope you found this article informative and useful. Should any questions arise or if you noticed any mistakes, feel free to leave a comment. In the next article of this series, I will dedicate myself to animations of Gradient Descent on the example of Logistic Regression. The complete notebook can be found on my GitHub."
}
]
|
How to create a regression model in R with interaction between all combinations of two variables? | The easiest way to create a regression model with interactions is inputting the variables with multiplication sign that is * but this will create many other combinations that are of higher order. If we want to create the interaction of two variables combinations then power operator can be used as shown in the below examples.
Live Demo
x1<−rnorm(10)
x2<−rnorm(10,1,0.2)
x3<−rnorm(10,1,0.04)
y<−rnorm(10,5,1)
M1<−lm(y~(x1+x2+x3)^2)
summary(M1)
Call:
lm(formula = y ~ (x1 + x2 + x3)^2)
Residuals:
1 2 3 4 5 6 7 8
0.47052 −0.39362 0.37762 −0.80668 0.41637 −0.04845 0.00832 0.27097
9 10
0.14218 −0.43722
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.2893 172.6567 0.002 0.999
x1 28.5300 25.1856 1.133 0.340
x2 7.9753 191.0616 0.042 0.969
x3 3.3123 168.1906 0.020 0.986
x1:x2 1.2607 16.6937 0.076 0.945
x1:x3 −28.3810 19.4585 −1.459 0.241
x2:x3 −6.2240 186.3458 −0.033 0.975
Residual standard error: 0.7372 on 3 degrees of freedom
Multiple R−squared: 0.7996, Adjusted R−squared: 0.3989
F−statistic: 1.995 on 6 and 3 DF, p−value: 0.3048
Live Demo
a1<−rpois(500,5)
a2<−rpois(500,8)
a3<−rpois(500,10)
a4<−rpois(500,2)
a5<−rpois(500,12)
a6<−rpois(500,15)
a7<−rpois(500,9)
y<−rpois(500,1)
M2<−lm(y~(a1+a2+a3+a4+a5+a6+a7)^2)
summary(M2)
Call:
lm(formula = y ~ (a1 + a2 + a3 + a4 + a5 + a6 + a7)^2)
Residuals:
Min 1Q Median 3Q Max
−1.4849 −0.8804 −0.0342 0.6623 4.2336
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) −0.1225469 1.8336636 −0.067 0.94674
a1 0.4629300 0.1548978 2.989 0.00295 **
a2 −0.0330453 0.1246535 −0.265 0.79105
a3 0.0442927 0.1191984 0.372 0.71037
a4 −0.0661164 0.2644226 −0.250 0.80266
a5 0.0657267 0.1035211 0.635 0.52579
a6 −0.0434769 0.0832513 −0.522 0.60175
a7 −0.0132370 0.1187218 −0.111 0.91127
a1:a2 −0.0055441 0.0072067 −0.769 0.44210
a1:a3 −0.0095850 0.0062517 −1.533 0.12590
a1:a4 −0.0197856 0.0156935 −1.261 0.20802
a1:a5 −0.0063698 0.0055879 −1.140 0.25489
a1:a6 −0.0119008 0.0057317 −2.076 0.03841 *
a1:a7 −0.0009957 0.0069639 −0.143 0.88637
a2:a3 −0.0005469 0.0048617 −0.112 0.91049
a2:a4 −0.0096056 0.0119358 −0.805 0.42136
a2:a5 −0.0040884 0.0048707 −0.839 0.40167
a2:a6 0.0059163 0.0045048 1.313 0.18971
a2:a7 0.0023896 0.0052308 0.457 0.64800
a3:a4 −0.0003036 0.0096746 −0.031 0.97498
a3:a5 −0.0070901 0.0045312 −1.565 0.11832
a3:a6 0.0049534 0.0039970 1.239 0.21586
a3:a7 0.0013881 0.0050959 0.272 0.78543
a4:a5 0.0138932 0.0095724 1.451 0.14734
a4:a6 0.0053824 0.0088454 0.608 0.54315
a4:a7 0.0020738 0.0107736 0.192 0.84745
a5:a6 0.0019474 0.0036433 0.535 0.59324
a5:a7 0.0019719 0.0048370 0.408 0.68370
a6:a7 −0.0031881 0.0041510 −0.768 0.44285
−−−
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 1.017 on 471 degrees of freedom
Multiple R−squared: 0.04549, Adjusted R−squared: −0.01126
F−statistic: 0.8016 on 28 and 471 DF, p−value: 0.7563
Live Demo
z1<−runif(100,1,2)
z2<−runif(100,1,4)
z3<−runif(100,1,5)
z4<−runif(100,2,5)
z5<−runif(100,2,10)
y<−runif(100,1,10)
M3<−lm(y~(z1+z2+z3+z4+z5)^2)
summary(M3)
Call:
lm(formula = y ~ (z1 + z2 + z3 + z4 + z5)^2)
Residuals:
Min 1Q Median 3Q Max
−5.4732 −2.0570 0.0582 2.1667 5.3376
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) −2.03476 14.52311 −0.140 0.8889
z1 3.14344 6.80702 0.462 0.6454
z2 3.85518 3.05398 1.262 0.2103
z3 −1.88782 2.16124 −0.873 0.3849
z4 2.75794 3.11048 0.887 0.3778
z5 −0.70359 1.05400 −0.668 0.5063
z1:z2 −2.09623 1.24757 −1.680 0.0966 .
z1:z3 0.17328 0.97128 0.178 0.8588
z1:z4 0.53514 1.26533 0.423 0.6734
z1:z5 0.02687 0.43087 0.062 0.9504
z2:z3 0.15894 0.34335 0.463 0.6446
z2:z4 −0.72427 0.43987 −1.647 0.1034
z2:z5 0.22560 0.16570 1.362 0.1770
z3:z4 −0.16602 0.33847 −0.491 0.6251
z3:z5 0.30484 0.12536 2.432 0.0171 *
z4:z5 −0.19887 0.17768 −1.119 0.2662
−−−
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 2.792 on 84 degrees of freedom
Multiple R−squared: 0.1587, Adjusted R−squared: 0.008411
F−statistic: 1.056 on 15 and 84 DF, p−value: 0.4091 | [
{
"code": null,
"e": 1389,
"s": 1062,
"text": "The easiest way to create a regression model with interactions is inputting the variables with multiplication sign that is * but this will create many other combinations that are of higher order. If we want to create the interaction of two variables combinations then power operator can be used as shown in the below examples."
},
{
"code": null,
"e": 1400,
"s": 1389,
"text": " Live Demo"
},
{
"code": null,
"e": 1715,
"s": 1400,
"text": "x1<−rnorm(10)\nx2<−rnorm(10,1,0.2)\nx3<−rnorm(10,1,0.04)\ny<−rnorm(10,5,1)\nM1<−lm(y~(x1+x2+x3)^2)\nsummary(M1)\nCall:\nlm(formula = y ~ (x1 + x2 + x3)^2)\nResiduals:\n1 2 3 4 5 6 7 8\n0.47052 −0.39362 0.37762 −0.80668 0.41637 −0.04845 0.00832 0.27097\n9 10\n0.14218 −0.43722\nCoefficients:\nEstimate Std. Error t value Pr(>|t|)"
},
{
"code": null,
"e": 1955,
"s": 1715,
"text": "(Intercept) 0.2893 172.6567 0.002 0.999\nx1 28.5300 25.1856 1.133 0.340\nx2 7.9753 191.0616 0.042 0.969\nx3 3.3123 168.1906 0.020 0.986\nx1:x2 1.2607 16.6937 0.076 0.945\nx1:x3 −28.3810 19.4585 −1.459 0.241\nx2:x3 −6.2240 186.3458 −0.033 0.975"
},
{
"code": null,
"e": 2116,
"s": 1955,
"text": "Residual standard error: 0.7372 on 3 degrees of freedom\nMultiple R−squared: 0.7996, Adjusted R−squared: 0.3989\nF−statistic: 1.995 on 6 and 3 DF, p−value: 0.3048"
},
{
"code": null,
"e": 2127,
"s": 2116,
"text": " Live Demo"
},
{
"code": null,
"e": 2494,
"s": 2127,
"text": "a1<−rpois(500,5)\na2<−rpois(500,8)\na3<−rpois(500,10)\na4<−rpois(500,2)\na5<−rpois(500,12)\na6<−rpois(500,15)\na7<−rpois(500,9)\ny<−rpois(500,1)\nM2<−lm(y~(a1+a2+a3+a4+a5+a6+a7)^2)\nsummary(M2)\nCall:\nlm(formula = y ~ (a1 + a2 + a3 + a4 + a5 + a6 + a7)^2)\nResiduals:\nMin 1Q Median 3Q Max\n−1.4849 −0.8804 −0.0342 0.6623 4.2336\nCoefficients:\nEstimate Std. Error t value Pr(>|t|)"
},
{
"code": null,
"e": 3873,
"s": 2494,
"text": "(Intercept) −0.1225469 1.8336636 −0.067 0.94674\na1 0.4629300 0.1548978 2.989 0.00295 **\na2 −0.0330453 0.1246535 −0.265 0.79105\na3 0.0442927 0.1191984 0.372 0.71037\na4 −0.0661164 0.2644226 −0.250 0.80266\na5 0.0657267 0.1035211 0.635 0.52579\na6 −0.0434769 0.0832513 −0.522 0.60175\na7 −0.0132370 0.1187218 −0.111 0.91127\na1:a2 −0.0055441 0.0072067 −0.769 0.44210\na1:a3 −0.0095850 0.0062517 −1.533 0.12590\na1:a4 −0.0197856 0.0156935 −1.261 0.20802\na1:a5 −0.0063698 0.0055879 −1.140 0.25489\na1:a6 −0.0119008 0.0057317 −2.076 0.03841 *\na1:a7 −0.0009957 0.0069639 −0.143 0.88637\na2:a3 −0.0005469 0.0048617 −0.112 0.91049\na2:a4 −0.0096056 0.0119358 −0.805 0.42136\na2:a5 −0.0040884 0.0048707 −0.839 0.40167\na2:a6 0.0059163 0.0045048 1.313 0.18971\na2:a7 0.0023896 0.0052308 0.457 0.64800\na3:a4 −0.0003036 0.0096746 −0.031 0.97498\na3:a5 −0.0070901 0.0045312 −1.565 0.11832\na3:a6 0.0049534 0.0039970 1.239 0.21586\na3:a7 0.0013881 0.0050959 0.272 0.78543\na4:a5 0.0138932 0.0095724 1.451 0.14734\na4:a6 0.0053824 0.0088454 0.608 0.54315\na4:a7 0.0020738 0.0107736 0.192 0.84745\na5:a6 0.0019474 0.0036433 0.535 0.59324\na5:a7 0.0019719 0.0048370 0.408 0.68370\na6:a7 −0.0031881 0.0041510 −0.768 0.44285\n−−−\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 4042,
"s": 3873,
"text": "Residual standard error: 1.017 on 471 degrees of freedom\nMultiple R−squared: 0.04549, Adjusted R−squared: −0.01126\nF−statistic: 0.8016 on 28 and 471 DF, p−value: 0.7563"
},
{
"code": null,
"e": 4053,
"s": 4042,
"text": " Live Demo"
},
{
"code": null,
"e": 4329,
"s": 4053,
"text": "z1<−runif(100,1,2)\nz2<−runif(100,1,4)\nz3<−runif(100,1,5)\nz4<−runif(100,2,5)\nz5<−runif(100,2,10)\ny<−runif(100,1,10)\nM3<−lm(y~(z1+z2+z3+z4+z5)^2)\nsummary(M3)\nCall:\nlm(formula = y ~ (z1 + z2 + z3 + z4 + z5)^2)\nResiduals:\nMin 1Q Median 3Q Max\n−5.4732 −2.0570 0.0582 2.1667 5.3376"
},
{
"code": null,
"e": 5094,
"s": 4329,
"text": "Coefficients:\nEstimate Std. Error t value Pr(>|t|)\n(Intercept) −2.03476 14.52311 −0.140 0.8889\nz1 3.14344 6.80702 0.462 0.6454\nz2 3.85518 3.05398 1.262 0.2103\nz3 −1.88782 2.16124 −0.873 0.3849\nz4 2.75794 3.11048 0.887 0.3778\nz5 −0.70359 1.05400 −0.668 0.5063\nz1:z2 −2.09623 1.24757 −1.680 0.0966 .\nz1:z3 0.17328 0.97128 0.178 0.8588\nz1:z4 0.53514 1.26533 0.423 0.6734\nz1:z5 0.02687 0.43087 0.062 0.9504\nz2:z3 0.15894 0.34335 0.463 0.6446\nz2:z4 −0.72427 0.43987 −1.647 0.1034\nz2:z5 0.22560 0.16570 1.362 0.1770\nz3:z4 −0.16602 0.33847 −0.491 0.6251\nz3:z5 0.30484 0.12536 2.432 0.0171 *\nz4:z5 −0.19887 0.17768 −1.119 0.2662\n−−−\nSignif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 5151,
"s": 5094,
"text": "Residual standard error: 2.792 on 84 degrees of freedom\n"
},
{
"code": null,
"e": 5209,
"s": 5151,
"text": "Multiple R−squared: 0.1587, Adjusted R−squared: 0.008411\n"
},
{
"code": null,
"e": 5261,
"s": 5209,
"text": "F−statistic: 1.056 on 15 and 84 DF, p−value: 0.4091"
}
]
|
JavaFX Effects - Color Adjust | You can adjust the color of an image by applying the color adjust effect to it. This includes the adjustment of the Hue, Saturation, Brightness and Contrast on each pixel.
The class named ColorAdjust of the package javafx.scene.effect represents the color adjust effect, this class contains five properties namely −
input − This property is of the Effect type and it represents an input to the color adjust effect.
input − This property is of the Effect type and it represents an input to the color adjust effect.
brightness − This property is of Double type and it represents the brightness adjustment value for this effect.
brightness − This property is of Double type and it represents the brightness adjustment value for this effect.
contrast − This property is of Double type and it represents the contrast adjustment value for this effect.
contrast − This property is of Double type and it represents the contrast adjustment value for this effect.
hue − This property is of Double type and it represents the hue adjustment value for this effect.
hue − This property is of Double type and it represents the hue adjustment value for this effect.
saturation − This property is of Double type and it represents the saturation adjustment value for this effect.
saturation − This property is of Double type and it represents the saturation adjustment value for this effect.
The following program is an example of demonstrating the color adjust effect. In here, we are embedding an image (Tutorialspoint Logo) in JavaFX scene using Image and ImageView classes. This is being done at the position 100, 70 and with a fit height and fit width of 200 and 400 respectively.
We are adjusting the color of this image using the color adjust effect. With contrast, hue, brightness and saturation values as 0.4. -0.05, 0.9, 0.8.
Save this code in a file with the name ColorAdjustEffectExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class ColorAdjustEffectExample extends Application {
@Override
public void start(Stage stage) {
//Creating an image
Image image = new Image("http://www.tutorialspoint.com/green/images/logo.png");
//Setting the image view
ImageView imageView = new ImageView(image);
//Setting the position of the image
imageView.setX(100);
imageView.setY(70);
//setting the fit height and width of the image view
imageView.setFitHeight(200);
imageView.setFitWidth(400);
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
//Instantiating the ColorAdjust class
ColorAdjust colorAdjust = new ColorAdjust();
//Setting the contrast value
colorAdjust.setContrast(0.4);
//Setting the hue value
colorAdjust.setHue(-0.05);
//Setting the brightness value
colorAdjust.setBrightness(0.9);
//Setting the saturation value
colorAdjust.setSaturation(0.8);
//Applying coloradjust effect to the ImageView node
imageView.setEffect(colorAdjust);
//Creating a Group object
Group root = new Group(imageView);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Coloradjust effect example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac ColorAdjustEffectExample.java
java ColorAdjustEffectExample
On executing, the above program generates a JavaFX window as shown below.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2072,
"s": 1900,
"text": "You can adjust the color of an image by applying the color adjust effect to it. This includes the adjustment of the Hue, Saturation, Brightness and Contrast on each pixel."
},
{
"code": null,
"e": 2216,
"s": 2072,
"text": "The class named ColorAdjust of the package javafx.scene.effect represents the color adjust effect, this class contains five properties namely −"
},
{
"code": null,
"e": 2315,
"s": 2216,
"text": "input − This property is of the Effect type and it represents an input to the color adjust effect."
},
{
"code": null,
"e": 2414,
"s": 2315,
"text": "input − This property is of the Effect type and it represents an input to the color adjust effect."
},
{
"code": null,
"e": 2526,
"s": 2414,
"text": "brightness − This property is of Double type and it represents the brightness adjustment value for this effect."
},
{
"code": null,
"e": 2638,
"s": 2526,
"text": "brightness − This property is of Double type and it represents the brightness adjustment value for this effect."
},
{
"code": null,
"e": 2746,
"s": 2638,
"text": "contrast − This property is of Double type and it represents the contrast adjustment value for this effect."
},
{
"code": null,
"e": 2854,
"s": 2746,
"text": "contrast − This property is of Double type and it represents the contrast adjustment value for this effect."
},
{
"code": null,
"e": 2952,
"s": 2854,
"text": "hue − This property is of Double type and it represents the hue adjustment value for this effect."
},
{
"code": null,
"e": 3050,
"s": 2952,
"text": "hue − This property is of Double type and it represents the hue adjustment value for this effect."
},
{
"code": null,
"e": 3162,
"s": 3050,
"text": "saturation − This property is of Double type and it represents the saturation adjustment value for this effect."
},
{
"code": null,
"e": 3274,
"s": 3162,
"text": "saturation − This property is of Double type and it represents the saturation adjustment value for this effect."
},
{
"code": null,
"e": 3568,
"s": 3274,
"text": "The following program is an example of demonstrating the color adjust effect. In here, we are embedding an image (Tutorialspoint Logo) in JavaFX scene using Image and ImageView classes. This is being done at the position 100, 70 and with a fit height and fit width of 200 and 400 respectively."
},
{
"code": null,
"e": 3718,
"s": 3568,
"text": "We are adjusting the color of this image using the color adjust effect. With contrast, hue, brightness and saturation values as 0.4. -0.05, 0.9, 0.8."
},
{
"code": null,
"e": 3788,
"s": 3718,
"text": "Save this code in a file with the name ColorAdjustEffectExample.java."
},
{
"code": null,
"e": 5771,
"s": 3788,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.scene.effect.ColorAdjust; \nimport javafx.scene.image.Image; \nimport javafx.scene.image.ImageView; \nimport javafx.stage.Stage; \n \npublic class ColorAdjustEffectExample extends Application { \n @Override \n public void start(Stage stage) { \n //Creating an image \n Image image = new Image(\"http://www.tutorialspoint.com/green/images/logo.png\");\n \n //Setting the image view \n ImageView imageView = new ImageView(image); \n \n //Setting the position of the image \n imageView.setX(100); \n imageView.setY(70); \n \n //setting the fit height and width of the image view \n imageView.setFitHeight(200); \n imageView.setFitWidth(400); \n \n //Setting the preserve ratio of the image view \n imageView.setPreserveRatio(true); \n \n //Instantiating the ColorAdjust class \n ColorAdjust colorAdjust = new ColorAdjust(); \n \n //Setting the contrast value \n colorAdjust.setContrast(0.4); \n \n //Setting the hue value \n colorAdjust.setHue(-0.05); \n \n //Setting the brightness value \n colorAdjust.setBrightness(0.9); \n \n //Setting the saturation value \n colorAdjust.setSaturation(0.8); \n \n //Applying coloradjust effect to the ImageView node \n imageView.setEffect(colorAdjust); \n \n //Creating a Group object \n Group root = new Group(imageView); \n \n //Creating a scene object \n Scene scene = new Scene(root, 600, 300); \n \n //Setting title to the Stage \n stage.setTitle(\"Coloradjust effect example\");\n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 5865,
"s": 5771,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 5933,
"s": 5865,
"text": "javac ColorAdjustEffectExample.java \njava ColorAdjustEffectExample\n"
},
{
"code": null,
"e": 6007,
"s": 5933,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 6042,
"s": 6007,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6053,
"s": 6042,
"text": " Syed Raza"
},
{
"code": null,
"e": 6089,
"s": 6053,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6125,
"s": 6089,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6158,
"s": 6125,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6194,
"s": 6158,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 6201,
"s": 6194,
"text": " Print"
},
{
"code": null,
"e": 6212,
"s": 6201,
"text": " Add Notes"
}
]
|
How to write a Python regular expression that matches floating point numbers? | The following code uses Python regex to match floating point numbers
import re
s = '234.6789'
match = re.match(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?',s)
print match.group()
s2 = '0.45'
match = re.match(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?',s2)
print match.group()
This gives the output
234.6789
0.45 | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "The following code uses Python regex to match floating point numbers"
},
{
"code": null,
"e": 1335,
"s": 1131,
"text": "import re\ns = '234.6789'\nmatch = re.match(r'[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?',s)\nprint match.group()\ns2 = '0.45'\nmatch = re.match(r'[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?',s2)\nprint match.group()"
},
{
"code": null,
"e": 1357,
"s": 1335,
"text": "This gives the output"
},
{
"code": null,
"e": 1371,
"s": 1357,
"text": "234.6789\n0.45"
}
]
|
C++ map having key as a user define data type | 30 Mar, 2018
C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator ” < " So if we use our own data type as key, we must overload this operator for our data type.
Let us consider a map having key data type as a structure and mapped value as integer.
// key's structure
struct key
{
int a;
};
// CPP program to demonstrate how a map can// be used to have a user defined data type// as key.#include <bits/stdc++.h>using namespace std;struct Test { int id;}; // We compare Test objects by their ids.bool operator<(const Test& t1, const Test& t2){ return (t1.id < t2.id);} // Driver codeint main(){ Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // Inserting above four objects in an empty map map<Test, int> mp; mp[t1] = 1; mp[t2] = 2; mp[t3] = 3; mp[t4] = 4; // Printing Test objects in sorted order for (auto x : mp) cout << x.first.id << " " << x.second << endl; return 0;}
101 3
102 2
110 1
115 4
We can also make < operator a member of structure/class.
// With < operator defined as member method.#include <bits/stdc++.h>using namespace std;struct Test { int id; // We compare Test objects by their ids. bool operator<(const Test& t) const { return (this->id < t.id); }}; // Driver codeint main(){ Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // Inserting above four objects in an empty map map<Test, int> mp; mp[t1] = 1; mp[t2] = 2; mp[t3] = 3; mp[t4] = 4; // Printing Test objects in sorted order for (auto x : mp) cout << x.first.id << " " << x.second << endl; return 0;}
101 3
102 2
110 1
115 4
What happens if we do not overload < operator?We get compiler error if we try to insert anything into the map.
#include <bits/stdc++.h>using namespace std;struct Test { int id;}; // Driver codeint main(){ map<Test, int> mp; Test t1 = {10}; mp[t1] = 10; return 0;}
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for 'operator<' (operand types are 'const Test' and 'const Test')
{ return __x < __y; }
cpp-map
cpp-operator-overloading
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
Friend class and function in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
Inline Functions in C++
vector insert() function in C++ STL | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Mar, 2018"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator ” < \" So if we use our own data type as key, we must overload this operator for our data type."
},
{
"code": null,
"e": 382,
"s": 295,
"text": "Let us consider a map having key data type as a structure and mapped value as integer."
},
{
"code": null,
"e": 428,
"s": 382,
"text": "// key's structure\nstruct key\n{\n int a;\n};"
},
{
"code": "// CPP program to demonstrate how a map can// be used to have a user defined data type// as key.#include <bits/stdc++.h>using namespace std;struct Test { int id;}; // We compare Test objects by their ids.bool operator<(const Test& t1, const Test& t2){ return (t1.id < t2.id);} // Driver codeint main(){ Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // Inserting above four objects in an empty map map<Test, int> mp; mp[t1] = 1; mp[t2] = 2; mp[t3] = 3; mp[t4] = 4; // Printing Test objects in sorted order for (auto x : mp) cout << x.first.id << \" \" << x.second << endl; return 0;}",
"e": 1073,
"s": 428,
"text": null
},
{
"code": null,
"e": 1098,
"s": 1073,
"text": "101 3\n102 2\n110 1\n115 4\n"
},
{
"code": null,
"e": 1155,
"s": 1098,
"text": "We can also make < operator a member of structure/class."
},
{
"code": "// With < operator defined as member method.#include <bits/stdc++.h>using namespace std;struct Test { int id; // We compare Test objects by their ids. bool operator<(const Test& t) const { return (this->id < t.id); }}; // Driver codeint main(){ Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // Inserting above four objects in an empty map map<Test, int> mp; mp[t1] = 1; mp[t2] = 2; mp[t3] = 3; mp[t4] = 4; // Printing Test objects in sorted order for (auto x : mp) cout << x.first.id << \" \" << x.second << endl; return 0;}",
"e": 1759,
"s": 1155,
"text": null
},
{
"code": null,
"e": 1784,
"s": 1759,
"text": "101 3\n102 2\n110 1\n115 4\n"
},
{
"code": null,
"e": 1895,
"s": 1784,
"text": "What happens if we do not overload < operator?We get compiler error if we try to insert anything into the map."
},
{
"code": "#include <bits/stdc++.h>using namespace std;struct Test { int id;}; // Driver codeint main(){ map<Test, int> mp; Test t1 = {10}; mp[t1] = 10; return 0;}",
"e": 2064,
"s": 1895,
"text": null
},
{
"code": null,
"e": 2223,
"s": 2064,
"text": "/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for 'operator<' (operand types are 'const Test' and 'const Test')\n { return __x < __y; }\n"
},
{
"code": null,
"e": 2231,
"s": 2223,
"text": "cpp-map"
},
{
"code": null,
"e": 2256,
"s": 2231,
"text": "cpp-operator-overloading"
},
{
"code": null,
"e": 2260,
"s": 2256,
"text": "STL"
},
{
"code": null,
"e": 2264,
"s": 2260,
"text": "C++"
},
{
"code": null,
"e": 2268,
"s": 2264,
"text": "STL"
},
{
"code": null,
"e": 2272,
"s": 2268,
"text": "CPP"
},
{
"code": null,
"e": 2370,
"s": 2272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2394,
"s": 2370,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2414,
"s": 2394,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2462,
"s": 2414,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2506,
"s": 2462,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2531,
"s": 2506,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2564,
"s": 2531,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2609,
"s": 2564,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2653,
"s": 2609,
"text": "List in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2677,
"s": 2653,
"text": "Inline Functions in C++"
}
]
|
C# - Continue Statement | The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control passes to the conditional tests.
The syntax for a continue statement in C# is as follows −
continue;
using System;
namespace Loops {
class Program {
static void Main(string[] args) {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
if (a == 15) {
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;
}
while (a < 20);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19 | [
{
"code": null,
"e": 2607,
"s": 2404,
"text": "The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between."
},
{
"code": null,
"e": 2834,
"s": 2607,
"text": "For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control passes to the conditional tests."
},
{
"code": null,
"e": 2893,
"s": 2834,
"text": "The syntax for a continue statement in C# is as follows −"
},
{
"code": null,
"e": 2904,
"s": 2893,
"text": "continue;\n"
},
{
"code": null,
"e": 3399,
"s": 2904,
"text": "using System;\n\nnamespace Loops {\n class Program {\n static void Main(string[] args) {\n /* local variable definition */\n int a = 10;\n \n /* do loop execution */\n do {\n if (a == 15) {\n /* skip the iteration */\n a = a + 1;\n continue;\n }\n Console.WriteLine(\"value of a: {0}\", a);\n a++;\n } \n while (a < 20);\n Console.ReadLine();\n }\n }\n} "
},
{
"code": null,
"e": 3480,
"s": 3399,
"text": "When the above code is compiled and executed, it produces the following result −"
}
]
|
How to Plot Predicted Values in R? | 19 Dec, 2021
In this article, we will discuss how to plot predicted values in the R Programming Language.
A linear model is used to predict the value of an unknown variable based on independent variables using the technique linear regression. It is mostly used for finding out the relationship between variables and forecasting. The lm() function is used to fit linear models to data frames in the R Language. We plot the predicted actual along with actual values to know how much both values differ by, this helps us in determining the accuracy of the model. To do so, we have the following methods in the R Language.
To plot predicted value vs actual values in the R Language, we first fit our data frame into a linear regression model using the lm() function. The lm() function takes a regression function as an argument along with the data frame and returns linear model. Then we can use predict() function to use that linear model to predict values for any given data point. We will then plot a scatter plot between the predicted value and actual by using the plot() function and then add linear diagonal line using the abline() function to visualize the difference between predicted and actual values.
Syntax:
linear_model <- lm( regression_function, df)
plot( predict(linear_model), df$y)
abline(a = 0, b = 1)
where,
regression_function: determines the function on which linear model has to be fitted.
df: determines the data frame that is used for prediction.
y: determines the y-axis variable.
Example: Here, is a plot of actual values vs predicted values using a linear regression model using the Base R methods.
R
# create sample data framex <- rnorm(100)y <- rnorm(100) + xsample_data <- data.frame(x, y) # fit data to a linear modellinear_model <- lm(y~x, sample_data ) # plot predicted values and actual valuesplot(predict(linear_model), sample_data$y, xlab = "Predicted Values", ylab = "Observed Values")abline(a = 0, b = 1, lwd=2, col = "green")
Output:
To plot predicted value vs actual values in the R Language using the ggplot2 package library, we first fit our data frame into a linear regression model using the lm() function. The lm() function takes a regression function as an argument along with the data frame and returns a linear model. Then we make a data frame that contains the predicted value and actual value for plotting. to get predicted values, we can use predict() function to use that linear model to predict values for any given data point. We will then plot a scatter plot between the predicted value and actual by using the ggplot() function with the geom_point() function and then add a linear diagonal line using the geom_abline() function to visualize the difference between predicted and actual values.
Syntax:
linear_model <- lm( regression_function, df)
plot_data <- data.frame( predicted_data = predict(linear_model), actual_data= df$y )
ggplot( plot_data, aes( x=predicted_data, y=actual_data ) ) + geom_point()+ geom_abline(intercept =0, slope=1)
where,
regression_function: determines the function on which linear model has to be fitted.
df: determines the data frame that is used for prediction.
y: determines the y-axis variable.
Example: Here, is a plot of actual values vs predicted values using a linear regression model using the ggplot2 package.
R
# create sample data framex1 <- rnorm(100)x2 <- rnorm(100)y <- rnorm(100) + x1 + x2sample_data <- data.frame(x1, x2, y) # fit data to a linear modellinear_model <- lm(y~x1+x2, sample_data ) # load library ggplot2library(ggplot2) # create dataframe with actual and predicted valuesplot_data <- data.frame(Predicted_value = predict(linear_model), Observed_value = sample_data$y) # plot predicted values and actual valuesggplot(plot_data, aes(x = Predicted_value, y = Observed_value)) + geom_point() + geom_abline(intercept = 0, slope = 1, color = "green")
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "In this article, we will discuss how to plot predicted values in the R Programming Language."
},
{
"code": null,
"e": 634,
"s": 121,
"text": "A linear model is used to predict the value of an unknown variable based on independent variables using the technique linear regression. It is mostly used for finding out the relationship between variables and forecasting. The lm() function is used to fit linear models to data frames in the R Language. We plot the predicted actual along with actual values to know how much both values differ by, this helps us in determining the accuracy of the model. To do so, we have the following methods in the R Language."
},
{
"code": null,
"e": 1223,
"s": 634,
"text": "To plot predicted value vs actual values in the R Language, we first fit our data frame into a linear regression model using the lm() function. The lm() function takes a regression function as an argument along with the data frame and returns linear model. Then we can use predict() function to use that linear model to predict values for any given data point. We will then plot a scatter plot between the predicted value and actual by using the plot() function and then add linear diagonal line using the abline() function to visualize the difference between predicted and actual values."
},
{
"code": null,
"e": 1231,
"s": 1223,
"text": "Syntax:"
},
{
"code": null,
"e": 1276,
"s": 1231,
"text": "linear_model <- lm( regression_function, df)"
},
{
"code": null,
"e": 1311,
"s": 1276,
"text": "plot( predict(linear_model), df$y)"
},
{
"code": null,
"e": 1332,
"s": 1311,
"text": "abline(a = 0, b = 1)"
},
{
"code": null,
"e": 1339,
"s": 1332,
"text": "where,"
},
{
"code": null,
"e": 1424,
"s": 1339,
"text": "regression_function: determines the function on which linear model has to be fitted."
},
{
"code": null,
"e": 1483,
"s": 1424,
"text": "df: determines the data frame that is used for prediction."
},
{
"code": null,
"e": 1518,
"s": 1483,
"text": "y: determines the y-axis variable."
},
{
"code": null,
"e": 1638,
"s": 1518,
"text": "Example: Here, is a plot of actual values vs predicted values using a linear regression model using the Base R methods."
},
{
"code": null,
"e": 1640,
"s": 1638,
"text": "R"
},
{
"code": "# create sample data framex <- rnorm(100)y <- rnorm(100) + xsample_data <- data.frame(x, y) # fit data to a linear modellinear_model <- lm(y~x, sample_data ) # plot predicted values and actual valuesplot(predict(linear_model), sample_data$y, xlab = \"Predicted Values\", ylab = \"Observed Values\")abline(a = 0, b = 1, lwd=2, col = \"green\")",
"e": 1993,
"s": 1640,
"text": null
},
{
"code": null,
"e": 2001,
"s": 1993,
"text": "Output:"
},
{
"code": null,
"e": 2777,
"s": 2001,
"text": "To plot predicted value vs actual values in the R Language using the ggplot2 package library, we first fit our data frame into a linear regression model using the lm() function. The lm() function takes a regression function as an argument along with the data frame and returns a linear model. Then we make a data frame that contains the predicted value and actual value for plotting. to get predicted values, we can use predict() function to use that linear model to predict values for any given data point. We will then plot a scatter plot between the predicted value and actual by using the ggplot() function with the geom_point() function and then add a linear diagonal line using the geom_abline() function to visualize the difference between predicted and actual values."
},
{
"code": null,
"e": 2785,
"s": 2777,
"text": "Syntax:"
},
{
"code": null,
"e": 2830,
"s": 2785,
"text": "linear_model <- lm( regression_function, df)"
},
{
"code": null,
"e": 2915,
"s": 2830,
"text": "plot_data <- data.frame( predicted_data = predict(linear_model), actual_data= df$y )"
},
{
"code": null,
"e": 3026,
"s": 2915,
"text": "ggplot( plot_data, aes( x=predicted_data, y=actual_data ) ) + geom_point()+ geom_abline(intercept =0, slope=1)"
},
{
"code": null,
"e": 3033,
"s": 3026,
"text": "where,"
},
{
"code": null,
"e": 3118,
"s": 3033,
"text": "regression_function: determines the function on which linear model has to be fitted."
},
{
"code": null,
"e": 3177,
"s": 3118,
"text": "df: determines the data frame that is used for prediction."
},
{
"code": null,
"e": 3212,
"s": 3177,
"text": "y: determines the y-axis variable."
},
{
"code": null,
"e": 3333,
"s": 3212,
"text": "Example: Here, is a plot of actual values vs predicted values using a linear regression model using the ggplot2 package."
},
{
"code": null,
"e": 3335,
"s": 3333,
"text": "R"
},
{
"code": "# create sample data framex1 <- rnorm(100)x2 <- rnorm(100)y <- rnorm(100) + x1 + x2sample_data <- data.frame(x1, x2, y) # fit data to a linear modellinear_model <- lm(y~x1+x2, sample_data ) # load library ggplot2library(ggplot2) # create dataframe with actual and predicted valuesplot_data <- data.frame(Predicted_value = predict(linear_model), Observed_value = sample_data$y) # plot predicted values and actual valuesggplot(plot_data, aes(x = Predicted_value, y = Observed_value)) + geom_point() + geom_abline(intercept = 0, slope = 1, color = \"green\")",
"e": 3950,
"s": 3335,
"text": null
},
{
"code": null,
"e": 3958,
"s": 3950,
"text": "Output:"
},
{
"code": null,
"e": 3965,
"s": 3958,
"text": "Picked"
},
{
"code": null,
"e": 3974,
"s": 3965,
"text": "R-Charts"
},
{
"code": null,
"e": 3983,
"s": 3974,
"text": "R-Graphs"
},
{
"code": null,
"e": 3991,
"s": 3983,
"text": "R-plots"
},
{
"code": null,
"e": 4002,
"s": 3991,
"text": "R Language"
},
{
"code": null,
"e": 4100,
"s": 4002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4152,
"s": 4100,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4210,
"s": 4152,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4245,
"s": 4210,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4283,
"s": 4245,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4332,
"s": 4283,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4369,
"s": 4332,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4386,
"s": 4369,
"text": "R - if statement"
},
{
"code": null,
"e": 4429,
"s": 4386,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4466,
"s": 4429,
"text": "How to import an Excel File into R ?"
}
]
|
Why “0” is equal to false in JavaScript ? | 27 Jun, 2019
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
Example: This example illustrates why “0” equals to false.
<script> // JavaScript code to demonstrate // why “0” is equal to false function GFG() { // Print type of "0" document.write(typeof "0" + "</br>"); // Test whether "0" equals to false // or not. If "0" is equal to false // then "0" == false i.e. // false == false which return true var result = ("0" == false); // Print result document.write(result + "</br>"); // Convert and print "0" to its numeric // value document.write(Number("0") + "</br>"); // Convert and print false in numeric value document.write(Number(false) + "</br>"); // So both numeric value are same // Therefore condition "0" == false // evaluates to true document.write("0" == false); document.write("</br>"); // Or this statement document.write(Number("0") == Number(false)); } // Driver code GFG(); </script>
Output:
string
true
0
0
true
true
So, from above it is clear that “0” is equal to false and reason behind this behavior is also clear, but when “0” is tested in if condition then it evaluates to true.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Jun, 2019"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false."
},
{
"code": null,
"e": 366,
"s": 307,
"text": "Example: This example illustrates why “0” equals to false."
},
{
"code": "<script> // JavaScript code to demonstrate // why “0” is equal to false function GFG() { // Print type of \"0\" document.write(typeof \"0\" + \"</br>\"); // Test whether \"0\" equals to false // or not. If \"0\" is equal to false // then \"0\" == false i.e. // false == false which return true var result = (\"0\" == false); // Print result document.write(result + \"</br>\"); // Convert and print \"0\" to its numeric // value document.write(Number(\"0\") + \"</br>\"); // Convert and print false in numeric value document.write(Number(false) + \"</br>\"); // So both numeric value are same // Therefore condition \"0\" == false // evaluates to true document.write(\"0\" == false); document.write(\"</br>\"); // Or this statement document.write(Number(\"0\") == Number(false)); } // Driver code GFG(); </script>",
"e": 1398,
"s": 366,
"text": null
},
{
"code": null,
"e": 1406,
"s": 1398,
"text": "Output:"
},
{
"code": null,
"e": 1433,
"s": 1406,
"text": "string\ntrue\n0\n0\ntrue\ntrue\n"
},
{
"code": null,
"e": 1600,
"s": 1433,
"text": "So, from above it is clear that “0” is equal to false and reason behind this behavior is also clear, but when “0” is tested in if condition then it evaluates to true."
},
{
"code": null,
"e": 1616,
"s": 1600,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1623,
"s": 1616,
"text": "Picked"
},
{
"code": null,
"e": 1634,
"s": 1623,
"text": "JavaScript"
},
{
"code": null,
"e": 1651,
"s": 1634,
"text": "Web Technologies"
},
{
"code": null,
"e": 1678,
"s": 1651,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1776,
"s": 1678,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1837,
"s": 1776,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1909,
"s": 1837,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1949,
"s": 1909,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1990,
"s": 1949,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2032,
"s": 1990,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2094,
"s": 2032,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2127,
"s": 2094,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2188,
"s": 2127,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2238,
"s": 2188,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
PostgreSQL – Constants | 28 Aug, 2020
Unlike variables, the value of constants cannot be changed once initialized. The main purpose of the use of constants in PostgreSQL are:
It makes the query more readable.
It reduces the maintenance efforts.
Syntax: constant_name CONSTANT data_type := expression;
Let’s analyze the above syntax:
First, specify the constant name. By convention, it is generally in the uppercase form.
Second, put the CONSTANT keyword and specify the data type that the constant is associated with.
Third, initialize a value for the constant.
Example 1:
The following example declares a constant named VAT for valued added tax and calculates the selling price from the net price:
DO $$
DECLARE
VAT CONSTANT NUMERIC := 0.1;
net_price NUMERIC := 20.5;
BEGIN
RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
END $$;
Output:
Now let’s attempt to change the constant as below:
DO $$
DECLARE
VAT constant NUMERIC := 0.1;
net_price NUMERIC := 20.5;
BEGIN
RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
VAT := 0.05;
END $$;
As expected it raises an error as shown below:
Example 2:
It is important to note that PostgreSQL evaluates the value for the constant when the block is entered at run-time, not compile-time as shown in the below example:
DO $$
DECLARE
start_at CONSTANT time := now();
BEGIN
RAISE NOTICE 'Start executing block at %', start_at;
END $$;
Output:
PostgreSQL evaluates the NOW( ) function every time we call the block. To prove it, we execute the block again:
And got a different result.
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
PostgreSQL - SELECT | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "Unlike variables, the value of constants cannot be changed once initialized. The main purpose of the use of constants in PostgreSQL are:"
},
{
"code": null,
"e": 199,
"s": 165,
"text": "It makes the query more readable."
},
{
"code": null,
"e": 235,
"s": 199,
"text": "It reduces the maintenance efforts."
},
{
"code": null,
"e": 292,
"s": 235,
"text": "Syntax: constant_name CONSTANT data_type := expression;\n"
},
{
"code": null,
"e": 324,
"s": 292,
"text": "Let’s analyze the above syntax:"
},
{
"code": null,
"e": 412,
"s": 324,
"text": "First, specify the constant name. By convention, it is generally in the uppercase form."
},
{
"code": null,
"e": 509,
"s": 412,
"text": "Second, put the CONSTANT keyword and specify the data type that the constant is associated with."
},
{
"code": null,
"e": 553,
"s": 509,
"text": "Third, initialize a value for the constant."
},
{
"code": null,
"e": 564,
"s": 553,
"text": "Example 1:"
},
{
"code": null,
"e": 690,
"s": 564,
"text": "The following example declares a constant named VAT for valued added tax and calculates the selling price from the net price:"
},
{
"code": null,
"e": 853,
"s": 690,
"text": "DO $$ \nDECLARE\n VAT CONSTANT NUMERIC := 0.1;\n net_price NUMERIC := 20.5;\nBEGIN \n RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );\nEND $$;\n"
},
{
"code": null,
"e": 861,
"s": 853,
"text": "Output:"
},
{
"code": null,
"e": 912,
"s": 861,
"text": "Now let’s attempt to change the constant as below:"
},
{
"code": null,
"e": 1091,
"s": 912,
"text": "DO $$ \nDECLARE\n VAT constant NUMERIC := 0.1;\n net_price NUMERIC := 20.5;\nBEGIN \n RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );\n VAT := 0.05;\nEND $$;\n"
},
{
"code": null,
"e": 1138,
"s": 1091,
"text": "As expected it raises an error as shown below:"
},
{
"code": null,
"e": 1149,
"s": 1138,
"text": "Example 2:"
},
{
"code": null,
"e": 1313,
"s": 1149,
"text": "It is important to note that PostgreSQL evaluates the value for the constant when the block is entered at run-time, not compile-time as shown in the below example:"
},
{
"code": null,
"e": 1436,
"s": 1313,
"text": "DO $$ \nDECLARE\n start_at CONSTANT time := now();\nBEGIN \n RAISE NOTICE 'Start executing block at %', start_at;\nEND $$;\n"
},
{
"code": null,
"e": 1444,
"s": 1436,
"text": "Output:"
},
{
"code": null,
"e": 1556,
"s": 1444,
"text": "PostgreSQL evaluates the NOW( ) function every time we call the block. To prove it, we execute the block again:"
},
{
"code": null,
"e": 1584,
"s": 1556,
"text": "And got a different result."
},
{
"code": null,
"e": 1605,
"s": 1584,
"text": "postgreSQL-dataTypes"
},
{
"code": null,
"e": 1616,
"s": 1605,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1714,
"s": 1616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1752,
"s": 1714,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1782,
"s": 1752,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 1802,
"s": 1782,
"text": "PostgreSQL - INSERT"
},
{
"code": null,
"e": 1826,
"s": 1802,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1854,
"s": 1826,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 1887,
"s": 1854,
"text": "PostgreSQL - ROW_NUMBER Function"
},
{
"code": null,
"e": 1914,
"s": 1887,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 1943,
"s": 1914,
"text": "PostgreSQL - EXISTS Operator"
},
{
"code": null,
"e": 1966,
"s": 1943,
"text": "PostgreSQL - LEFT JOIN"
}
]
|
Why the error Collection was modified; enumeration operation may not execute occurs and how to handle it in C#? | This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or removed) during the runtime.
Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
try {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
}
catch(Exception ex) {
Console.WriteLine($"Exception: {ex.Message}");
Console.ReadLine();
}
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
The output of the above code is
Id: 1, Name: John
Exception: Collection was modified; enumeration operation may not execute.
In the above example, the foreach loop is executed on the studentsList. When the Id of the student is 0, the item will be removed from the studentsList. Because of this change the studentsList gets modified (resized) and an exception is being thrown during the runtime.
To overcome the above issue, perform a ToList() operation on the studentsList before the start of each iteration.
foreach (var student in studentsList.ToList())
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DemoApplication {
public class Program {
static void Main(string[] args) {
var studentsList = new List<Student> {
new Student {
Id = 1,
Name = "John"
},
new Student {
Id = 0,
Name = "Jack"
},
new Student {
Id = 2,
Name = "Jack"
}
};
foreach (var student in studentsList.ToList()) {
if (student.Id <= 0) {
studentsList.Remove(student);
}
else {
Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
}
}
Console.ReadLine();
}
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
}
}
The output of the above code is
Id: 1, Name: John
Id: 2, Name: Jack | [
{
"code": null,
"e": 1347,
"s": 1187,
"text": "This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or removed) during the runtime."
},
{
"code": null,
"e": 1358,
"s": 1347,
"text": " Live Demo"
},
{
"code": null,
"e": 2446,
"s": 1358,
"text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n try {\n var studentsList = new List<Student> {\n new Student {\n Id = 1,\n Name = \"John\"\n },\n new Student {\n Id = 0,\n Name = \"Jack\"\n },\n new Student {\n Id = 2,\n Name = \"Jack\"\n }\n };\n foreach (var student in studentsList) {\n if (student.Id <= 0) {\n studentsList.Remove(student);\n }\n else {\n Console.WriteLine($\"Id: {student.Id}, Name: {student.Name}\");\n }\n }\n }\n catch(Exception ex) {\n Console.WriteLine($\"Exception: {ex.Message}\");\n Console.ReadLine();\n }\n }\n }\n public class Student {\n public int Id { get; set; }\n public string Name { get; set; }\n }\n}"
},
{
"code": null,
"e": 2478,
"s": 2446,
"text": "The output of the above code is"
},
{
"code": null,
"e": 2571,
"s": 2478,
"text": "Id: 1, Name: John\nException: Collection was modified; enumeration operation may not execute."
},
{
"code": null,
"e": 2841,
"s": 2571,
"text": "In the above example, the foreach loop is executed on the studentsList. When the Id of the student is 0, the item will be removed from the studentsList. Because of this change the studentsList gets modified (resized) and an exception is being thrown during the runtime."
},
{
"code": null,
"e": 2955,
"s": 2841,
"text": "To overcome the above issue, perform a ToList() operation on the studentsList before the start of each iteration."
},
{
"code": null,
"e": 3002,
"s": 2955,
"text": "foreach (var student in studentsList.ToList())"
},
{
"code": null,
"e": 3975,
"s": 3002,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Threading.Tasks;\nnamespace DemoApplication {\n public class Program {\n static void Main(string[] args) {\n var studentsList = new List<Student> {\n new Student {\n Id = 1,\n Name = \"John\"\n },\n new Student {\n Id = 0,\n Name = \"Jack\"\n },\n new Student {\n Id = 2,\n Name = \"Jack\"\n }\n };\n foreach (var student in studentsList.ToList()) {\n if (student.Id <= 0) {\n studentsList.Remove(student);\n }\n else {\n Console.WriteLine($\"Id: {student.Id}, Name: {student.Name}\");\n }\n }\n Console.ReadLine();\n }\n }\n public class Student {\n public int Id { get; set; }\n public string Name { get; set; }\n }\n}"
},
{
"code": null,
"e": 4007,
"s": 3975,
"text": "The output of the above code is"
},
{
"code": null,
"e": 4043,
"s": 4007,
"text": "Id: 1, Name: John\nId: 2, Name: Jack"
}
]
|
Node.js util.inspect() Method | 28 Jul, 2020
The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them by ‘require(‘util’)’.
The util.inspect() (Added in v0.3.0) method is an inbuilt application programming interface of the util module which is intended for debugging and returns a string representation of the object. The util.inspect() method is not programmatically dependent. It returns output that may change any time to alter the result supplementary options (like showHidden, depth) could be passed. For inspected value, it either uses the constructor name or @@toStringTag to make an identifiable tag.
Syntax:
const util = require('util');
util.inspect(object[, options])
Parameters: This function accepts two parameters as mentioned above and described below:
object <any>: Any Class, Function, Object, or JavaScript primitive.
object <any>: Any Class, Function, Object, or JavaScript primitive.
options <Object>: The options are of ‘object’ type which accepts the JSON form of the data.showHidden <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then it starts showing hidden non-enumerable symbols and properties along with user-defined prototype, WeakMap and WeakSet entries in the formatted result.depth <number>: By default, the value of the object is set ‘2’. It specifies how many times to recurse and while inspecting large objects and call stack size is passed Infinity or null to recurse up to the maximum.colors <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then output gets colored style with ANSI color codes.customInspect <boolean>: By default, the value of the object is set ‘true’, if it is set ‘false’ then, [[util.inspect.custom](depth, opts)] functions are not invoked.showProxy <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then the target and handler objects are included by the proxy inspection.maxArrayLength <integer>: By default, the value of the object is set ‘100’. While formatting maximum length is specified, i.e. how many Arrays, WeakMaps, and WeakSets are needed to be included in the formatted result. To show (0) no elements, set the value to 0 or negative and to show all elements, set the value to Infinity or null.maxStringLength <integer>: By default, the value of the object is set ‘Infinity’. While formatting the maximum length of characters is specified, i.e. length of characters to be included in the formatted result. To show (”) no characters, set the value to 0 or negative and to show all elements, set the value to Infinity or null.breakLength <integer>: By default, the value of the object is set ’80’. While formatting it specifies the maximum length at which input values are split across multiple lines. To format the input in a single line, set it to Infinity.sorted <boolean> | <Function>: By default, the value of the object is set ‘false’, if it is set ‘true’ or a function is passed, all properties are sorted in the formatted string. Default sort is used if set to ‘true’ and it is used as a compare function if set to a function.getters <boolean> | <string>: By default, the value of the object is set ‘false’, if it is set to ‘true’ then getters will be inspected. If it is set to ‘get’ then only getters will be inspected. If it is set to ‘set’ then only getters with a corresponding setter will be inspected. This risk of side effects is high depending on the getter function.
options <Object>: The options are of ‘object’ type which accepts the JSON form of the data.
showHidden <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then it starts showing hidden non-enumerable symbols and properties along with user-defined prototype, WeakMap and WeakSet entries in the formatted result.
depth <number>: By default, the value of the object is set ‘2’. It specifies how many times to recurse and while inspecting large objects and call stack size is passed Infinity or null to recurse up to the maximum.
colors <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then output gets colored style with ANSI color codes.
customInspect <boolean>: By default, the value of the object is set ‘true’, if it is set ‘false’ then, [[util.inspect.custom](depth, opts)] functions are not invoked.
showProxy <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then the target and handler objects are included by the proxy inspection.
maxArrayLength <integer>: By default, the value of the object is set ‘100’. While formatting maximum length is specified, i.e. how many Arrays, WeakMaps, and WeakSets are needed to be included in the formatted result. To show (0) no elements, set the value to 0 or negative and to show all elements, set the value to Infinity or null.
maxStringLength <integer>: By default, the value of the object is set ‘Infinity’. While formatting the maximum length of characters is specified, i.e. length of characters to be included in the formatted result. To show (”) no characters, set the value to 0 or negative and to show all elements, set the value to Infinity or null.
breakLength <integer>: By default, the value of the object is set ’80’. While formatting it specifies the maximum length at which input values are split across multiple lines. To format the input in a single line, set it to Infinity.
sorted <boolean> | <Function>: By default, the value of the object is set ‘false’, if it is set ‘true’ or a function is passed, all properties are sorted in the formatted string. Default sort is used if set to ‘true’ and it is used as a compare function if set to a function.
getters <boolean> | <string>: By default, the value of the object is set ‘false’, if it is set to ‘true’ then getters will be inspected. If it is set to ‘get’ then only getters will be inspected. If it is set to ‘set’ then only getters with a corresponding setter will be inspected. This risk of side effects is high depending on the getter function.
Return Value: <string>: Returns the formatted string which represents the object.
Example 1: Filename: index.js
// Node.js syntax to demonstrate// the util.inspect() method // Importing util libraryconst util = require('util'); // Objectconst nestedObject = {};nestedObject.a = [nestedObject];nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];nestedObject.b = {};nestedObject.b.inner = nestedObject.b;nestedObject.b.obj = nestedObject; // Inspect by basic methodconsole.log("1.>", util.inspect(nestedObject)); // Random class class geeksForGeeks { } // Inspecting geeksForGeeks class console.log("2.>", util.inspect(new geeksForGeeks())); // Inspect by passing options to methodconsole.log("3.>", util.inspect( nestedObject, true, 0, false)); // Inspect by calling option nameconsole.log("4.>", util.inspect(nestedObject, showHidden = false, depth = 0, colorize = true)); // Inspect by passing in JSON format console.log("5.>", util.inspect(nestedObject, { showHidden: false, depth: 0, colorize: true })); // Inspect by directly calling inspect from 'util'const { inspect } = require('util'); // Directly calling inspect method// with single propertyconsole.log("6.>", inspect(nestedObject), { colorize: true }); // Directly passing the JSON dataconsole.log("7.>", util.inspect([ { name: "Amit", city: "Ayodhya" }, { name: "Satyam", city: "Lucknow" }, { name: "Sahai", city: "Lucknow" }], false, 3, true)); // Directly calling inspect method with single propertyconsole.log("8.>", inspect(nestedObject), { depth: 0 });
Run index.js file using the following command:
node index.js
Output:
1.> <ref *1> {
a: [ [Circular *1] ],
b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
}
2.> geeksForGeeks {}
3.> { a: [Array], b: [Object] }
4.> { a: [Array], b: [Object] }
5.> { a: [Array], b: [Object] }
6.> <ref *1> {
a: [ [Circular *1] ],
b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
} { colorize: true }
7.> [
{ name: 'Amit', city: 'Ayodhya' },
{ name: 'Satyam', city: 'Lucknow' },
{ name: 'Sahai', city: 'Lucknow' }
]
8.> <ref *1> {
a: [ [Circular *1] ],
b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }
} { depth: 0 }
Example 2: Filename: index.js
// Node.js syntax to demonstrate the // util.inspect() method // Import the util module const util = require('util');const { inspect } = require('util'); // Importing http modulevar http = require('http'); // Inspecting http moduleconsole.log("1.>", util.inspect(http, { showHidden: false, depth: 0, showProxy: false})); // Inspecting console moduleconsole.log("2.>", util.inspect( console, showHidden = false, depth = 0, showProxy = true)); // Creating array filled with default value 1const inspectArray = Array(108).fill(1); // Prints the truncated arrayconsole.log("3.>", inspectArray);util.inspect.defaultOptions.maxArrayLength = null; // Prints the full arrayconsole.log("4.>", inspectArray); const object = { amit: [1, 2, [[ 'alfa_romeo, spp___, sahai_harshit ' + 'Annapurna, chai paratha.', 'chota', 'bong']], 55], vikas: new Map([ ['alfa', 1], ['romeo', 'data']])}; // Returns the compact view output.console.log("5.>", util.inspect(object, { compact: true, depth: 5, breakLength: 80})); // Returns the output more reader friendly.console.log("6.>", util.inspect(object, { compact: false, depth: 5, breakLength: 80})); const object1 = { alfa: 10 };const object2 = { beta: 20 }; // Creating weakSetconst inspectingWeakset = new WeakSet([object1, object2]); console.log("7.>", inspect( inspectingWeakset, { showHidden: true }));// Output { { alfa: 10 }, { beta: 20 } } object2[util.inspect.custom] = (depth) => { return { alfaa: 'romeo' };}; console.log("8.>", util.inspect(object2));// Prints: "{ alfaa: 'romeo' }"
Run index.js file using the following command:
node index.js
Output:
1.> { _connectionListener: [Function: connectionListener], .... globalAgent: [Getter/Setter]}2.> { log: [Function: bound consoleCall], .....[Symbol(kFormatForStderr)]: [Function: bound ]}3.> [ 1, 1, 1, 1, 1, 1, .........1, 1, 1, 1, 1, ... 8 more items]4.> [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ....1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]5.> { amit: [ 1, 2, [ [ ‘alfa_romeo, spp___, sahai_harshit Annapurna, chai paratha.’,‘chota’, ‘bong’ ] ], 55 ], vikas: Map(2) { ‘alfa’ => 1, ‘romeo’ => ‘data’ } }6.> returns the output more reader friendly.7.> WeakSet { { alfa: 10 }, { beta: 20 } }8.> { alfaa: ‘romeo’ }
The util.format(format[, ...]) method also gives the same result along with formatted string using the first argument as a printf-like format.
Reference: https://nodejs.org/api/util.html#util_util_inspect_object_options
Node.js-util-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
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": "\n28 Jul, 2020"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them by ‘require(‘util’)’."
},
{
"code": null,
"e": 671,
"s": 186,
"text": "The util.inspect() (Added in v0.3.0) method is an inbuilt application programming interface of the util module which is intended for debugging and returns a string representation of the object. The util.inspect() method is not programmatically dependent. It returns output that may change any time to alter the result supplementary options (like showHidden, depth) could be passed. For inspected value, it either uses the constructor name or @@toStringTag to make an identifiable tag."
},
{
"code": null,
"e": 679,
"s": 671,
"text": "Syntax:"
},
{
"code": null,
"e": 741,
"s": 679,
"text": "const util = require('util');\nutil.inspect(object[, options])"
},
{
"code": null,
"e": 830,
"s": 741,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 898,
"s": 830,
"text": "object <any>: Any Class, Function, Object, or JavaScript primitive."
},
{
"code": null,
"e": 966,
"s": 898,
"text": "object <any>: Any Class, Function, Object, or JavaScript primitive."
},
{
"code": null,
"e": 3519,
"s": 966,
"text": "options <Object>: The options are of ‘object’ type which accepts the JSON form of the data.showHidden <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then it starts showing hidden non-enumerable symbols and properties along with user-defined prototype, WeakMap and WeakSet entries in the formatted result.depth <number>: By default, the value of the object is set ‘2’. It specifies how many times to recurse and while inspecting large objects and call stack size is passed Infinity or null to recurse up to the maximum.colors <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then output gets colored style with ANSI color codes.customInspect <boolean>: By default, the value of the object is set ‘true’, if it is set ‘false’ then, [[util.inspect.custom](depth, opts)] functions are not invoked.showProxy <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then the target and handler objects are included by the proxy inspection.maxArrayLength <integer>: By default, the value of the object is set ‘100’. While formatting maximum length is specified, i.e. how many Arrays, WeakMaps, and WeakSets are needed to be included in the formatted result. To show (0) no elements, set the value to 0 or negative and to show all elements, set the value to Infinity or null.maxStringLength <integer>: By default, the value of the object is set ‘Infinity’. While formatting the maximum length of characters is specified, i.e. length of characters to be included in the formatted result. To show (”) no characters, set the value to 0 or negative and to show all elements, set the value to Infinity or null.breakLength <integer>: By default, the value of the object is set ’80’. While formatting it specifies the maximum length at which input values are split across multiple lines. To format the input in a single line, set it to Infinity.sorted <boolean> | <Function>: By default, the value of the object is set ‘false’, if it is set ‘true’ or a function is passed, all properties are sorted in the formatted string. Default sort is used if set to ‘true’ and it is used as a compare function if set to a function.getters <boolean> | <string>: By default, the value of the object is set ‘false’, if it is set to ‘true’ then getters will be inspected. If it is set to ‘get’ then only getters will be inspected. If it is set to ‘set’ then only getters with a corresponding setter will be inspected. This risk of side effects is high depending on the getter function."
},
{
"code": null,
"e": 3611,
"s": 3519,
"text": "options <Object>: The options are of ‘object’ type which accepts the JSON form of the data."
},
{
"code": null,
"e": 3861,
"s": 3611,
"text": "showHidden <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then it starts showing hidden non-enumerable symbols and properties along with user-defined prototype, WeakMap and WeakSet entries in the formatted result."
},
{
"code": null,
"e": 4076,
"s": 3861,
"text": "depth <number>: By default, the value of the object is set ‘2’. It specifies how many times to recurse and while inspecting large objects and call stack size is passed Infinity or null to recurse up to the maximum."
},
{
"code": null,
"e": 4220,
"s": 4076,
"text": "colors <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then output gets colored style with ANSI color codes."
},
{
"code": null,
"e": 4387,
"s": 4220,
"text": "customInspect <boolean>: By default, the value of the object is set ‘true’, if it is set ‘false’ then, [[util.inspect.custom](depth, opts)] functions are not invoked."
},
{
"code": null,
"e": 4554,
"s": 4387,
"text": "showProxy <boolean>: By default, the value of the object is set ‘False’, if it is set ‘true’ then the target and handler objects are included by the proxy inspection."
},
{
"code": null,
"e": 4889,
"s": 4554,
"text": "maxArrayLength <integer>: By default, the value of the object is set ‘100’. While formatting maximum length is specified, i.e. how many Arrays, WeakMaps, and WeakSets are needed to be included in the formatted result. To show (0) no elements, set the value to 0 or negative and to show all elements, set the value to Infinity or null."
},
{
"code": null,
"e": 5221,
"s": 4889,
"text": "maxStringLength <integer>: By default, the value of the object is set ‘Infinity’. While formatting the maximum length of characters is specified, i.e. length of characters to be included in the formatted result. To show (”) no characters, set the value to 0 or negative and to show all elements, set the value to Infinity or null."
},
{
"code": null,
"e": 5455,
"s": 5221,
"text": "breakLength <integer>: By default, the value of the object is set ’80’. While formatting it specifies the maximum length at which input values are split across multiple lines. To format the input in a single line, set it to Infinity."
},
{
"code": null,
"e": 5731,
"s": 5455,
"text": "sorted <boolean> | <Function>: By default, the value of the object is set ‘false’, if it is set ‘true’ or a function is passed, all properties are sorted in the formatted string. Default sort is used if set to ‘true’ and it is used as a compare function if set to a function."
},
{
"code": null,
"e": 6082,
"s": 5731,
"text": "getters <boolean> | <string>: By default, the value of the object is set ‘false’, if it is set to ‘true’ then getters will be inspected. If it is set to ‘get’ then only getters will be inspected. If it is set to ‘set’ then only getters with a corresponding setter will be inspected. This risk of side effects is high depending on the getter function."
},
{
"code": null,
"e": 6164,
"s": 6082,
"text": "Return Value: <string>: Returns the formatted string which represents the object."
},
{
"code": null,
"e": 6194,
"s": 6164,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Node.js syntax to demonstrate// the util.inspect() method // Importing util libraryconst util = require('util'); // Objectconst nestedObject = {};nestedObject.a = [nestedObject];nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];nestedObject.b = {};nestedObject.b.inner = nestedObject.b;nestedObject.b.obj = nestedObject; // Inspect by basic methodconsole.log(\"1.>\", util.inspect(nestedObject)); // Random class class geeksForGeeks { } // Inspecting geeksForGeeks class console.log(\"2.>\", util.inspect(new geeksForGeeks())); // Inspect by passing options to methodconsole.log(\"3.>\", util.inspect( nestedObject, true, 0, false)); // Inspect by calling option nameconsole.log(\"4.>\", util.inspect(nestedObject, showHidden = false, depth = 0, colorize = true)); // Inspect by passing in JSON format console.log(\"5.>\", util.inspect(nestedObject, { showHidden: false, depth: 0, colorize: true })); // Inspect by directly calling inspect from 'util'const { inspect } = require('util'); // Directly calling inspect method// with single propertyconsole.log(\"6.>\", inspect(nestedObject), { colorize: true }); // Directly passing the JSON dataconsole.log(\"7.>\", util.inspect([ { name: \"Amit\", city: \"Ayodhya\" }, { name: \"Satyam\", city: \"Lucknow\" }, { name: \"Sahai\", city: \"Lucknow\" }], false, 3, true)); // Directly calling inspect method with single propertyconsole.log(\"8.>\", inspect(nestedObject), { depth: 0 });",
"e": 7643,
"s": 6194,
"text": null
},
{
"code": null,
"e": 7690,
"s": 7643,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 7705,
"s": 7690,
"text": "node index.js\n"
},
{
"code": null,
"e": 7713,
"s": 7705,
"text": "Output:"
},
{
"code": null,
"e": 8284,
"s": 7713,
"text": "1.> <ref *1> {\n a: [ [Circular *1] ],\n b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n}\n2.> geeksForGeeks {}\n3.> { a: [Array], b: [Object] }\n4.> { a: [Array], b: [Object] }\n5.> { a: [Array], b: [Object] }\n6.> <ref *1> {\n a: [ [Circular *1] ],\n b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n} { colorize: true }\n7.> [\n { name: 'Amit', city: 'Ayodhya' },\n { name: 'Satyam', city: 'Lucknow' },\n { name: 'Sahai', city: 'Lucknow' }\n]\n8.> <ref *1> {\n a: [ [Circular *1] ],\n b: <ref *2> { inner: [Circular *2], obj: [Circular *1] }\n} { depth: 0 }\n"
},
{
"code": null,
"e": 8314,
"s": 8284,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Node.js syntax to demonstrate the // util.inspect() method // Import the util module const util = require('util');const { inspect } = require('util'); // Importing http modulevar http = require('http'); // Inspecting http moduleconsole.log(\"1.>\", util.inspect(http, { showHidden: false, depth: 0, showProxy: false})); // Inspecting console moduleconsole.log(\"2.>\", util.inspect( console, showHidden = false, depth = 0, showProxy = true)); // Creating array filled with default value 1const inspectArray = Array(108).fill(1); // Prints the truncated arrayconsole.log(\"3.>\", inspectArray);util.inspect.defaultOptions.maxArrayLength = null; // Prints the full arrayconsole.log(\"4.>\", inspectArray); const object = { amit: [1, 2, [[ 'alfa_romeo, spp___, sahai_harshit ' + 'Annapurna, chai paratha.', 'chota', 'bong']], 55], vikas: new Map([ ['alfa', 1], ['romeo', 'data']])}; // Returns the compact view output.console.log(\"5.>\", util.inspect(object, { compact: true, depth: 5, breakLength: 80})); // Returns the output more reader friendly.console.log(\"6.>\", util.inspect(object, { compact: false, depth: 5, breakLength: 80})); const object1 = { alfa: 10 };const object2 = { beta: 20 }; // Creating weakSetconst inspectingWeakset = new WeakSet([object1, object2]); console.log(\"7.>\", inspect( inspectingWeakset, { showHidden: true }));// Output { { alfa: 10 }, { beta: 20 } } object2[util.inspect.custom] = (depth) => { return { alfaa: 'romeo' };}; console.log(\"8.>\", util.inspect(object2));// Prints: \"{ alfaa: 'romeo' }\"",
"e": 9928,
"s": 8314,
"text": null
},
{
"code": null,
"e": 9975,
"s": 9928,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 9990,
"s": 9975,
"text": "node index.js\n"
},
{
"code": null,
"e": 9998,
"s": 9990,
"text": "Output:"
},
{
"code": null,
"e": 10602,
"s": 9998,
"text": "1.> { _connectionListener: [Function: connectionListener], .... globalAgent: [Getter/Setter]}2.> { log: [Function: bound consoleCall], .....[Symbol(kFormatForStderr)]: [Function: bound ]}3.> [ 1, 1, 1, 1, 1, 1, .........1, 1, 1, 1, 1, ... 8 more items]4.> [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ....1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]5.> { amit: [ 1, 2, [ [ ‘alfa_romeo, spp___, sahai_harshit Annapurna, chai paratha.’,‘chota’, ‘bong’ ] ], 55 ], vikas: Map(2) { ‘alfa’ => 1, ‘romeo’ => ‘data’ } }6.> returns the output more reader friendly.7.> WeakSet { { alfa: 10 }, { beta: 20 } }8.> { alfaa: ‘romeo’ }"
},
{
"code": null,
"e": 10746,
"s": 10602,
"text": "The util.format(format[, ...]) method also gives the same result along with formatted string using the first argument as a printf-like format."
},
{
"code": null,
"e": 10823,
"s": 10746,
"text": "Reference: https://nodejs.org/api/util.html#util_util_inspect_object_options"
},
{
"code": null,
"e": 10843,
"s": 10823,
"text": "Node.js-util-module"
},
{
"code": null,
"e": 10851,
"s": 10843,
"text": "Node.js"
},
{
"code": null,
"e": 10868,
"s": 10851,
"text": "Web Technologies"
},
{
"code": null,
"e": 10966,
"s": 10868,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11014,
"s": 10966,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 11047,
"s": 11014,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 11077,
"s": 11047,
"text": "Node.js fs.writeFile() Method"
},
{
"code": null,
"e": 11097,
"s": 11077,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 11151,
"s": 11097,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 11213,
"s": 11151,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 11274,
"s": 11213,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 11324,
"s": 11274,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 11367,
"s": 11324,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
PostgreSQL – EXCEPT Operator | 28 Aug, 2020
In PostgreSQL, the EXCEPT operator is used to return distinct rows from the first (left) query that are not in the output of the second (right) query while comparing result sets of two or more queries.
Syntax:
SELECT column_list
FROM A
WHERE condition_a
EXCEPT
SELECT column_list
FROM B
WHERE condition_b;
The below rules must be obeyed while using the EXCEPT operator:
The number of columns and their orders must be the same in the two queries.
The data types of the respective columns must be compatible.
The below Venn diagram illustrates the result of EXCEPT operator:
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for films that are not in the inventory using EXCEPT operator from data of the “film” and “inventory” tables of our sample database and sort them using ORDER BY clause based on the film title.
SELECT
film_id,
title
FROM
film
EXCEPT
SELECT
DISTINCT inventory.film_id,
title
FROM
inventory
INNER JOIN film ON film.film_id = inventory.film_id
ORDER BY title;
Output:
Example 2:Here we will query for films that are only in the English Language (ie, language_id = 1) using EXCEPT operator from data of the “film” and “language” tables of our sample database and sort them using the ORDER BY clause based on the film title.
SELECT
language_id,
title
FROM
film
WHERE
language_id = 1
EXCEPT
SELECT
DISTINCT language.language_id,
name
FROM
language
INNER JOIN film ON film.language_id = language.language_id
ORDER BY title;;
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "In PostgreSQL, the EXCEPT operator is used to return distinct rows from the first (left) query that are not in the output of the second (right) query while comparing result sets of two or more queries."
},
{
"code": null,
"e": 335,
"s": 230,
"text": "Syntax:\nSELECT column_list\nFROM A\nWHERE condition_a\nEXCEPT \nSELECT column_list\nFROM B\nWHERE condition_b;"
},
{
"code": null,
"e": 399,
"s": 335,
"text": "The below rules must be obeyed while using the EXCEPT operator:"
},
{
"code": null,
"e": 475,
"s": 399,
"text": "The number of columns and their orders must be the same in the two queries."
},
{
"code": null,
"e": 536,
"s": 475,
"text": "The data types of the respective columns must be compatible."
},
{
"code": null,
"e": 602,
"s": 536,
"text": "The below Venn diagram illustrates the result of EXCEPT operator:"
},
{
"code": null,
"e": 989,
"s": 602,
"text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Example 1:Here we will query for films that are not in the inventory using EXCEPT operator from data of the “film” and “inventory” tables of our sample database and sort them using ORDER BY clause based on the film title."
},
{
"code": null,
"e": 1200,
"s": 989,
"text": "SELECT\n film_id,\n title\nFROM\n film\nEXCEPT\n SELECT\n DISTINCT inventory.film_id,\n title\n FROM\n inventory\n INNER JOIN film ON film.film_id = inventory.film_id\nORDER BY title;"
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1463,
"s": 1208,
"text": "Example 2:Here we will query for films that are only in the English Language (ie, language_id = 1) using EXCEPT operator from data of the “film” and “language” tables of our sample database and sort them using the ORDER BY clause based on the film title."
},
{
"code": null,
"e": 1717,
"s": 1463,
"text": "SELECT\n language_id,\n title\nFROM\n film\nWHERE\n language_id = 1\nEXCEPT\n SELECT\n DISTINCT language.language_id,\n name\n FROM\n language\n INNER JOIN film ON film.language_id = language.language_id\nORDER BY title;;"
},
{
"code": null,
"e": 1725,
"s": 1717,
"text": "Output:"
},
{
"code": null,
"e": 1746,
"s": 1725,
"text": "postgreSQL-operators"
},
{
"code": null,
"e": 1757,
"s": 1746,
"text": "PostgreSQL"
}
]
|
How to connect multiple MySQL databases on a single webpage ? | 15 Jul, 2021
This article explains how to connect multiple MySQL databases into a single webpage. It is useful to access data from multiple databases.
There are two methods to connect multiple MySQL databases into a single webpage which are:
Using MySQLi (Improved version of MySQL)
Using PDO (PHP Data Objects)
Syntax:
MySQLi Procedural syntax:
$link = mysqli_connect( “host_name”, “user_name”, “password”, “database_name” );
MySQLi Object Oriented syntax:
$link = new mysqli( “host_name”, “user_name”, “password”, “database_name” );
PDO (PHP Data Objects) syntax:
$pdo = new PDO( “mysql:host=host_name; dbname=database_name”, “user_name”, “password” );
Program: This program uses MySQLi to connect multiple databases on a single webpage.
PHP
<?php// PHP program to connect multiple MySQL database// into single webpage // Connection of first database// Database name => database1// Default username of localhost => root// Default password of localhost is '' (none)$link1 = mysqli_connect("localhost", "root", "", "database1"); // Check for connectionif($link1 == true) { echo "database1 Connected Successfully";}else { die("ERROR: Could not connect " . mysqli_connect_error());} echo "<br>"; // Connection of first database// Database name => database1$link2 = mysqli_connect("localhost", "root", "", "database2"); // Check for connectionif($link2 == true) { echo "database2 Connected Successfully";}else { die("ERROR: Could not connect " . mysqli_connect_error());} echo "<br><br>Display the list of all Databases:<br>"; // Connection of databases$link = mysqli_connect('localhost', 'root', ''); // Display the list of all database name$res = mysqli_query($link, "SHOW DATABASES"); while( $row = mysqli_fetch_assoc($res) ) { echo $row['Database'] . "<br>";} ?>
Output:
sweetyty
mysql
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 167,
"s": 28,
"text": "This article explains how to connect multiple MySQL databases into a single webpage. It is useful to access data from multiple databases. "
},
{
"code": null,
"e": 259,
"s": 167,
"text": "There are two methods to connect multiple MySQL databases into a single webpage which are: "
},
{
"code": null,
"e": 300,
"s": 259,
"text": "Using MySQLi (Improved version of MySQL)"
},
{
"code": null,
"e": 329,
"s": 300,
"text": "Using PDO (PHP Data Objects)"
},
{
"code": null,
"e": 339,
"s": 329,
"text": "Syntax: "
},
{
"code": null,
"e": 365,
"s": 339,
"text": "MySQLi Procedural syntax:"
},
{
"code": null,
"e": 446,
"s": 365,
"text": "$link = mysqli_connect( “host_name”, “user_name”, “password”, “database_name” );"
},
{
"code": null,
"e": 477,
"s": 446,
"text": "MySQLi Object Oriented syntax:"
},
{
"code": null,
"e": 554,
"s": 477,
"text": "$link = new mysqli( “host_name”, “user_name”, “password”, “database_name” );"
},
{
"code": null,
"e": 585,
"s": 554,
"text": "PDO (PHP Data Objects) syntax:"
},
{
"code": null,
"e": 674,
"s": 585,
"text": "$pdo = new PDO( “mysql:host=host_name; dbname=database_name”, “user_name”, “password” );"
},
{
"code": null,
"e": 761,
"s": 674,
"text": "Program: This program uses MySQLi to connect multiple databases on a single webpage. "
},
{
"code": null,
"e": 765,
"s": 761,
"text": "PHP"
},
{
"code": "<?php// PHP program to connect multiple MySQL database// into single webpage // Connection of first database// Database name => database1// Default username of localhost => root// Default password of localhost is '' (none)$link1 = mysqli_connect(\"localhost\", \"root\", \"\", \"database1\"); // Check for connectionif($link1 == true) { echo \"database1 Connected Successfully\";}else { die(\"ERROR: Could not connect \" . mysqli_connect_error());} echo \"<br>\"; // Connection of first database// Database name => database1$link2 = mysqli_connect(\"localhost\", \"root\", \"\", \"database2\"); // Check for connectionif($link2 == true) { echo \"database2 Connected Successfully\";}else { die(\"ERROR: Could not connect \" . mysqli_connect_error());} echo \"<br><br>Display the list of all Databases:<br>\"; // Connection of databases$link = mysqli_connect('localhost', 'root', ''); // Display the list of all database name$res = mysqli_query($link, \"SHOW DATABASES\"); while( $row = mysqli_fetch_assoc($res) ) { echo $row['Database'] . \"<br>\";} ?>",
"e": 1800,
"s": 765,
"text": null
},
{
"code": null,
"e": 1809,
"s": 1800,
"text": "Output: "
},
{
"code": null,
"e": 1820,
"s": 1811,
"text": "sweetyty"
},
{
"code": null,
"e": 1826,
"s": 1820,
"text": "mysql"
},
{
"code": null,
"e": 1833,
"s": 1826,
"text": "Picked"
},
{
"code": null,
"e": 1837,
"s": 1833,
"text": "PHP"
},
{
"code": null,
"e": 1850,
"s": 1837,
"text": "PHP Programs"
},
{
"code": null,
"e": 1867,
"s": 1850,
"text": "Web Technologies"
},
{
"code": null,
"e": 1871,
"s": 1867,
"text": "PHP"
}
]
|
C# | Math.Sin() Method | 31 Jan, 2019
Math.Sin() is an inbuilt Math class method which returns the sine of a given double value argument(specified angle).
Syntax:
public static double Sin(double num)
Parameter:
num: It is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Double.
Return Value: Returns the sine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.
Below are the programs to illustrate the Math.Sin() method.
Program 1: To show the working of Math.Sin() method.
// C# program to demonstrate working// Math.Sin() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 30; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 45; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 60; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 90; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); }}
0.5
0.707106781186547
0.866025403784439
1
Program 2: To show the working of Math.Sin() method when the argument is NaN or infinity.
// C# program to demonstrate working// Math.Sin() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Sin(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Sin(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Sin(nan); Console.WriteLine(result); }}
NaN
NaN
NaN
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 171,
"s": 54,
"text": "Math.Sin() is an inbuilt Math class method which returns the sine of a given double value argument(specified angle)."
},
{
"code": null,
"e": 179,
"s": 171,
"text": "Syntax:"
},
{
"code": null,
"e": 216,
"s": 179,
"text": "public static double Sin(double num)"
},
{
"code": null,
"e": 227,
"s": 216,
"text": "Parameter:"
},
{
"code": null,
"e": 346,
"s": 227,
"text": "num: It is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Double."
},
{
"code": null,
"e": 500,
"s": 346,
"text": "Return Value: Returns the sine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN."
},
{
"code": null,
"e": 560,
"s": 500,
"text": "Below are the programs to illustrate the Math.Sin() method."
},
{
"code": null,
"e": 613,
"s": 560,
"text": "Program 1: To show the working of Math.Sin() method."
},
{
"code": "// C# program to demonstrate working// Math.Sin() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 30; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 45; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 60; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); a = 90; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Sin(b)); }}",
"e": 1526,
"s": 613,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1526,
"text": "0.5\n0.707106781186547\n0.866025403784439\n1\n"
},
{
"code": null,
"e": 1661,
"s": 1571,
"text": "Program 2: To show the working of Math.Sin() method when the argument is NaN or infinity."
},
{
"code": "// C# program to demonstrate working// Math.Sin() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Sin(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Sin(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Sin(nan); Console.WriteLine(result); }}",
"e": 2498,
"s": 1661,
"text": null
},
{
"code": null,
"e": 2511,
"s": 2498,
"text": "NaN\nNaN\nNaN\n"
},
{
"code": null,
"e": 2523,
"s": 2511,
"text": "CSharp-Math"
},
{
"code": null,
"e": 2537,
"s": 2523,
"text": "CSharp-method"
},
{
"code": null,
"e": 2540,
"s": 2537,
"text": "C#"
},
{
"code": null,
"e": 2638,
"s": 2540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2666,
"s": 2638,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2709,
"s": 2666,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2740,
"s": 2709,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2755,
"s": 2740,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2804,
"s": 2755,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2820,
"s": 2804,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2843,
"s": 2820,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 2883,
"s": 2843,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 2901,
"s": 2883,
"text": "C# | Constructors"
}
]
|
Designing a RESTful API to interact with SQLite database | 27 Apr, 2021
In this chapter, we will create Django API views for HTTP requests and will discuss how Django and Django REST framework process each HTTP request.
Creating Django Views
Routing URLs to Django views and functions
Launching Django’s development server
Making HTTP requests using the command-line tool
Making HTTP requests with Postman
In the previous chapters, you have seen how to create a model and its serializer. Now, let’s look at how to process HTTP requests and provide HTTP responses. Here, we will create Django views to process the HTTP requests. On receiving an HTTP request, Django creates an HttpRequest instance and it is passed as the first argument to the view function. This instance contains metadata information that has HTTP verbs such as GET, POST, or PUT. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it easier to test the code, which doesn’t portray a production-ready web service. Let’s get into code implementation.
Python3
from django.http import HttpResponsefrom django.views.decorators.csrf import csrf_exemptfrom rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParserfrom rest_framework import statusfrom taskmanagement.models import TaskManagementfrom taskmanagement.serializers import TaskMngSerializer class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exemptdef task_list(request): if request.method == 'GET': task = TaskManagement.objects.all() task_serializer = TaskMngSerializer(task, many=True) return JSONResponse(task_serializer.data) elif request.method == 'POST': task_data = JSONParser().parse(request) task_serializer = TaskMngSerializer(data=task_data) if task_serializer.is_valid(): task_serializer.save() return JSONResponse(task_serializer.data, \ status=status.HTTP_201_CREATED) return JSONResponse(task_serializer.errors, \ status = status.HTTP_400_BAD_REQUEST) @csrf_exemptdef task_detail(request, pk): try: task = TaskManagement.objects.get(pk=pk) except TaskManagement.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': task_serializer = TaskMngSerializer(task) return JSONResponse(task_serializer.data) elif request.method == 'PUT': task_data = JSONParser().parse(request) task_serializer = TaskMngSerializer(task, data=task_data) if task_serializer.is_valid(): task_serializer.save() return JSONResponse(task_serializer.data) return JSONResponse(task_serializer.errors, \ status=status.HTTP_400_BAD_REQUESTS) elif request.method == 'DELETE': task.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
Let’s evaluate the code. Here we have two functions.
task_list()task_detail()
task_list()
task_detail()
Note: Later we will add the security and throttling rules for our RESTFul web service. And, also we need to remove repeated codes. Now the above code is necessary to understand how basic things work.
The task_list() function is capable of processing two HTTP verbs – GET and POST.
If the verb is GET, the code retrieves all the task management instances.
if request.method == ‘GET’:
task = TaskManagement.objects.all()
task_serializer = TaskMngSerializer(task, many=True)
return JSONResponse(task_serializer.data)
It retrieves all the tasks using TaskManagement.objects.all() method,
serializes the tasks using TaskMngSerializer(task, many=True),
the data generated by TaskMngSerializer is passed to the JSONResponse, and
returns the JSONResponse built.
Note: The many=True argument in TaskMngSerializer(task, many=True) specifies that multiple instances have to be serialized.
If the verb is POST, the code creates a new task. Here the new task is provided as JSON data in the body of the HTTP request.
elif request.method == ‘POST’:
task_data = JSONParser().parse(request)
task_serializer = TaskMngSerializer(data=task_data)
if task_serializer.is_valid():
task_serializer.save()
return JSONResponse(task_serializer.data, \
status=status.HTTP_201_CREATED)
return JSONResponse(task_serializer.errors, \
status = status.HTTP_400_BAD_REQUEST)
Uses JSONParser to parse the request,
Serialize the parsed data using TaskMngSerializer,
If data is valid, it is saved in the database, and
returns the JSONResponse built (contains data and HTTP_201_CREATED status).
The task_detail() function is capable of processing three HTTP verbs – GET, PUT, and DELETE. Here, the function receives the primary key as an argument, and the respective operation is done on the particular instance that has the same key.
If the verb is GET, then the code retrieves a single task based on the key. If the verb is PUT, the code updates the instance and saves it to the database. if the verb is DELETE, then the code deletes the instance from the database, based on the pk value.
Apart from the two functions explained, the code has a class called JSONResponse.
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs[‘content_type’] = ‘application/json’
super(JSONResponse, self).__init__(content, **kwargs)
It renders the data in JSON and saves the returned byte string in the content local variable.
Now, it’s necessary to route URLs to view. You need to create a new Python file name urls.py in the taskmanagement folder (restapi\taskmanagement) and add the below code.
Python3
from django.conf.urls import urlfrom taskmanagement import views urlpatterns = [ url(r'^taskmanagement/$',views.task_list), url(r'^taskmanagement/(?P<pk>[0-9]+)$', views.task_detail),]
Based on the matching regular expression the URLs are routed to corresponding views. Next, we have to replace the code in the urls.py file in restapi folder (restapi\restapi\urls.py). At present, it has the root URL configurations. Update the urls.py file with the below code.
Python3
from django.conf.urls import url, include urlpatterns = [ url(r'^',include('taskmanagement.urls')), ]
After activating the virtual environment, you can run the below command to start the server.
python manage.py runserver
Sharing the screenshot below.
Development server
Let’s make use of the command-line tools that we installed in Chapter 1.
The HTTP GET requests are used to retrieve the task details from the database. We can use GET requests to retrieve a collection of tasks or a single task.
The below curl command retrieves a collection of tasks.
curl -X GET localhost:8000/taskmanagement/
Output:
On executing the command, Django creates an HttpRequest instance and it is passed as the first argument to the view function. The Django routes the URL to the appropriate view function. Here the views have two methods, task_list and task_detail. Let’s look into the URL pattern, which is configured in taskmanagement\urls.py file
urlpatterns = [
url(r’^taskmanagement/$’,views.task_list),
url(r’^taskmanagement/(?P<pk>[0-9]+)$’, views.task_detail),
]
Here the URL (localhost:8000/taskmanagement/) matches the URL pattern for views.task_list. The task_list method gets executed and checks the HTTP verb. Since our HTTP verb for the request is GET, it retrieves all the tasks.
Let’s run the command to retrieve all the tasks by combining the -i and -X options. Here the benefit is that it shows the HTTP response header, status, Content-Type, etc.
curl -iX GET localhost:8000/taskmanagement/
Output:
So far we have executed the cURL command. Now we will look at the HTTPie utility command to compose and send HTTP requests. For this, we need to access the HTTPie utility prompt installed in the virtual environment. After activating the virtual environment, run the below command.
http :8000/taskmanagement/
The command sends the request: GET http://localhost:8000/taskmanagement/.
Output:
HTTPie utility GET request – retrieve all tasks
Now you are familiar with the command to retrieve a collection of tasks. Next, let’s understand how to retrieve a task based on a task id. Here, we will pass the task id along with the URL. Since the URL has a parameter, Django routes the URL to the task_detail function. Let’s execute the commands.
The HTTPie utility command to retrieve a single task.
http :8000/taskmanagement/2
The above command sends the request: GET http://localhost:8000/taskmanagement/2.
Output:
Retrieve a single element using HTTPie utility
The equivalent curl command as follows:
curl -iX GET localhost:8000/taskmanagement/2
Output:
Let’s try to retrieve an element that is not in the database.
http :8000/taskmanagement/5
The output as follows
HTTP/1.1 404 Not Found
Content-Length: 0
Content-Type: text/html; charset=utf-8
Date: Fri, 30 Oct 2020 14:32:46 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.7.5
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
We use POST requests to create a task. The HTTPUtilityPie command to create a new ask as follows.
http POST :8000/taskmanagement/ task_name=”Document XYZ” task_desc=”Document Description” category=”Writing” priority=”Low” created_date=”2020-10-30 00:00:00.000000+00:00′′ deadline=”2020-11-03 00:00:00.000000+00:00′′ status=”Pending” payment_done=false
Here the URL request (http POST :8000/taskmanagement/ ) matches the regular expression (taskmanagement/$). Hence, it calls the function task_list, and the POST verb satisfies the condition to execute the code for the task creation.
Output:
POST Request using HTTPUtilityPie
Let’s create another instance using the curl command. The curl command for POST request as follows
curl -iX POST -H “Content-Type: application/json” -d “{\”task_name\”:\”Task 01\”, \”task_desc\”:\”Desc 01\”, \”category\”:\”Writing\”, \”priority\”:\”Medium\”, \”created_date\”:\”2020-10-27 13:02:20.890678\”, \”deadline\”:\”2020-10-29 00:00:00.000000+00:00\”, \”status\”:\”Completed\”, \”payment_done\”: \”true\”}” localhost:8000/taskmanagement/
Output:
POST Request using curl
Here the data required to create a new task is specified after -d and the usage of -H “Content-Type: application/json” signifies the data is in JSON format.
{
“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-10-27 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”
}
We make use of PUT request to update an existing task. Here we pass the id of the task that needs to be updated along with the URL. Since the URL has a parameter, Django sends the URL instance to the task_detail function in views. And, executes the code that holds the condition for the PUT verb.
The HTTPie utility command to update the task:
http PUT :8000/taskmanagement/1 task_name=”Swap two elements” task_desc=”Write a Python program to swap two elements in a list” category=”Writing” priority=”Medium” created_date=”2020-10-27 13:02:20.890678′′ deadline=”2020-10-29 00:00:00.000000+00:00′′ status=”Completed” payment_done=true
Output:
PUT
The equivalent CURL command as follows
curl -iX PUT -H “Content-Type: application/json” -d “{\”task_name\”:\”Swap two elements\”, \”task_desc\”:\”Write a Python program to swap two elements in a list\”, \”category\”:\”Writing\”, \”priority\”:\”Medium\”, \”created_date\”:\”2020-10-27 13:02:20.890678\”, \”deadline\”:\”2020-10-29 00:00:00.000000+00:00\”, \”status\”:\”Completed\”, \”payment_done\”: \”true\”}” localhost:8000/taskmanagement/1
The HTTP DELETE Request is used to delete a particular task from the database. Let’s look at the HTTPie utility command.
http DELETE :8000/taskmanagement/4
Output:
Delete Request
The equivalent curl command as follows:
curl -iX DELETE localhost:8000/taskmanagement/4
So far, we took advantage of command-line tools to compose and send HTTP requests. Now, we will make use of Postman. Postman REST client is a Graphical User Interface (GUI) tool that facilitates composing and sending HTTP requests to the Django development server. Let’s compose and send GET and POST requests.
You can select GET in the drop-down menu, type the URL (localhost:8000/taskmanagement/) in the URL field, and hit the Send button. The Postman will display the information in the output Body section. The below screenshot shows the JSON output response.
HTTP GET request using Postman
You can click the Header tab to view the header details. Sharing the screenshot below:
Header
Now let’s send a POST request using the Postman GUI tool. Follow the below steps:
Select the POST verb from the drop-down menu,Type the URL in the URL field (localhost:8000/taskmanagement/)Select the Body section (in the input section)Check the raw radio button and also select JSON in the dropdown menu on the right side of the GraphQL buttonEnter the following lines {“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-11-02 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”} in the body (input section). and hit send.
Select the POST verb from the drop-down menu,
Type the URL in the URL field (localhost:8000/taskmanagement/)
Select the Body section (in the input section)
Check the raw radio button and also select JSON in the dropdown menu on the right side of the GraphQL button
Enter the following lines {“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-11-02 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”} in the body (input section). and hit send.
Sharing the screenshot below.
In this article, we created a Django API view for HTTP requests to interact with the SQLite database through the RESTFul web service. We worked with GET, POST, PUT, and DELETE HTTP verbs. We have seen how to send and compose HTTP requests using command-line tools (curl and HTTPie) and the GUI tool (POSTMAN).
Django-REST
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 177,
"s": 28,
"text": "In this chapter, we will create Django API views for HTTP requests and will discuss how Django and Django REST framework process each HTTP request. "
},
{
"code": null,
"e": 199,
"s": 177,
"text": "Creating Django Views"
},
{
"code": null,
"e": 242,
"s": 199,
"text": "Routing URLs to Django views and functions"
},
{
"code": null,
"e": 280,
"s": 242,
"text": "Launching Django’s development server"
},
{
"code": null,
"e": 329,
"s": 280,
"text": "Making HTTP requests using the command-line tool"
},
{
"code": null,
"e": 363,
"s": 329,
"text": "Making HTTP requests with Postman"
},
{
"code": null,
"e": 1110,
"s": 363,
"text": "In the previous chapters, you have seen how to create a model and its serializer. Now, let’s look at how to process HTTP requests and provide HTTP responses. Here, we will create Django views to process the HTTP requests. On receiving an HTTP request, Django creates an HttpRequest instance and it is passed as the first argument to the view function. This instance contains metadata information that has HTTP verbs such as GET, POST, or PUT. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it easier to test the code, which doesn’t portray a production-ready web service. Let’s get into code implementation."
},
{
"code": null,
"e": 1118,
"s": 1110,
"text": "Python3"
},
{
"code": "from django.http import HttpResponsefrom django.views.decorators.csrf import csrf_exemptfrom rest_framework.renderers import JSONRendererfrom rest_framework.parsers import JSONParserfrom rest_framework import statusfrom taskmanagement.models import TaskManagementfrom taskmanagement.serializers import TaskMngSerializer class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exemptdef task_list(request): if request.method == 'GET': task = TaskManagement.objects.all() task_serializer = TaskMngSerializer(task, many=True) return JSONResponse(task_serializer.data) elif request.method == 'POST': task_data = JSONParser().parse(request) task_serializer = TaskMngSerializer(data=task_data) if task_serializer.is_valid(): task_serializer.save() return JSONResponse(task_serializer.data, \\ status=status.HTTP_201_CREATED) return JSONResponse(task_serializer.errors, \\ status = status.HTTP_400_BAD_REQUEST) @csrf_exemptdef task_detail(request, pk): try: task = TaskManagement.objects.get(pk=pk) except TaskManagement.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': task_serializer = TaskMngSerializer(task) return JSONResponse(task_serializer.data) elif request.method == 'PUT': task_data = JSONParser().parse(request) task_serializer = TaskMngSerializer(task, data=task_data) if task_serializer.is_valid(): task_serializer.save() return JSONResponse(task_serializer.data) return JSONResponse(task_serializer.errors, \\ status=status.HTTP_400_BAD_REQUESTS) elif request.method == 'DELETE': task.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT) ",
"e": 3204,
"s": 1118,
"text": null
},
{
"code": null,
"e": 3257,
"s": 3204,
"text": "Let’s evaluate the code. Here we have two functions."
},
{
"code": null,
"e": 3282,
"s": 3257,
"text": "task_list()task_detail()"
},
{
"code": null,
"e": 3294,
"s": 3282,
"text": "task_list()"
},
{
"code": null,
"e": 3308,
"s": 3294,
"text": "task_detail()"
},
{
"code": null,
"e": 3508,
"s": 3308,
"text": "Note: Later we will add the security and throttling rules for our RESTFul web service. And, also we need to remove repeated codes. Now the above code is necessary to understand how basic things work."
},
{
"code": null,
"e": 3590,
"s": 3508,
"text": "The task_list() function is capable of processing two HTTP verbs – GET and POST. "
},
{
"code": null,
"e": 3665,
"s": 3590,
"text": "If the verb is GET, the code retrieves all the task management instances. "
},
{
"code": null,
"e": 3693,
"s": 3665,
"text": "if request.method == ‘GET’:"
},
{
"code": null,
"e": 3736,
"s": 3693,
"text": " task = TaskManagement.objects.all()"
},
{
"code": null,
"e": 3796,
"s": 3736,
"text": " task_serializer = TaskMngSerializer(task, many=True)"
},
{
"code": null,
"e": 3845,
"s": 3796,
"text": " return JSONResponse(task_serializer.data)"
},
{
"code": null,
"e": 3915,
"s": 3845,
"text": "It retrieves all the tasks using TaskManagement.objects.all() method,"
},
{
"code": null,
"e": 3978,
"s": 3915,
"text": "serializes the tasks using TaskMngSerializer(task, many=True),"
},
{
"code": null,
"e": 4053,
"s": 3978,
"text": "the data generated by TaskMngSerializer is passed to the JSONResponse, and"
},
{
"code": null,
"e": 4085,
"s": 4053,
"text": "returns the JSONResponse built."
},
{
"code": null,
"e": 4209,
"s": 4085,
"text": "Note: The many=True argument in TaskMngSerializer(task, many=True) specifies that multiple instances have to be serialized."
},
{
"code": null,
"e": 4335,
"s": 4209,
"text": "If the verb is POST, the code creates a new task. Here the new task is provided as JSON data in the body of the HTTP request."
},
{
"code": null,
"e": 4366,
"s": 4335,
"text": "elif request.method == ‘POST’:"
},
{
"code": null,
"e": 4413,
"s": 4366,
"text": " task_data = JSONParser().parse(request)"
},
{
"code": null,
"e": 4472,
"s": 4413,
"text": " task_serializer = TaskMngSerializer(data=task_data)"
},
{
"code": null,
"e": 4510,
"s": 4472,
"text": " if task_serializer.is_valid():"
},
{
"code": null,
"e": 4544,
"s": 4510,
"text": " task_serializer.save()"
},
{
"code": null,
"e": 4599,
"s": 4544,
"text": " return JSONResponse(task_serializer.data, \\"
},
{
"code": null,
"e": 4662,
"s": 4599,
"text": " status=status.HTTP_201_CREATED)"
},
{
"code": null,
"e": 4715,
"s": 4662,
"text": " return JSONResponse(task_serializer.errors, \\"
},
{
"code": null,
"e": 4780,
"s": 4715,
"text": " status = status.HTTP_400_BAD_REQUEST)"
},
{
"code": null,
"e": 4818,
"s": 4780,
"text": "Uses JSONParser to parse the request,"
},
{
"code": null,
"e": 4869,
"s": 4818,
"text": "Serialize the parsed data using TaskMngSerializer,"
},
{
"code": null,
"e": 4920,
"s": 4869,
"text": "If data is valid, it is saved in the database, and"
},
{
"code": null,
"e": 4996,
"s": 4920,
"text": "returns the JSONResponse built (contains data and HTTP_201_CREATED status)."
},
{
"code": null,
"e": 5236,
"s": 4996,
"text": "The task_detail() function is capable of processing three HTTP verbs – GET, PUT, and DELETE. Here, the function receives the primary key as an argument, and the respective operation is done on the particular instance that has the same key."
},
{
"code": null,
"e": 5492,
"s": 5236,
"text": "If the verb is GET, then the code retrieves a single task based on the key. If the verb is PUT, the code updates the instance and saves it to the database. if the verb is DELETE, then the code deletes the instance from the database, based on the pk value."
},
{
"code": null,
"e": 5574,
"s": 5492,
"text": "Apart from the two functions explained, the code has a class called JSONResponse."
},
{
"code": null,
"e": 5608,
"s": 5574,
"text": "class JSONResponse(HttpResponse):"
},
{
"code": null,
"e": 5647,
"s": 5608,
"text": " def __init__(self, data, **kwargs):"
},
{
"code": null,
"e": 5692,
"s": 5647,
"text": " content = JSONRenderer().render(data)"
},
{
"code": null,
"e": 5743,
"s": 5692,
"text": " kwargs[‘content_type’] = ‘application/json’"
},
{
"code": null,
"e": 5804,
"s": 5743,
"text": " super(JSONResponse, self).__init__(content, **kwargs)"
},
{
"code": null,
"e": 5898,
"s": 5804,
"text": "It renders the data in JSON and saves the returned byte string in the content local variable."
},
{
"code": null,
"e": 6069,
"s": 5898,
"text": "Now, it’s necessary to route URLs to view. You need to create a new Python file name urls.py in the taskmanagement folder (restapi\\taskmanagement) and add the below code."
},
{
"code": null,
"e": 6077,
"s": 6069,
"text": "Python3"
},
{
"code": "from django.conf.urls import urlfrom taskmanagement import views urlpatterns = [ url(r'^taskmanagement/$',views.task_list), url(r'^taskmanagement/(?P<pk>[0-9]+)$', views.task_detail),]",
"e": 6269,
"s": 6077,
"text": null
},
{
"code": null,
"e": 6546,
"s": 6269,
"text": "Based on the matching regular expression the URLs are routed to corresponding views. Next, we have to replace the code in the urls.py file in restapi folder (restapi\\restapi\\urls.py). At present, it has the root URL configurations. Update the urls.py file with the below code."
},
{
"code": null,
"e": 6554,
"s": 6546,
"text": "Python3"
},
{
"code": "from django.conf.urls import url, include urlpatterns = [ url(r'^',include('taskmanagement.urls')), ]",
"e": 6660,
"s": 6554,
"text": null
},
{
"code": null,
"e": 6753,
"s": 6660,
"text": "After activating the virtual environment, you can run the below command to start the server."
},
{
"code": null,
"e": 6780,
"s": 6753,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 6810,
"s": 6780,
"text": "Sharing the screenshot below."
},
{
"code": null,
"e": 6829,
"s": 6810,
"text": "Development server"
},
{
"code": null,
"e": 6902,
"s": 6829,
"text": "Let’s make use of the command-line tools that we installed in Chapter 1."
},
{
"code": null,
"e": 7058,
"s": 6902,
"text": "The HTTP GET requests are used to retrieve the task details from the database. We can use GET requests to retrieve a collection of tasks or a single task. "
},
{
"code": null,
"e": 7115,
"s": 7058,
"text": "The below curl command retrieves a collection of tasks. "
},
{
"code": null,
"e": 7158,
"s": 7115,
"text": "curl -X GET localhost:8000/taskmanagement/"
},
{
"code": null,
"e": 7166,
"s": 7158,
"text": "Output:"
},
{
"code": null,
"e": 7496,
"s": 7166,
"text": "On executing the command, Django creates an HttpRequest instance and it is passed as the first argument to the view function. The Django routes the URL to the appropriate view function. Here the views have two methods, task_list and task_detail. Let’s look into the URL pattern, which is configured in taskmanagement\\urls.py file"
},
{
"code": null,
"e": 7512,
"s": 7496,
"text": "urlpatterns = ["
},
{
"code": null,
"e": 7558,
"s": 7512,
"text": " url(r’^taskmanagement/$’,views.task_list),"
},
{
"code": null,
"e": 7621,
"s": 7558,
"text": " url(r’^taskmanagement/(?P<pk>[0-9]+)$’, views.task_detail),"
},
{
"code": null,
"e": 7623,
"s": 7621,
"text": "]"
},
{
"code": null,
"e": 7847,
"s": 7623,
"text": "Here the URL (localhost:8000/taskmanagement/) matches the URL pattern for views.task_list. The task_list method gets executed and checks the HTTP verb. Since our HTTP verb for the request is GET, it retrieves all the tasks."
},
{
"code": null,
"e": 8018,
"s": 7847,
"text": "Let’s run the command to retrieve all the tasks by combining the -i and -X options. Here the benefit is that it shows the HTTP response header, status, Content-Type, etc."
},
{
"code": null,
"e": 8062,
"s": 8018,
"text": "curl -iX GET localhost:8000/taskmanagement/"
},
{
"code": null,
"e": 8070,
"s": 8062,
"text": "Output:"
},
{
"code": null,
"e": 8351,
"s": 8070,
"text": "So far we have executed the cURL command. Now we will look at the HTTPie utility command to compose and send HTTP requests. For this, we need to access the HTTPie utility prompt installed in the virtual environment. After activating the virtual environment, run the below command."
},
{
"code": null,
"e": 8378,
"s": 8351,
"text": "http :8000/taskmanagement/"
},
{
"code": null,
"e": 8452,
"s": 8378,
"text": "The command sends the request: GET http://localhost:8000/taskmanagement/."
},
{
"code": null,
"e": 8460,
"s": 8452,
"text": "Output:"
},
{
"code": null,
"e": 8508,
"s": 8460,
"text": "HTTPie utility GET request – retrieve all tasks"
},
{
"code": null,
"e": 8808,
"s": 8508,
"text": "Now you are familiar with the command to retrieve a collection of tasks. Next, let’s understand how to retrieve a task based on a task id. Here, we will pass the task id along with the URL. Since the URL has a parameter, Django routes the URL to the task_detail function. Let’s execute the commands."
},
{
"code": null,
"e": 8862,
"s": 8808,
"text": "The HTTPie utility command to retrieve a single task."
},
{
"code": null,
"e": 8890,
"s": 8862,
"text": "http :8000/taskmanagement/2"
},
{
"code": null,
"e": 8972,
"s": 8890,
"text": "The above command sends the request: GET http://localhost:8000/taskmanagement/2. "
},
{
"code": null,
"e": 8980,
"s": 8972,
"text": "Output:"
},
{
"code": null,
"e": 9027,
"s": 8980,
"text": "Retrieve a single element using HTTPie utility"
},
{
"code": null,
"e": 9067,
"s": 9027,
"text": "The equivalent curl command as follows:"
},
{
"code": null,
"e": 9112,
"s": 9067,
"text": "curl -iX GET localhost:8000/taskmanagement/2"
},
{
"code": null,
"e": 9120,
"s": 9112,
"text": "Output:"
},
{
"code": null,
"e": 9182,
"s": 9120,
"text": "Let’s try to retrieve an element that is not in the database."
},
{
"code": null,
"e": 9211,
"s": 9182,
"text": " http :8000/taskmanagement/5"
},
{
"code": null,
"e": 9233,
"s": 9211,
"text": "The output as follows"
},
{
"code": null,
"e": 9469,
"s": 9233,
"text": "HTTP/1.1 404 Not Found\nContent-Length: 0\nContent-Type: text/html; charset=utf-8\nDate: Fri, 30 Oct 2020 14:32:46 GMT\nReferrer-Policy: same-origin\nServer: WSGIServer/0.2 CPython/3.7.5\nX-Content-Type-Options: nosniff\nX-Frame-Options: DENY"
},
{
"code": null,
"e": 9567,
"s": 9469,
"text": "We use POST requests to create a task. The HTTPUtilityPie command to create a new ask as follows."
},
{
"code": null,
"e": 9821,
"s": 9567,
"text": "http POST :8000/taskmanagement/ task_name=”Document XYZ” task_desc=”Document Description” category=”Writing” priority=”Low” created_date=”2020-10-30 00:00:00.000000+00:00′′ deadline=”2020-11-03 00:00:00.000000+00:00′′ status=”Pending” payment_done=false"
},
{
"code": null,
"e": 10054,
"s": 9821,
"text": "Here the URL request (http POST :8000/taskmanagement/ ) matches the regular expression (taskmanagement/$). Hence, it calls the function task_list, and the POST verb satisfies the condition to execute the code for the task creation. "
},
{
"code": null,
"e": 10062,
"s": 10054,
"text": "Output:"
},
{
"code": null,
"e": 10096,
"s": 10062,
"text": "POST Request using HTTPUtilityPie"
},
{
"code": null,
"e": 10195,
"s": 10096,
"text": "Let’s create another instance using the curl command. The curl command for POST request as follows"
},
{
"code": null,
"e": 10541,
"s": 10195,
"text": "curl -iX POST -H “Content-Type: application/json” -d “{\\”task_name\\”:\\”Task 01\\”, \\”task_desc\\”:\\”Desc 01\\”, \\”category\\”:\\”Writing\\”, \\”priority\\”:\\”Medium\\”, \\”created_date\\”:\\”2020-10-27 13:02:20.890678\\”, \\”deadline\\”:\\”2020-10-29 00:00:00.000000+00:00\\”, \\”status\\”:\\”Completed\\”, \\”payment_done\\”: \\”true\\”}” localhost:8000/taskmanagement/"
},
{
"code": null,
"e": 10549,
"s": 10541,
"text": "Output:"
},
{
"code": null,
"e": 10573,
"s": 10549,
"text": "POST Request using curl"
},
{
"code": null,
"e": 10731,
"s": 10573,
"text": "Here the data required to create a new task is specified after -d and the usage of -H “Content-Type: application/json” signifies the data is in JSON format. "
},
{
"code": null,
"e": 10733,
"s": 10731,
"text": "{"
},
{
"code": null,
"e": 10963,
"s": 10733,
"text": "“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-10-27 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”"
},
{
"code": null,
"e": 10965,
"s": 10963,
"text": "}"
},
{
"code": null,
"e": 11262,
"s": 10965,
"text": "We make use of PUT request to update an existing task. Here we pass the id of the task that needs to be updated along with the URL. Since the URL has a parameter, Django sends the URL instance to the task_detail function in views. And, executes the code that holds the condition for the PUT verb."
},
{
"code": null,
"e": 11309,
"s": 11262,
"text": "The HTTPie utility command to update the task:"
},
{
"code": null,
"e": 11599,
"s": 11309,
"text": "http PUT :8000/taskmanagement/1 task_name=”Swap two elements” task_desc=”Write a Python program to swap two elements in a list” category=”Writing” priority=”Medium” created_date=”2020-10-27 13:02:20.890678′′ deadline=”2020-10-29 00:00:00.000000+00:00′′ status=”Completed” payment_done=true"
},
{
"code": null,
"e": 11607,
"s": 11599,
"text": "Output:"
},
{
"code": null,
"e": 11611,
"s": 11607,
"text": "PUT"
},
{
"code": null,
"e": 11650,
"s": 11611,
"text": "The equivalent CURL command as follows"
},
{
"code": null,
"e": 12052,
"s": 11650,
"text": "curl -iX PUT -H “Content-Type: application/json” -d “{\\”task_name\\”:\\”Swap two elements\\”, \\”task_desc\\”:\\”Write a Python program to swap two elements in a list\\”, \\”category\\”:\\”Writing\\”, \\”priority\\”:\\”Medium\\”, \\”created_date\\”:\\”2020-10-27 13:02:20.890678\\”, \\”deadline\\”:\\”2020-10-29 00:00:00.000000+00:00\\”, \\”status\\”:\\”Completed\\”, \\”payment_done\\”: \\”true\\”}” localhost:8000/taskmanagement/1"
},
{
"code": null,
"e": 12173,
"s": 12052,
"text": "The HTTP DELETE Request is used to delete a particular task from the database. Let’s look at the HTTPie utility command."
},
{
"code": null,
"e": 12208,
"s": 12173,
"text": "http DELETE :8000/taskmanagement/4"
},
{
"code": null,
"e": 12216,
"s": 12208,
"text": "Output:"
},
{
"code": null,
"e": 12231,
"s": 12216,
"text": "Delete Request"
},
{
"code": null,
"e": 12271,
"s": 12231,
"text": "The equivalent curl command as follows:"
},
{
"code": null,
"e": 12319,
"s": 12271,
"text": "curl -iX DELETE localhost:8000/taskmanagement/4"
},
{
"code": null,
"e": 12630,
"s": 12319,
"text": "So far, we took advantage of command-line tools to compose and send HTTP requests. Now, we will make use of Postman. Postman REST client is a Graphical User Interface (GUI) tool that facilitates composing and sending HTTP requests to the Django development server. Let’s compose and send GET and POST requests."
},
{
"code": null,
"e": 12883,
"s": 12630,
"text": "You can select GET in the drop-down menu, type the URL (localhost:8000/taskmanagement/) in the URL field, and hit the Send button. The Postman will display the information in the output Body section. The below screenshot shows the JSON output response."
},
{
"code": null,
"e": 12914,
"s": 12883,
"text": "HTTP GET request using Postman"
},
{
"code": null,
"e": 13001,
"s": 12914,
"text": "You can click the Header tab to view the header details. Sharing the screenshot below:"
},
{
"code": null,
"e": 13008,
"s": 13001,
"text": "Header"
},
{
"code": null,
"e": 13090,
"s": 13008,
"text": "Now let’s send a POST request using the Postman GUI tool. Follow the below steps:"
},
{
"code": null,
"e": 13660,
"s": 13090,
"text": "Select the POST verb from the drop-down menu,Type the URL in the URL field (localhost:8000/taskmanagement/)Select the Body section (in the input section)Check the raw radio button and also select JSON in the dropdown menu on the right side of the GraphQL buttonEnter the following lines {“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-11-02 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”} in the body (input section). and hit send."
},
{
"code": null,
"e": 13706,
"s": 13660,
"text": "Select the POST verb from the drop-down menu,"
},
{
"code": null,
"e": 13769,
"s": 13706,
"text": "Type the URL in the URL field (localhost:8000/taskmanagement/)"
},
{
"code": null,
"e": 13816,
"s": 13769,
"text": "Select the Body section (in the input section)"
},
{
"code": null,
"e": 13925,
"s": 13816,
"text": "Check the raw radio button and also select JSON in the dropdown menu on the right side of the GraphQL button"
},
{
"code": null,
"e": 14234,
"s": 13925,
"text": "Enter the following lines {“task_name”:”Task 01′′, “task_desc”:”Desc 01′′, “category”:”Writing”, “priority”:”Medium”, “created_date”:”2020-11-02 13:02:20.890678′′, “deadline”:”2020-10-29 00:00:00.000000+00:00′′, “status”:”Completed”, “payment_done”: “true”} in the body (input section). and hit send."
},
{
"code": null,
"e": 14264,
"s": 14234,
"text": "Sharing the screenshot below."
},
{
"code": null,
"e": 14574,
"s": 14264,
"text": "In this article, we created a Django API view for HTTP requests to interact with the SQLite database through the RESTFul web service. We worked with GET, POST, PUT, and DELETE HTTP verbs. We have seen how to send and compose HTTP requests using command-line tools (curl and HTTPie) and the GUI tool (POSTMAN)."
},
{
"code": null,
"e": 14586,
"s": 14574,
"text": "Django-REST"
},
{
"code": null,
"e": 14600,
"s": 14586,
"text": "Python Django"
},
{
"code": null,
"e": 14607,
"s": 14600,
"text": "Python"
}
]
|
Count of Prime Nodes of a Singly Linked List - GeeksforGeeks | 29 Oct, 2021
Given a singly linked list containing N nodes, the task is to find the total count of prime numbers.
Examples:
Input: List = 15 -> 5 -> 6 -> 10 -> 17
Output: 2
5 and 17 are the prime nodes
Input: List = 29 -> 3 -> 4 -> 2 -> 9
Output: 3
2, 3 and 29 are the prime nodes
Approach: The idea is to traverse the linked list to the end and check if the current node is prime or not. If YES, increment the count by 1 and keep doing the same until all the nodes get traversed.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find count of prime numbers// in the singly linked list#include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node { int data; Node* next;}; // Function to insert a node at the beginning// of the singly Linked Listvoid push(Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to check if a number is primebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked listint countPrime(Node** head_ref){ int count = 0; Node* ptr = *head_ref; while (ptr != NULL) { // If current node is prime if (isPrime(ptr->data)) { // Update count count++; } ptr = ptr->next; } return count;} // Driver programint main(){ // start with the empty list Node* head = NULL; // create the linked list // 15 -> 5 -> 6 -> 10 -> 17 push(&head, 17); push(&head, 10); push(&head, 6); push(&head, 5); push(&head, 15); // Function call to print require answer cout << "Count of prime nodes = " << countPrime(&head); return 0;}
// Java implementation to find count of prime numbers// in the singly linked listclass solution{ // Node of the singly linked liststatic class Node { int data; Node next;} // Function to insert a node at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = ( head_ref); ( head_ref) = new_node; return head_ref;} // Function to check if a number is primestatic boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked liststatic int countPrime(Node head_ref){ int count = 0; Node ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver programpublic static void main(String args[]){ // start with the empty list Node head = null; // create the linked list // 15 . 5 . 6 . 10 . 17 head=push(head, 17); head=push(head, 10); head=push(head, 6); head=push(head, 5); head=push(head, 15); // Function call to print require answer System.out.print( "Count of prime nodes = "+ countPrime(head)); }} // This code is contributed by Arnab Kundu
# Python3 implementation to find count of# prime numbers in the singly linked list # Function to check if a number is primedef isPrime(n): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that we can skip # middle five numbers in below loop if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to find count of prime # nodes in a linked list def countPrime(self): count = 0 ptr = self.head while ptr != None: # If current node is prime if isPrime(ptr.data): # Update count count += 1 ptr = ptr.next return count # Driver Codeif __name__ == "__main__": # Start with the empty list linkedlist = LinkedList() # create the linked list # 15 -> 5 -> 6 -> 10 -> 17 linkedlist.push(17) linkedlist.push(10) linkedlist.push(6) linkedlist.push(5) linkedlist.push(15) # Function call to print require answer print("Count of prime nodes =", linkedlist.countPrime()) # This code is contributed by Rituraj Jain
// C# implementation to find count of prime numbers// in the singly linked listusing System; class GFG{ // Node of the singly linked listpublic class Node{ public int data; public Node next;} // Function to insert a node at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = ( head_ref); ( head_ref) = new_node; return head_ref;} // Function to check if a number is primestatic bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked liststatic int countPrime(Node head_ref){ int count = 0; Node ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the linked list // 15 . 5 . 6 . 10 . 17 head=push(head, 17); head=push(head, 10); head=push(head, 6); head=push(head, 5); head=push(head, 15); // Function call to print require answer Console.Write( "Count of prime nodes = "+ countPrime(head));}} // This code has been contributed by 29AjayKumar
<script> // Javascript implementation to find count// of prime numbers in the singly linked list // Node of the singly linked listclass Node{ constructor(val) { this.data = val; this.next = null; }} // Function to insert a node at the beginning// of the singly Linked Listfunction push(head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to check if a number is primefunction isPrime(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked listfunction countPrime(head_ref){ var count = 0; var ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver code // Start with the empty listvar head = null; // Create the linked list// 15 . 5 . 6 . 10 . 17head = push(head, 17);head = push(head, 10);head = push(head, 6);head = push(head, 5);head = push(head, 15); // Function call to print require answerdocument.write("Count of prime nodes = " + countPrime(head)); // This code is contributed by gauravrajput1 </script>
Count of prime nodes = 2
Time Complexity: O(N*sqrt(P)), where N is length of the LinkedList and P is the maximum element in the List
andrew1234
rahul_gfg
rituraj_jain
29AjayKumar
GauravRajput1
ankita_saini
Prime Number
sieve
Linked List
Mathematical
Linked List
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
LinkedList in Java
Doubly Linked List | Set 1 (Introduction and Insertion)
Linked List vs Array
Delete a Linked List node at a given position
Queue - Linked List Implementation
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": 24770,
"s": 24742,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 24871,
"s": 24770,
"text": "Given a singly linked list containing N nodes, the task is to find the total count of prime numbers."
},
{
"code": null,
"e": 24882,
"s": 24871,
"text": "Examples: "
},
{
"code": null,
"e": 25042,
"s": 24882,
"text": "Input: List = 15 -> 5 -> 6 -> 10 -> 17\nOutput: 2\n5 and 17 are the prime nodes\n\nInput: List = 29 -> 3 -> 4 -> 2 -> 9\nOutput: 3\n2, 3 and 29 are the prime nodes\n "
},
{
"code": null,
"e": 25243,
"s": 25042,
"text": "Approach: The idea is to traverse the linked list to the end and check if the current node is prime or not. If YES, increment the count by 1 and keep doing the same until all the nodes get traversed. "
},
{
"code": null,
"e": 25292,
"s": 25243,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 25296,
"s": 25292,
"text": "C++"
},
{
"code": null,
"e": 25301,
"s": 25296,
"text": "Java"
},
{
"code": null,
"e": 25309,
"s": 25301,
"text": "Python3"
},
{
"code": null,
"e": 25312,
"s": 25309,
"text": "C#"
},
{
"code": null,
"e": 25323,
"s": 25312,
"text": "Javascript"
},
{
"code": "// C++ implementation to find count of prime numbers// in the singly linked list#include <bits/stdc++.h>using namespace std; // Node of the singly linked liststruct Node { int data; Node* next;}; // Function to insert a node at the beginning// of the singly Linked Listvoid push(Node** head_ref, int new_data){ Node* new_node = new Node; new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Function to check if a number is primebool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked listint countPrime(Node** head_ref){ int count = 0; Node* ptr = *head_ref; while (ptr != NULL) { // If current node is prime if (isPrime(ptr->data)) { // Update count count++; } ptr = ptr->next; } return count;} // Driver programint main(){ // start with the empty list Node* head = NULL; // create the linked list // 15 -> 5 -> 6 -> 10 -> 17 push(&head, 17); push(&head, 10); push(&head, 6); push(&head, 5); push(&head, 15); // Function call to print require answer cout << \"Count of prime nodes = \" << countPrime(&head); return 0;}",
"e": 26882,
"s": 25323,
"text": null
},
{
"code": "// Java implementation to find count of prime numbers// in the singly linked listclass solution{ // Node of the singly linked liststatic class Node { int data; Node next;} // Function to insert a node at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = ( head_ref); ( head_ref) = new_node; return head_ref;} // Function to check if a number is primestatic boolean isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked liststatic int countPrime(Node head_ref){ int count = 0; Node ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver programpublic static void main(String args[]){ // start with the empty list Node head = null; // create the linked list // 15 . 5 . 6 . 10 . 17 head=push(head, 17); head=push(head, 10); head=push(head, 6); head=push(head, 5); head=push(head, 15); // Function call to print require answer System.out.print( \"Count of prime nodes = \"+ countPrime(head)); }} // This code is contributed by Arnab Kundu",
"e": 28535,
"s": 26882,
"text": null
},
{
"code": "# Python3 implementation to find count of# prime numbers in the singly linked list # Function to check if a number is primedef isPrime(n): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that we can skip # middle five numbers in below loop if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True # Link list nodeclass Node: def __init__(self, data, next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None # Push a new node on the front of the list. def push(self, new_data): new_node = Node(new_data, self.head) self.head = new_node # Function to find count of prime # nodes in a linked list def countPrime(self): count = 0 ptr = self.head while ptr != None: # If current node is prime if isPrime(ptr.data): # Update count count += 1 ptr = ptr.next return count # Driver Codeif __name__ == \"__main__\": # Start with the empty list linkedlist = LinkedList() # create the linked list # 15 -> 5 -> 6 -> 10 -> 17 linkedlist.push(17) linkedlist.push(10) linkedlist.push(6) linkedlist.push(5) linkedlist.push(15) # Function call to print require answer print(\"Count of prime nodes =\", linkedlist.countPrime()) # This code is contributed by Rituraj Jain",
"e": 30193,
"s": 28535,
"text": null
},
{
"code": "// C# implementation to find count of prime numbers// in the singly linked listusing System; class GFG{ // Node of the singly linked listpublic class Node{ public int data; public Node next;} // Function to insert a node at the beginning// of the singly Linked Liststatic Node push(Node head_ref, int new_data){ Node new_node = new Node(); new_node.data = new_data; new_node.next = ( head_ref); ( head_ref) = new_node; return head_ref;} // Function to check if a number is primestatic bool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked liststatic int countPrime(Node head_ref){ int count = 0; Node ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the linked list // 15 . 5 . 6 . 10 . 17 head=push(head, 17); head=push(head, 10); head=push(head, 6); head=push(head, 5); head=push(head, 15); // Function call to print require answer Console.Write( \"Count of prime nodes = \"+ countPrime(head));}} // This code has been contributed by 29AjayKumar",
"e": 31863,
"s": 30193,
"text": null
},
{
"code": "<script> // Javascript implementation to find count// of prime numbers in the singly linked list // Node of the singly linked listclass Node{ constructor(val) { this.data = val; this.next = null; }} // Function to insert a node at the beginning// of the singly Linked Listfunction push(head_ref, new_data){ var new_node = new Node(); new_node.data = new_data; new_node.next = (head_ref); (head_ref) = new_node; return head_ref;} // Function to check if a number is primefunction isPrime(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for(i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true;} // Function to find count of prime// nodes in a linked listfunction countPrime(head_ref){ var count = 0; var ptr = head_ref; while (ptr != null) { // If current node is prime if (isPrime(ptr.data)) { // Update count count++; } ptr = ptr.next; } return count;} // Driver code // Start with the empty listvar head = null; // Create the linked list// 15 . 5 . 6 . 10 . 17head = push(head, 17);head = push(head, 10);head = push(head, 6);head = push(head, 5);head = push(head, 15); // Function call to print require answerdocument.write(\"Count of prime nodes = \" + countPrime(head)); // This code is contributed by gauravrajput1 </script>",
"e": 33503,
"s": 31863,
"text": null
},
{
"code": null,
"e": 33528,
"s": 33503,
"text": "Count of prime nodes = 2"
},
{
"code": null,
"e": 33639,
"s": 33530,
"text": "Time Complexity: O(N*sqrt(P)), where N is length of the LinkedList and P is the maximum element in the List "
},
{
"code": null,
"e": 33650,
"s": 33639,
"text": "andrew1234"
},
{
"code": null,
"e": 33660,
"s": 33650,
"text": "rahul_gfg"
},
{
"code": null,
"e": 33673,
"s": 33660,
"text": "rituraj_jain"
},
{
"code": null,
"e": 33685,
"s": 33673,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33699,
"s": 33685,
"text": "GauravRajput1"
},
{
"code": null,
"e": 33712,
"s": 33699,
"text": "ankita_saini"
},
{
"code": null,
"e": 33725,
"s": 33712,
"text": "Prime Number"
},
{
"code": null,
"e": 33731,
"s": 33725,
"text": "sieve"
},
{
"code": null,
"e": 33743,
"s": 33731,
"text": "Linked List"
},
{
"code": null,
"e": 33756,
"s": 33743,
"text": "Mathematical"
},
{
"code": null,
"e": 33768,
"s": 33756,
"text": "Linked List"
},
{
"code": null,
"e": 33781,
"s": 33768,
"text": "Mathematical"
},
{
"code": null,
"e": 33794,
"s": 33781,
"text": "Prime Number"
},
{
"code": null,
"e": 33800,
"s": 33794,
"text": "sieve"
},
{
"code": null,
"e": 33898,
"s": 33800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33907,
"s": 33898,
"text": "Comments"
},
{
"code": null,
"e": 33920,
"s": 33907,
"text": "Old Comments"
},
{
"code": null,
"e": 33939,
"s": 33920,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 33995,
"s": 33939,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 34016,
"s": 33995,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 34062,
"s": 34016,
"text": "Delete a Linked List node at a given position"
},
{
"code": null,
"e": 34097,
"s": 34062,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 34127,
"s": 34097,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 34187,
"s": 34127,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34202,
"s": 34187,
"text": "C++ Data Types"
},
{
"code": null,
"e": 34245,
"s": 34202,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
How to set “value” to input web element using selenium? | We can set value to input webelement using Selenium webdriver. We can take the help of the sendKeys method to enter text to the input field. The value to be entered is passed as an argument to the method.
driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");
We can also perform web operations like entering text to the edit box with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.value='<value to be entered>' and webelement as arguments to the method.
WebElement i = driver.findElement(By.id("id"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", i);
Code Implementation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
public class SetValue{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
l.sendKeys("Selenium");
// obtain the value entered with getAttribute method
System.out.println("Value entered is: " +l.getAttribute("value"));
driver.close();
}
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetValueJS{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
// Javascript Executor class with executeScript method
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", l);
System.out.println("Value entered is: " +l.getAttribute("value"));
driver.close();
}
} | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "We can set value to input webelement using Selenium webdriver. We can take the help of the sendKeys method to enter text to the input field. The value to be entered is passed as an argument to the method."
},
{
"code": null,
"e": 1332,
"s": 1267,
"text": "driver.findElement(By.id(\"txtSearchText\")).sendKeys(\"Selenium\");"
},
{
"code": null,
"e": 1575,
"s": 1332,
"text": "We can also perform web operations like entering text to the edit box with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.value='<value to be entered>' and webelement as arguments to the method."
},
{
"code": null,
"e": 1728,
"s": 1575,
"text": "WebElement i = driver.findElement(By.id(\"id\"));\nJavascriptExecutor j = (JavascriptExecutor)driver;\nj.executeScript(\"arguments[0].value='Selenium';\", i);"
},
{
"code": null,
"e": 1748,
"s": 1728,
"text": "Code Implementation"
},
{
"code": null,
"e": 2599,
"s": 1748,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport java.util.concurrent.TimeUnit;\npublic class SetValue{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement l=driver.findElement(By.cssSelector(\"input[id*='id']\"));\n l.sendKeys(\"Selenium\");\n // obtain the value entered with getAttribute method\n System.out.println(\"Value entered is: \" +l.getAttribute(\"value\"));\n driver.close();\n }\n}"
},
{
"code": null,
"e": 2645,
"s": 2599,
"text": "Code Implementation with Javascript Executor."
},
{
"code": null,
"e": 3634,
"s": 2645,
"text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.By;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class SetValueJS{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n driver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\");\n // identify element\n WebElement l=driver.findElement(By.cssSelector(\"input[id*='id']\"));\n // Javascript Executor class with executeScript method\n JavascriptExecutor j = (JavascriptExecutor)driver;\n j.executeScript(\"arguments[0].value='Selenium';\", l);\n System.out.println(\"Value entered is: \" +l.getAttribute(\"value\"));\n driver.close();\n }\n}"
}
]
|
How to find an element using the attribute “id” in Selenium? | We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@id='value']. Then, we have to use the method By.xpath to locate it. To locate an element with locator id, we have to use the By.id method.
Let us look at the html code of an element with id attribute −
WebElement e = driver. findElement(By.id("session_key"));
WebElement m = driver. findElement(By.xpath("//input[@id=' session_key']"));
WebElement n =
driver. findElement(By.cssSelector("input[id=' session_key']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorId{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.linkedin.com/");
// identify element with Id
WebElement l = driver.findElement(By.id("session_key"));
l.sendKeys("Java");
//identify element with css
WebElement m = driver.
findElement(By.cssSelector("input[id='session_key']"));
String s = m.getAttribute("value");
System.out.println("Attribute value: " + s);
//identify element with xpath
WebElement n = driver.
findElement(By.xpath("//input[@id='session_key']"));
n.clear();
driver.quit();
}
} | [
{
"code": null,
"e": 1296,
"s": 1062,
"text": "We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By.cssSelector."
},
{
"code": null,
"e": 1507,
"s": 1296,
"text": "To identify the element with xpath, the expression should be //tagname[@id='value']. Then, we have to use the method By.xpath to locate it. To locate an element with locator id, we have to use the By.id method."
},
{
"code": null,
"e": 1570,
"s": 1507,
"text": "Let us look at the html code of an element with id attribute −"
},
{
"code": null,
"e": 1785,
"s": 1570,
"text": "WebElement e = driver. findElement(By.id(\"session_key\"));\nWebElement m = driver. findElement(By.xpath(\"//input[@id=' session_key']\"));\nWebElement n =\ndriver. findElement(By.cssSelector(\"input[id=' session_key']\"));"
},
{
"code": null,
"e": 2869,
"s": 1785,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class LocatorId{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.linkedin.com/\");\n // identify element with Id\n WebElement l = driver.findElement(By.id(\"session_key\"));\n l.sendKeys(\"Java\");\n //identify element with css\n WebElement m = driver.\n findElement(By.cssSelector(\"input[id='session_key']\"));\n String s = m.getAttribute(\"value\");\n System.out.println(\"Attribute value: \" + s);\n //identify element with xpath\n WebElement n = driver.\n findElement(By.xpath(\"//input[@id='session_key']\"));\n n.clear();\n driver.quit();\n }\n}"
}
]
|
How to create a borderless fullscreen application using Python-3 Tkinter? | In order to make a Tkinter window borderless and full-screen, we can use the utility method attributes(‘-fullscreen’, True). Tkinter windows can be configured using functions and methods defined in the Tkinter library.
Another similar method Tkinter provides to make the application window full-screen is, overrideredirect(True). This method can be invoked only if the application needs to resize in its defined width and height only.
#Import the required Libraries
from tkinter import *
#Create an instance of Tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x250")
#Full Screen Window
win.attributes('-fullscreen', True)
def quit_win():
win.destroy()
#Create a Quit Button
button=Button(win,text="Quit", font=('Comic Sans', 13, 'bold'), command= quit_win)
button.pack(pady=20)
win.mainloop()
Running the above code will display a full-screen window.
Click the "Quit" button to close the full-screen window. | [
{
"code": null,
"e": 1281,
"s": 1062,
"text": "In order to make a Tkinter window borderless and full-screen, we can use the utility method attributes(‘-fullscreen’, True). Tkinter windows can be configured using functions and methods defined in the Tkinter library."
},
{
"code": null,
"e": 1497,
"s": 1281,
"text": "Another similar method Tkinter provides to make the application window full-screen is, overrideredirect(True). This method can be invoked only if the application needs to resize in its defined width and height only."
},
{
"code": null,
"e": 1869,
"s": 1497,
"text": "#Import the required Libraries\nfrom tkinter import *\n#Create an instance of Tkinter frame\nwin= Tk()\n#Set the Geometry\nwin.geometry(\"750x250\")\n#Full Screen Window\nwin.attributes('-fullscreen', True)\ndef quit_win():\n win.destroy()\n#Create a Quit Button\nbutton=Button(win,text=\"Quit\", font=('Comic Sans', 13, 'bold'), command= quit_win)\nbutton.pack(pady=20)\nwin.mainloop()"
},
{
"code": null,
"e": 1927,
"s": 1869,
"text": "Running the above code will display a full-screen window."
},
{
"code": null,
"e": 1984,
"s": 1927,
"text": "Click the \"Quit\" button to close the full-screen window."
}
]
|
D3.js axis.tickFormat() Function - GeeksforGeeks | 05 Aug, 2020
The d3.axis.tickFormat() Function in D3.js is used to control which ticks are labelled. This function is used to implement your own tick format function.
Syntax:
axis.tickFormat([format])
Parameters: This function accepts the following parameter.
format: These parameters are format to set the tick format function.
Return Value: This function returns the currently set tick format function, which defaults to null.
Below programs illustrate the d3.axis.tickFormat() function in D3.js:
Example 1:
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickFormat() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft().scale(yscale) .tickValues([0, .2, .5, .70, 1]) .tickFormat((d, i) => ['a', 'e', 'i', 'o', 'u'][i]); svg.append("g") .attr("transform", "translate(100, 20)") .call(y_axis) </script></body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickFormat() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 600, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 100]); var x_axis = d3.axisBottom(xscale).ticks(4) .tickFormat(x => `(${x.toFixed(1)})`); var xAxisTranslate = height / 2; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate + ")") .call(x_axis) </script> </body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 24890,
"s": 24862,
"text": "\n05 Aug, 2020"
},
{
"code": null,
"e": 25044,
"s": 24890,
"text": "The d3.axis.tickFormat() Function in D3.js is used to control which ticks are labelled. This function is used to implement your own tick format function."
},
{
"code": null,
"e": 25052,
"s": 25044,
"text": "Syntax:"
},
{
"code": null,
"e": 25078,
"s": 25052,
"text": "axis.tickFormat([format])"
},
{
"code": null,
"e": 25137,
"s": 25078,
"text": "Parameters: This function accepts the following parameter."
},
{
"code": null,
"e": 25206,
"s": 25137,
"text": "format: These parameters are format to set the tick format function."
},
{
"code": null,
"e": 25306,
"s": 25206,
"text": "Return Value: This function returns the currently set tick format function, which defaults to null."
},
{
"code": null,
"e": 25376,
"s": 25306,
"text": "Below programs illustrate the d3.axis.tickFormat() function in D3.js:"
},
{
"code": null,
"e": 25387,
"s": 25376,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickFormat() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft().scale(yscale) .tickValues([0, .2, .5, .70, 1]) .tickFormat((d, i) => ['a', 'e', 'i', 'o', 'u'][i]); svg.append(\"g\") .attr(\"transform\", \"translate(100, 20)\") .call(y_axis) </script></body> </html>",
"e": 26332,
"s": 25387,
"text": null
},
{
"code": null,
"e": 26340,
"s": 26332,
"text": "Output:"
},
{
"code": null,
"e": 26351,
"s": 26340,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.tickFormat() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 600, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 100]); var x_axis = d3.axisBottom(xscale).ticks(4) .tickFormat(x => `(${x.toFixed(1)})`); var xAxisTranslate = height / 2; svg.append(\"g\") .attr(\"transform\", \"translate(50, \" + xAxisTranslate + \")\") .call(x_axis) </script> </body> </html>",
"e": 27319,
"s": 26351,
"text": null
},
{
"code": null,
"e": 27327,
"s": 27319,
"text": "Output:"
},
{
"code": null,
"e": 27333,
"s": 27327,
"text": "D3.js"
},
{
"code": null,
"e": 27344,
"s": 27333,
"text": "JavaScript"
},
{
"code": null,
"e": 27361,
"s": 27344,
"text": "Web Technologies"
},
{
"code": null,
"e": 27459,
"s": 27361,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27504,
"s": 27459,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27565,
"s": 27504,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27637,
"s": 27565,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27678,
"s": 27637,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27718,
"s": 27678,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27760,
"s": 27718,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27793,
"s": 27760,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27855,
"s": 27793,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27898,
"s": 27855,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
C - Loops | You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
C programming language provides the following types of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
It is more like a while statement, except that it tests the condition at the end of the loop body.
You can use one or more loops inside any other while, for, or do..while loop.
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Transfers control to the labeled statement.
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2319,
"s": 2084,
"text": "You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on."
},
{
"code": null,
"e": 2425,
"s": 2319,
"text": "Programming languages provide various control structures that allow for more complicated execution paths."
},
{
"code": null,
"e": 2605,
"s": 2425,
"text": "A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −"
},
{
"code": null,
"e": 2698,
"s": 2605,
"text": "C programming language provides the following types of loops to handle looping requirements."
},
{
"code": null,
"e": 2829,
"s": 2698,
"text": "Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body."
},
{
"code": null,
"e": 2935,
"s": 2829,
"text": "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 3034,
"s": 2935,
"text": "It is more like a while statement, except that it tests the condition at the end of the loop body."
},
{
"code": null,
"e": 3112,
"s": 3034,
"text": "You can use one or more loops inside any other while, for, or do..while loop."
},
{
"code": null,
"e": 3279,
"s": 3112,
"text": "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed."
},
{
"code": null,
"e": 3324,
"s": 3279,
"text": "C supports the following control statements."
},
{
"code": null,
"e": 3447,
"s": 3324,
"text": "Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch."
},
{
"code": null,
"e": 3556,
"s": 3447,
"text": "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating."
},
{
"code": null,
"e": 3600,
"s": 3556,
"text": "Transfers control to the labeled statement."
},
{
"code": null,
"e": 3870,
"s": 3600,
"text": "A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty."
},
{
"code": null,
"e": 3990,
"s": 3870,
"text": "#include <stdio.h>\n \nint main () {\n\n for( ; ; ) {\n printf(\"This loop will run forever.\\n\");\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 4203,
"s": 3990,
"text": "When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop."
},
{
"code": null,
"e": 4272,
"s": 4203,
"text": "NOTE − You can terminate an infinite loop by pressing Ctrl + C keys."
},
{
"code": null,
"e": 4279,
"s": 4272,
"text": " Print"
},
{
"code": null,
"e": 4290,
"s": 4279,
"text": " Add Notes"
}
]
|
How to avoid binding by using arrow functions in callbacks in ReactJS? - GeeksforGeeks | 18 Feb, 2022
In React class-based components when we use event handler callbacks, it is very important to give special attention to the ‘this’ keyword. In these cases the context this is undefined when the callback function actually gets invoked that’s why we have to bind the context of this. Now if binding all the methods of each class is very annoying. Instead of binding we can use the inline arrow function since the arrow function does not have its own value of this, it uses the parent or public value. Using the inline arrow function we can get rid of annoying method binding every time and also the code looks very packed and organized.
Example 1: This example illustrates how to use arrow functions in callbacks
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js :
Javascript
import React, { Component } from 'react' class App extends Component { // Default props static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } constructor(props){ super(props) // Set initial state this.state = {msg : 'React Course', content:''} } // Return an unordered list of contents renderContent(){ return ( <ul> {/* map over all the contents and return some JSX for each */} {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } render(){ const button = !this.state.content && <button // Arrow function in callback onClick={() => { // Update state this.setState({ msg : 'Course Content', content : this.renderContent() }) }} > Click here to know contents! </button> return ( <div> <p>{this.state.msg}</p> <p>{this.state.content}</p> {button} </div> ) }} export default App
Output :
Example 2 :
index.js :
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
App.js :
Javascript
import React, { Component } from 'react' class App extends Component{ // Default props static defaultProps = { name : ['John', 'Alex', 'Bob'] } constructor(props){ super(props) // Nnitialize count state this.state = {msg : 'Hi There', count:0} } render(){ return( <div> <h3>Greetings!</h3> <p>{this.state.msg}</p> <button // Arrow function in callback // does not required explicit binding onClick={() => { this.setState(st => ( st.msg = `${st.msg}, ${this.props.name[st.count]}`, st.count += 1 )) }} > Say greeting to employees! </button> </div> ) }}export default App
Output :
rkbhola5
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ? | [
{
"code": null,
"e": 27142,
"s": 27114,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 27776,
"s": 27142,
"text": "In React class-based components when we use event handler callbacks, it is very important to give special attention to the ‘this’ keyword. In these cases the context this is undefined when the callback function actually gets invoked that’s why we have to bind the context of this. Now if binding all the methods of each class is very annoying. Instead of binding we can use the inline arrow function since the arrow function does not have its own value of this, it uses the parent or public value. Using the inline arrow function we can get rid of annoying method binding every time and also the code looks very packed and organized."
},
{
"code": null,
"e": 27852,
"s": 27776,
"text": "Example 1: This example illustrates how to use arrow functions in callbacks"
},
{
"code": null,
"e": 27862,
"s": 27852,
"text": "index.js:"
},
{
"code": null,
"e": 27875,
"s": 27864,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 28014,
"s": 27875,
"text": null
},
{
"code": null,
"e": 28026,
"s": 28016,
"text": "App.js : "
},
{
"code": null,
"e": 28039,
"s": 28028,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react' class App extends Component { // Default props static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } constructor(props){ super(props) // Set initial state this.state = {msg : 'React Course', content:''} } // Return an unordered list of contents renderContent(){ return ( <ul> {/* map over all the contents and return some JSX for each */} {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } render(){ const button = !this.state.content && <button // Arrow function in callback onClick={() => { // Update state this.setState({ msg : 'Course Content', content : this.renderContent() }) }} > Click here to know contents! </button> return ( <div> <p>{this.state.msg}</p> <p>{this.state.content}</p> {button} </div> ) }} export default App",
"e": 29202,
"s": 28039,
"text": null
},
{
"code": null,
"e": 29213,
"s": 29204,
"text": "Output :"
},
{
"code": null,
"e": 29225,
"s": 29213,
"text": "Example 2 :"
},
{
"code": null,
"e": 29237,
"s": 29225,
"text": "index.js : "
},
{
"code": null,
"e": 29250,
"s": 29239,
"text": "Javascript"
},
{
"code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))",
"e": 29389,
"s": 29250,
"text": null
},
{
"code": null,
"e": 29401,
"s": 29391,
"text": "App.js : "
},
{
"code": null,
"e": 29414,
"s": 29403,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react' class App extends Component{ // Default props static defaultProps = { name : ['John', 'Alex', 'Bob'] } constructor(props){ super(props) // Nnitialize count state this.state = {msg : 'Hi There', count:0} } render(){ return( <div> <h3>Greetings!</h3> <p>{this.state.msg}</p> <button // Arrow function in callback // does not required explicit binding onClick={() => { this.setState(st => ( st.msg = `${st.msg}, ${this.props.name[st.count]}`, st.count += 1 )) }} > Say greeting to employees! </button> </div> ) }}export default App",
"e": 30160,
"s": 29414,
"text": null
},
{
"code": null,
"e": 30171,
"s": 30162,
"text": "Output :"
},
{
"code": null,
"e": 30180,
"s": 30171,
"text": "rkbhola5"
},
{
"code": null,
"e": 30189,
"s": 30180,
"text": "react-js"
},
{
"code": null,
"e": 30206,
"s": 30189,
"text": "Web Technologies"
},
{
"code": null,
"e": 30304,
"s": 30206,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30346,
"s": 30304,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30379,
"s": 30346,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30422,
"s": 30379,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30484,
"s": 30422,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30534,
"s": 30484,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30579,
"s": 30534,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30640,
"s": 30579,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30709,
"s": 30640,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 30767,
"s": 30709,
"text": "How to create footer to stay at the bottom of a Web page?"
}
]
|
Odd even sort in an array - JavaScript | We are required to write a JavaScript function that takes in an array of numbers and sorts the array such that first all the even numbers appear in ascending order and then all the odd numbers appear in ascending order.
For example: If the input array is −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
Then the output should be −
const output = [2, 2, 6, 8, 1, 5, 7, 9];
Following is the code −
const arr = [2, 5, 2, 6, 7, 1, 8, 9];
const isEven = num => num % 2 === 0;
const sorter = ((a, b) => {
if(isEven(a) && !isEven(b)){
return -1;
};
if(!isEven(a) && isEven(b)){
return 1;
};
return a - b;
});
const oddEvenSort = arr => {
arr.sort(sorter);
};
oddEvenSort(arr);
console.log(arr);
Following is the output in the console −
[
2, 2, 6, 8,
1, 5, 7, 9
] | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of numbers and sorts the array such that first all the even numbers appear in ascending order and then all the odd numbers appear in ascending order."
},
{
"code": null,
"e": 1319,
"s": 1282,
"text": "For example: If the input array is −"
},
{
"code": null,
"e": 1357,
"s": 1319,
"text": "const arr = [2, 5, 2, 6, 7, 1, 8, 9];"
},
{
"code": null,
"e": 1385,
"s": 1357,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1426,
"s": 1385,
"text": "const output = [2, 2, 6, 8, 1, 5, 7, 9];"
},
{
"code": null,
"e": 1450,
"s": 1426,
"text": "Following is the code −"
},
{
"code": null,
"e": 1772,
"s": 1450,
"text": "const arr = [2, 5, 2, 6, 7, 1, 8, 9];\nconst isEven = num => num % 2 === 0;\nconst sorter = ((a, b) => {\n if(isEven(a) && !isEven(b)){\n return -1;\n };\n if(!isEven(a) && isEven(b)){\n return 1;\n };\n return a - b;\n});\nconst oddEvenSort = arr => {\n arr.sort(sorter);\n};\noddEvenSort(arr);\nconsole.log(arr);"
},
{
"code": null,
"e": 1813,
"s": 1772,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1846,
"s": 1813,
"text": "[\n 2, 2, 6, 8,\n 1, 5, 7, 9\n]"
}
]
|
How to use isEmpty() in Android textview? | This example demonstrate about How to use isEmpty() in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and check that data is empty or not.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
int index = name.getText().toString().indexOf("sai");
text.setText(String.valueOf(index));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “Krishna sai” and it is not empty string so it returned index of sai as 8.
Click here to download the project code | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrate about How to use isEmpty() in Android textview."
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1329,
"s": 1264,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2219,
"s": 1329,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2352,
"s": 2219,
"text": "In the above code, we have taken name as Edit text, when user click on button it will take data and check that data is empty or not."
},
{
"code": null,
"e": 2409,
"s": 2352,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3520,
"s": 2409,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n int index = name.getText().toString().indexOf(\"sai\");\n text.setText(String.valueOf(index));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3867,
"s": 3520,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3983,
"s": 3867,
"text": "In the above result, enter the string as “Krishna sai” and it is not empty string so it returned index of sai as 8."
},
{
"code": null,
"e": 4023,
"s": 3983,
"text": "Click here to download the project code"
}
]
|
How to use an image as a link in HTML? | To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image. With that, also add the height and width.
You can try to run the following code to use an image as a link in HTML
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Image as link</title>
</head>
<body>
The following image works as a link:<br>
<a href="https://www.qries.com/">
<img alt="Qries" src="https://www.qries.com/images/banner_logo.png"
width=150" height="70">
</a>
</body>
</html> | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image. With that, also add the height and width."
},
{
"code": null,
"e": 1423,
"s": 1351,
"text": "You can try to run the following code to use an image as a link in HTML"
},
{
"code": null,
"e": 1433,
"s": 1423,
"text": "Live Demo"
},
{
"code": null,
"e": 1754,
"s": 1433,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Image as link</title>\n </head>\n <body>\n The following image works as a link:<br>\n <a href=\"https://www.qries.com/\">\n <img alt=\"Qries\" src=\"https://www.qries.com/images/banner_logo.png\"\n width=150\" height=\"70\">\n </a>\n </body>\n</html>"
}
]
|
Program to find all possible IP address after restoration in C++ | Suppose we have a string with only digits, we have to restore it by forming all possible valid IP address combinations. We know that a valid IP address consists of exactly four integers (each integer is in range 0 to 255) separated by single period symbol.
So, if the input is like ip = "25525511136", then the output will be ["254.25.40.123", "254.254.0.123"]
To solve this, we will follow these steps −
Define a function convertToNum(), this will take s, start, end,
num := 0
for initialize i := start, when i <= end, update (increase i by 1), do −num := (num * 10) + (s[i] - ASCII of '0')if num > 255, then −return 10000
num := (num * 10) + (s[i] - ASCII of '0')
if num > 255, then −return 10000
return 10000
return num
Define a function addDots(), this will take positions,
res := blank string
x := 0, posIndex := 0
for initialize i := 0, when i < size of positions, update (increase i by 1), do −num := positions[i]create one string str1temp := num as stringres := res + tempif i < size of positions, then −res := res concatenate "."
num := positions[i]
create one string str1
temp := num as string
res := res + temp
if i < size of positions, then −res := res concatenate "."
res := res concatenate "."
return res
Define a function solve(), this will take s, one string array result, an array positions, dotCount, this is initialize it with 3, startIndex, this is initialize it with 0,
if not dotCount is non-zero and ((size of s - 1) - startIndex + 1) 1, then −temp := convertToNum(s, startIndex, size of s)if temp >= 0 and temp <= 255, then −insert temp at the end of positionsres := addDots(positions)if size of res is same as size of s, then −insert res at the end of resultreturn
temp := convertToNum(s, startIndex, size of s)
if temp >= 0 and temp <= 255, then −insert temp at the end of positionsres := addDots(positions)if size of res is same as size of s, then −insert res at the end of result
insert temp at the end of positions
res := addDots(positions)
if size of res is same as size of s, then −insert res at the end of result
insert res at the end of result
return
for initialize i := startIndex, when i < size of s, update (increase i by 1), do −temp := convertToNum(s, startIndex, i)if temp >= 0 and temp <= 255, then −insert temp at the end of positionssolve(s, result, positions, dotCount - 1, i + 1)delete last element from positions
temp := convertToNum(s, startIndex, i)
if temp >= 0 and temp <= 255, then −insert temp at the end of positionssolve(s, result, positions, dotCount - 1, i + 1)delete last element from positions
insert temp at the end of positions
solve(s, result, positions, dotCount - 1, i + 1)
delete last element from positions
Define one function genIp this will take a string s
Define an array result
Define an array position
solve(s, result, position)
return result
From the main method call genIp(A)
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
typedef long long int lli;
class Solution {
public:
lli convertToNum(string s,int start, int end){
lli num = 0;
for (int i = start; i <= end; i++) {
num = (num * 10) + (s[i] - '0');
if (num > 255)
return 10000;
}
return num;
}
string addDots(vector <int> positions){
string res = "";
int x = 0;
int posIndex = 0;
for (int i = 0; i < positions.size(); i++) {
int num = positions[i];
ostringstream str1;
str1 << num;
string temp = str1.str();
res += temp;
if (i < positions.size() - 1)
res += ".";
}
return res;
}
void solve(string s, vector <string> &result,vector <int> positions, int dotCount = 3, int startIndex = 0){
if (!dotCount && ((s.size() - 1) - startIndex + 1) >= 1) {
int temp = convertToNum(s, startIndex, s.size() - 1);
if (temp >= 0 && temp <= 255) {
positions.push_back(temp);
string res = addDots(positions);
if (res.size() - 3 == s.size()) {
result.push_back(res);
}
}
return;
}
for (int i = startIndex; i < s.size(); i++) {
int temp = convertToNum(s, startIndex, i);
if (temp >= 0 && temp <= 255) {
positions.push_back(temp);
solve(s, result, positions, dotCount - 1, i + 1);
positions.pop_back();
}
}
}
vector<string> genIp(string s){
vector<string> result;
vector<int> position;
solve(s, result, position);
return result;
}
vector<string> get_ip(string A) {
return genIp(A);
}};
main(){
Solution ob;
string ip = "25525511136";
print_vector(ob.get_ip(ip));
}
25525511136
[255.255.11.136, 255.255.111.36, ] | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "Suppose we have a string with only digits, we have to restore it by forming all possible valid IP address combinations. We know that a valid IP address consists of exactly four integers (each integer is in range 0 to 255) separated by single period symbol."
},
{
"code": null,
"e": 1423,
"s": 1319,
"text": "So, if the input is like ip = \"25525511136\", then the output will be [\"254.25.40.123\", \"254.254.0.123\"]"
},
{
"code": null,
"e": 1467,
"s": 1423,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1531,
"s": 1467,
"text": "Define a function convertToNum(), this will take s, start, end,"
},
{
"code": null,
"e": 1540,
"s": 1531,
"text": "num := 0"
},
{
"code": null,
"e": 1686,
"s": 1540,
"text": "for initialize i := start, when i <= end, update (increase i by 1), do −num := (num * 10) + (s[i] - ASCII of '0')if num > 255, then −return 10000"
},
{
"code": null,
"e": 1728,
"s": 1686,
"text": "num := (num * 10) + (s[i] - ASCII of '0')"
},
{
"code": null,
"e": 1761,
"s": 1728,
"text": "if num > 255, then −return 10000"
},
{
"code": null,
"e": 1774,
"s": 1761,
"text": "return 10000"
},
{
"code": null,
"e": 1785,
"s": 1774,
"text": "return num"
},
{
"code": null,
"e": 1840,
"s": 1785,
"text": "Define a function addDots(), this will take positions,"
},
{
"code": null,
"e": 1860,
"s": 1840,
"text": "res := blank string"
},
{
"code": null,
"e": 1882,
"s": 1860,
"text": "x := 0, posIndex := 0"
},
{
"code": null,
"e": 2101,
"s": 1882,
"text": "for initialize i := 0, when i < size of positions, update (increase i by 1), do −num := positions[i]create one string str1temp := num as stringres := res + tempif i < size of positions, then −res := res concatenate \".\""
},
{
"code": null,
"e": 2121,
"s": 2101,
"text": "num := positions[i]"
},
{
"code": null,
"e": 2144,
"s": 2121,
"text": "create one string str1"
},
{
"code": null,
"e": 2166,
"s": 2144,
"text": "temp := num as string"
},
{
"code": null,
"e": 2184,
"s": 2166,
"text": "res := res + temp"
},
{
"code": null,
"e": 2243,
"s": 2184,
"text": "if i < size of positions, then −res := res concatenate \".\""
},
{
"code": null,
"e": 2270,
"s": 2243,
"text": "res := res concatenate \".\""
},
{
"code": null,
"e": 2281,
"s": 2270,
"text": "return res"
},
{
"code": null,
"e": 2453,
"s": 2281,
"text": "Define a function solve(), this will take s, one string array result, an array positions, dotCount, this is initialize it with 3, startIndex, this is initialize it with 0,"
},
{
"code": null,
"e": 2752,
"s": 2453,
"text": "if not dotCount is non-zero and ((size of s - 1) - startIndex + 1) 1, then −temp := convertToNum(s, startIndex, size of s)if temp >= 0 and temp <= 255, then −insert temp at the end of positionsres := addDots(positions)if size of res is same as size of s, then −insert res at the end of resultreturn"
},
{
"code": null,
"e": 2799,
"s": 2752,
"text": "temp := convertToNum(s, startIndex, size of s)"
},
{
"code": null,
"e": 2970,
"s": 2799,
"text": "if temp >= 0 and temp <= 255, then −insert temp at the end of positionsres := addDots(positions)if size of res is same as size of s, then −insert res at the end of result"
},
{
"code": null,
"e": 3006,
"s": 2970,
"text": "insert temp at the end of positions"
},
{
"code": null,
"e": 3032,
"s": 3006,
"text": "res := addDots(positions)"
},
{
"code": null,
"e": 3107,
"s": 3032,
"text": "if size of res is same as size of s, then −insert res at the end of result"
},
{
"code": null,
"e": 3139,
"s": 3107,
"text": "insert res at the end of result"
},
{
"code": null,
"e": 3146,
"s": 3139,
"text": "return"
},
{
"code": null,
"e": 3420,
"s": 3146,
"text": "for initialize i := startIndex, when i < size of s, update (increase i by 1), do −temp := convertToNum(s, startIndex, i)if temp >= 0 and temp <= 255, then −insert temp at the end of positionssolve(s, result, positions, dotCount - 1, i + 1)delete last element from positions"
},
{
"code": null,
"e": 3459,
"s": 3420,
"text": "temp := convertToNum(s, startIndex, i)"
},
{
"code": null,
"e": 3613,
"s": 3459,
"text": "if temp >= 0 and temp <= 255, then −insert temp at the end of positionssolve(s, result, positions, dotCount - 1, i + 1)delete last element from positions"
},
{
"code": null,
"e": 3649,
"s": 3613,
"text": "insert temp at the end of positions"
},
{
"code": null,
"e": 3698,
"s": 3649,
"text": "solve(s, result, positions, dotCount - 1, i + 1)"
},
{
"code": null,
"e": 3733,
"s": 3698,
"text": "delete last element from positions"
},
{
"code": null,
"e": 3785,
"s": 3733,
"text": "Define one function genIp this will take a string s"
},
{
"code": null,
"e": 3808,
"s": 3785,
"text": "Define an array result"
},
{
"code": null,
"e": 3833,
"s": 3808,
"text": "Define an array position"
},
{
"code": null,
"e": 3860,
"s": 3833,
"text": "solve(s, result, position)"
},
{
"code": null,
"e": 3874,
"s": 3860,
"text": "return result"
},
{
"code": null,
"e": 3909,
"s": 3874,
"text": "From the main method call genIp(A)"
},
{
"code": null,
"e": 3979,
"s": 3909,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3990,
"s": 3979,
"text": " Live Demo"
},
{
"code": null,
"e": 5987,
"s": 3990,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\ntypedef long long int lli;\nclass Solution {\n public:\n lli convertToNum(string s,int start, int end){\n lli num = 0;\n for (int i = start; i <= end; i++) {\n num = (num * 10) + (s[i] - '0');\n if (num > 255)\n return 10000;\n }\n return num;\n }\n string addDots(vector <int> positions){\n string res = \"\";\n int x = 0;\n int posIndex = 0;\n for (int i = 0; i < positions.size(); i++) {\n int num = positions[i];\n ostringstream str1;\n str1 << num;\n string temp = str1.str();\n res += temp;\n if (i < positions.size() - 1)\n res += \".\";\n }\n return res;\n }\n void solve(string s, vector <string> &result,vector <int> positions, int dotCount = 3, int startIndex = 0){\n if (!dotCount && ((s.size() - 1) - startIndex + 1) >= 1) {\n int temp = convertToNum(s, startIndex, s.size() - 1);\n if (temp >= 0 && temp <= 255) {\n positions.push_back(temp);\n string res = addDots(positions);\n if (res.size() - 3 == s.size()) {\n result.push_back(res);\n }\n }\n return;\n }\n for (int i = startIndex; i < s.size(); i++) {\n int temp = convertToNum(s, startIndex, i);\n if (temp >= 0 && temp <= 255) {\n positions.push_back(temp);\n solve(s, result, positions, dotCount - 1, i + 1);\n positions.pop_back();\n }\n }\n }\n vector<string> genIp(string s){\n vector<string> result;\n vector<int> position;\n solve(s, result, position);\n return result;\n }\n vector<string> get_ip(string A) {\n return genIp(A);\n}};\nmain(){\n Solution ob;\n string ip = \"25525511136\";\n print_vector(ob.get_ip(ip));\n}"
},
{
"code": null,
"e": 5999,
"s": 5987,
"text": "25525511136"
},
{
"code": null,
"e": 6034,
"s": 5999,
"text": "[255.255.11.136, 255.255.111.36, ]"
}
]
|
How to use sys.argv in Python - GeeksforGeeks | 27 Dec, 2019
Command line arguments are those values that are passed during calling of program along with the calling statement. Thus, the first element of the array sys.argv() is the name of the program itself. sys.argv() is an array for command line arguments in Python. To employ this module named “sys” is used. sys.argv is similar to an array and the values are also retrieved like Python array.
The sys module
The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
Examples:
# Python program to demonstrate# sys.argv import sys print("This is the name of the program:", sys.argv[0]) print("Argument List:", str(sys.argv))
Output:
The above program has been saved by the name “com.py” and thus has to be called in the following in command prompt
Functions that can be used with sys.argv
len()- function is used to count the number of arguments passed to the command line. Since the iteration starts with 0, it also counts the name of the program as one argument. If one just wants to deal with other inputs they can use (len(sys.argv)-1).
str()- this function is used to present the array as a string array. Makes displaying the command line array easier and better.
Example:
# Python program to demonstrate# sys.argv import sys print("This is the name of the program:", sys.argv[0])print("Number of elements including the name of the program:", len(sys.argv))print("Number of elements excluding the name of the program:", (len(sys.argv)-1))print("Argument List:", str(sys.argv))
Output:
The following program performs addition using inputs given during runtime:
# Python program to demonstrate# sys.argv import sys add = 0.0 # Getting the length of command# line argumentsn = len(sys.argv) for i in range(1, n): add += float(sys.argv[i]) print ("the sum is :", add)
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 23835,
"s": 23807,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 24223,
"s": 23835,
"text": "Command line arguments are those values that are passed during calling of program along with the calling statement. Thus, the first element of the array sys.argv() is the name of the program itself. sys.argv() is an array for command line arguments in Python. To employ this module named “sys” is used. sys.argv is similar to an array and the values are also retrieved like Python array."
},
{
"code": null,
"e": 24238,
"s": 24223,
"text": "The sys module"
},
{
"code": null,
"e": 24502,
"s": 24238,
"text": "The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter."
},
{
"code": null,
"e": 24512,
"s": 24502,
"text": "Examples:"
},
{
"code": "# Python program to demonstrate# sys.argv import sys print(\"This is the name of the program:\", sys.argv[0]) print(\"Argument List:\", str(sys.argv))",
"e": 24664,
"s": 24512,
"text": null
},
{
"code": null,
"e": 24672,
"s": 24664,
"text": "Output:"
},
{
"code": null,
"e": 24787,
"s": 24672,
"text": "The above program has been saved by the name “com.py” and thus has to be called in the following in command prompt"
},
{
"code": null,
"e": 24828,
"s": 24787,
"text": "Functions that can be used with sys.argv"
},
{
"code": null,
"e": 25080,
"s": 24828,
"text": "len()- function is used to count the number of arguments passed to the command line. Since the iteration starts with 0, it also counts the name of the program as one argument. If one just wants to deal with other inputs they can use (len(sys.argv)-1)."
},
{
"code": null,
"e": 25208,
"s": 25080,
"text": "str()- this function is used to present the array as a string array. Makes displaying the command line array easier and better."
},
{
"code": null,
"e": 25217,
"s": 25208,
"text": "Example:"
},
{
"code": "# Python program to demonstrate# sys.argv import sys print(\"This is the name of the program:\", sys.argv[0])print(\"Number of elements including the name of the program:\", len(sys.argv))print(\"Number of elements excluding the name of the program:\", (len(sys.argv)-1))print(\"Argument List:\", str(sys.argv))",
"e": 25550,
"s": 25217,
"text": null
},
{
"code": null,
"e": 25558,
"s": 25550,
"text": "Output:"
},
{
"code": null,
"e": 25633,
"s": 25558,
"text": "The following program performs addition using inputs given during runtime:"
},
{
"code": "# Python program to demonstrate# sys.argv import sys add = 0.0 # Getting the length of command# line argumentsn = len(sys.argv) for i in range(1, n): add += float(sys.argv[i]) print (\"the sum is :\", add)",
"e": 25847,
"s": 25633,
"text": null
},
{
"code": null,
"e": 25855,
"s": 25847,
"text": "Output:"
},
{
"code": null,
"e": 25870,
"s": 25855,
"text": "python-utility"
},
{
"code": null,
"e": 25877,
"s": 25870,
"text": "Python"
},
{
"code": null,
"e": 25975,
"s": 25877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25984,
"s": 25975,
"text": "Comments"
},
{
"code": null,
"e": 25997,
"s": 25984,
"text": "Old Comments"
},
{
"code": null,
"e": 26019,
"s": 25997,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26051,
"s": 26019,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26093,
"s": 26051,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26119,
"s": 26093,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26144,
"s": 26119,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26181,
"s": 26144,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26237,
"s": 26181,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26270,
"s": 26237,
"text": "Graph Plotting in Python | Set 1"
},
{
"code": null,
"e": 26311,
"s": 26270,
"text": "Print lists in Python (4 Different Ways)"
}
]
|
Binary Search Trees - GeeksforGeeks | 06 Sep, 2021
10
/
20
/
30
/
40
Search 40.
Delete 40
Insert 50.
The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)
2
3
4
6
Constructed binary search tree will be.
30
/ \
20 39
/ \ / \
10 25 35 42
\ /
15 23
10
/
5 20
/ /
4 15 30
/
11
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Find size of largest subset with bitwise AND greater than their bitwise XOR
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Compare Two Columns in Pandas?
Python Data Structures and Algorithms
Data Science With Python Tutorial | [
{
"code": null,
"e": 28855,
"s": 28827,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 28952,
"s": 28855,
"text": " 10\n /\n 20\n /\n 30\n / \n 40\n\nSearch 40. \nDelete 40\nInsert 50.\n"
},
{
"code": null,
"e": 29193,
"s": 28952,
"text": "The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004) "
},
{
"code": null,
"e": 29196,
"s": 29193,
"text": "2 "
},
{
"code": null,
"e": 29199,
"s": 29196,
"text": "3 "
},
{
"code": null,
"e": 29202,
"s": 29199,
"text": "4 "
},
{
"code": null,
"e": 29205,
"s": 29202,
"text": "6 "
},
{
"code": null,
"e": 29245,
"s": 29205,
"text": "Constructed binary search tree will be."
},
{
"code": null,
"e": 29371,
"s": 29247,
"text": " 30\n / \\\n 20 39 \n / \\ / \\\n 10 25 35 42 \n \\ /\n 15 23\n"
},
{
"code": null,
"e": 29532,
"s": 29371,
"text": "\n 10\n / \n 5 20\n / / \n 4 15 30\n / \n 11 "
},
{
"code": null,
"e": 29630,
"s": 29532,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29683,
"s": 29630,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29759,
"s": 29683,
"text": "Find size of largest subset with bitwise AND greater than their bitwise XOR"
},
{
"code": null,
"e": 29821,
"s": 29759,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29862,
"s": 29821,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29897,
"s": 29862,
"text": "Insert Image in a Jupyter Notebook"
},
{
"code": null,
"e": 29940,
"s": 29897,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29976,
"s": 29940,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 30014,
"s": 29976,
"text": "How to Compare Two Columns in Pandas?"
},
{
"code": null,
"e": 30052,
"s": 30014,
"text": "Python Data Structures and Algorithms"
}
]
|
C# | Get an ICollection containing the values in ListDictionary - GeeksforGeeks | 01 Feb, 2019
ListDictionary.Values property is used to get an ICollection containing the values in the ListDictionary.
Syntax:
public System.Collections.ICollection Values { get; }
Return Value : It returns an ICollection containing the values in the ListDictionary.
Below are the programs to illustrate the use of ListDictionary.Values property:
Example 1:
// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // Get an ICollection containing // the values in the ListDictionary ICollection ic = myDict.Values; // Displaying the values in ICollection ic foreach(String str in ic) { Console.WriteLine(str); } }}
Canberra
Brussels
Amsterdam
Beijing
Moscow
New Delhi
Example 2 :
// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add("I", "first"); myDict.Add("II", "second"); myDict.Add("III", "third"); myDict.Add("IV", "fourth"); myDict.Add("V", "fifth"); // Get an ICollection containing // the values in the ListDictionary ICollection ic = myDict.Values; // Displaying the values in ICollection ic foreach(String str in ic) { Console.WriteLine(str); } }}
first
second
third
fourth
fifth
Note:
The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method.
The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original ListDictionary. Therefore, changes to the ListDictionary continue to be reflected in the ICollection.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.values?view=netframework-4.7.2
CSharp-Specialized-ListDictionary
CSharp-Specialized-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | Replace() Method
C# | Data Types
C# | Encapsulation | [
{
"code": null,
"e": 25833,
"s": 25805,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 25939,
"s": 25833,
"text": "ListDictionary.Values property is used to get an ICollection containing the values in the ListDictionary."
},
{
"code": null,
"e": 25947,
"s": 25939,
"text": "Syntax:"
},
{
"code": null,
"e": 26002,
"s": 25947,
"text": "public System.Collections.ICollection Values { get; }\n"
},
{
"code": null,
"e": 26088,
"s": 26002,
"text": "Return Value : It returns an ICollection containing the values in the ListDictionary."
},
{
"code": null,
"e": 26168,
"s": 26088,
"text": "Below are the programs to illustrate the use of ListDictionary.Values property:"
},
{
"code": null,
"e": 26179,
"s": 26168,
"text": "Example 1:"
},
{
"code": "// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // Get an ICollection containing // the values in the ListDictionary ICollection ic = myDict.Values; // Displaying the values in ICollection ic foreach(String str in ic) { Console.WriteLine(str); } }}",
"e": 27026,
"s": 26179,
"text": null
},
{
"code": null,
"e": 27080,
"s": 27026,
"text": "Canberra\nBrussels\nAmsterdam\nBeijing\nMoscow\nNew Delhi\n"
},
{
"code": null,
"e": 27092,
"s": 27080,
"text": "Example 2 :"
},
{
"code": "// C# code to get an ICollection// containing the values in the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add(\"I\", \"first\"); myDict.Add(\"II\", \"second\"); myDict.Add(\"III\", \"third\"); myDict.Add(\"IV\", \"fourth\"); myDict.Add(\"V\", \"fifth\"); // Get an ICollection containing // the values in the ListDictionary ICollection ic = myDict.Values; // Displaying the values in ICollection ic foreach(String str in ic) { Console.WriteLine(str); } }}",
"e": 27858,
"s": 27092,
"text": null
},
{
"code": null,
"e": 27891,
"s": 27858,
"text": "first\nsecond\nthird\nfourth\nfifth\n"
},
{
"code": null,
"e": 27897,
"s": 27891,
"text": "Note:"
},
{
"code": null,
"e": 28052,
"s": 27897,
"text": "The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method."
},
{
"code": null,
"e": 28268,
"s": 28052,
"text": "The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original ListDictionary. Therefore, changes to the ListDictionary continue to be reflected in the ICollection."
},
{
"code": null,
"e": 28328,
"s": 28268,
"text": "Retrieving the value of this property is an O(1) operation."
},
{
"code": null,
"e": 28339,
"s": 28328,
"text": "Reference:"
},
{
"code": null,
"e": 28460,
"s": 28339,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.values?view=netframework-4.7.2"
},
{
"code": null,
"e": 28494,
"s": 28460,
"text": "CSharp-Specialized-ListDictionary"
},
{
"code": null,
"e": 28523,
"s": 28494,
"text": "CSharp-Specialized-Namespace"
},
{
"code": null,
"e": 28526,
"s": 28523,
"text": "C#"
},
{
"code": null,
"e": 28624,
"s": 28526,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28639,
"s": 28624,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28661,
"s": 28639,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28707,
"s": 28661,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28729,
"s": 28707,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28747,
"s": 28729,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28770,
"s": 28747,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28801,
"s": 28770,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28823,
"s": 28801,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28839,
"s": 28823,
"text": "C# | Data Types"
}
]
|
std::stable_partition in C++ - GeeksforGeeks | 05 Oct, 2017
The stable_partition( ) algorithm arranges the sequence defined by start and end such that all elements for which the predicate specified by pfn returns true come before those for which the predicate returns false. The partitioning is stable. This means that the relative ordering of the sequence is preserved.Syntax:
template
BiIter stable_partition(BiIter start, BiIter end, UnPred pfn);
Parameters:
start: the range of elements to reorder
end: the range of elements to reorder
pfn: User-defined predicate function object that
defines the condition to be satisfied if an element is to be classified.
A predicate takes single argument and returns true or false.
Return Value:
Returns an iterator to the beginning of the elements
for which the predicate is false.
This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen.Example 1:
// CPP program to illustrate stable_partition#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v{ 6, 9, 0, 1, 2, 7, 5, 8, 0 }; stable_partition(v.begin(), v.end(), [](int n) {return n>0; }); for (int n : v) { cout << n << ' '; } cout << '\n';}
Output:
6 9 1 2 7 5 8 0 0
Example 2:
// CPP program to illustrate stable_partition#include <iostream>#include <algorithm> // std::stable_partition#include <vector> bool odd(int i) { return (i % 2) == 1; } int main(){ std::vector<int> vct; for (int i = 1; i < 10; ++i) vct.push_back(i); // 1 2 3 4 5 6 7 8 9 std::vector<int>::iterator bound; bound = std::stable_partition(vct.begin(), vct.end(), odd); std::cout << "odd numbers:"; for (std::vector<int>::iterator it = vct.begin(); it != bound; ++it) std::cout << ' ' << *it; std::cout << '\n'; std::cout << "evennumbers:"; for (std::vector<int>::iterator it = bound; it != vct.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0;}
Output:
odd numbers: 1 3 5 7 9
even numbers: 2 4 6 8
Example 3:
// CPP program to illustrate stable_partition#include <algorithm>#include <deque>#include <functional>#include <iostream>#include <iterator> template <class Arg>struct is_even : public std::unary_function<Arg, bool> { bool operator()(const Arg& arg1) const { return (arg1 % 2) == 0; }}; int main(){ typedef std::deque<int, std::allocator<int> > Deque; typedef std::ostream_iterator<int, char, std::char_traits<char> > Iter; const Deque::value_type a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Deque d1(a + 0, a + sizeof a / sizeof *a); Deque d2(d1); std::cout << "Unpartitioned values: \t\t"; std::copy(d1.begin(), d1.end(), Iter(std::cout, " ")); std::partition(d2.begin(), d2.end(), is_even<int>()); std::cout << "\nPartitioned values: \t\t"; std::copy(d2.begin(), d2.end(), Iter(std::cout, " ")); std::stable_partition(d1.begin(), d1.end(), is_even<int>()); std::cout << "\nStable partitioned values: \t"; std::copy(d1.begin(), d1.end(), Iter(std::cout, " ")); std::cout << std::endl; return 0;}
Output:
Unpartitioned values: 1 2 3 4 5 6 7 8 9 10
Partitioned values: 10 2 8 4 6 5 7 3 9 1
Stable partitioned values: 2 4 6 8 10 1 3 5 7 9
Complexity: Exactly end-start applications of the predicate and at most (end-start)*log(end-start) swaps if there is insufficient memory or linear number of swaps if sufficient memory is available.
This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
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++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Queue in C++ Standard Template Library (STL)
Convert string to char array in C++ | [
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n05 Oct, 2017"
},
{
"code": null,
"e": 25685,
"s": 25367,
"text": "The stable_partition( ) algorithm arranges the sequence defined by start and end such that all elements for which the predicate specified by pfn returns true come before those for which the predicate returns false. The partitioning is stable. This means that the relative ordering of the sequence is preserved.Syntax:"
},
{
"code": null,
"e": 25759,
"s": 25685,
"text": "template \nBiIter stable_partition(BiIter start, BiIter end, UnPred pfn);\n"
},
{
"code": null,
"e": 25771,
"s": 25759,
"text": "Parameters:"
},
{
"code": null,
"e": 26140,
"s": 25771,
"text": "start: the range of elements to reorder\nend: the range of elements to reorder\npfn: User-defined predicate function object that \ndefines the condition to be satisfied if an element is to be classified.\nA predicate takes single argument and returns true or false.\nReturn Value: \nReturns an iterator to the beginning of the elements \nfor which the predicate is false.\n"
},
{
"code": null,
"e": 26270,
"s": 26140,
"text": "This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen.Example 1:"
},
{
"code": "// CPP program to illustrate stable_partition#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ vector<int> v{ 6, 9, 0, 1, 2, 7, 5, 8, 0 }; stable_partition(v.begin(), v.end(), [](int n) {return n>0; }); for (int n : v) { cout << n << ' '; } cout << '\\n';}",
"e": 26586,
"s": 26270,
"text": null
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "Output:"
},
{
"code": null,
"e": 26614,
"s": 26594,
"text": "6 9 1 2 7 5 8 0 0 \n"
},
{
"code": null,
"e": 26625,
"s": 26614,
"text": "Example 2:"
},
{
"code": "// CPP program to illustrate stable_partition#include <iostream>#include <algorithm> // std::stable_partition#include <vector> bool odd(int i) { return (i % 2) == 1; } int main(){ std::vector<int> vct; for (int i = 1; i < 10; ++i) vct.push_back(i); // 1 2 3 4 5 6 7 8 9 std::vector<int>::iterator bound; bound = std::stable_partition(vct.begin(), vct.end(), odd); std::cout << \"odd numbers:\"; for (std::vector<int>::iterator it = vct.begin(); it != bound; ++it) std::cout << ' ' << *it; std::cout << '\\n'; std::cout << \"evennumbers:\"; for (std::vector<int>::iterator it = bound; it != vct.end(); ++it) std::cout << ' ' << *it; std::cout << '\\n'; return 0;}",
"e": 27348,
"s": 26625,
"text": null
},
{
"code": null,
"e": 27356,
"s": 27348,
"text": "Output:"
},
{
"code": null,
"e": 27402,
"s": 27356,
"text": "odd numbers: 1 3 5 7 9\neven numbers: 2 4 6 8\n"
},
{
"code": null,
"e": 27413,
"s": 27402,
"text": "Example 3:"
},
{
"code": "// CPP program to illustrate stable_partition#include <algorithm>#include <deque>#include <functional>#include <iostream>#include <iterator> template <class Arg>struct is_even : public std::unary_function<Arg, bool> { bool operator()(const Arg& arg1) const { return (arg1 % 2) == 0; }}; int main(){ typedef std::deque<int, std::allocator<int> > Deque; typedef std::ostream_iterator<int, char, std::char_traits<char> > Iter; const Deque::value_type a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; Deque d1(a + 0, a + sizeof a / sizeof *a); Deque d2(d1); std::cout << \"Unpartitioned values: \\t\\t\"; std::copy(d1.begin(), d1.end(), Iter(std::cout, \" \")); std::partition(d2.begin(), d2.end(), is_even<int>()); std::cout << \"\\nPartitioned values: \\t\\t\"; std::copy(d2.begin(), d2.end(), Iter(std::cout, \" \")); std::stable_partition(d1.begin(), d1.end(), is_even<int>()); std::cout << \"\\nStable partitioned values: \\t\"; std::copy(d1.begin(), d1.end(), Iter(std::cout, \" \")); std::cout << std::endl; return 0;}",
"e": 28583,
"s": 27413,
"text": null
},
{
"code": null,
"e": 28591,
"s": 28583,
"text": "Output:"
},
{
"code": null,
"e": 28747,
"s": 28591,
"text": "Unpartitioned values: 1 2 3 4 5 6 7 8 9 10 \nPartitioned values: 10 2 8 4 6 5 7 3 9 1 \nStable partitioned values: 2 4 6 8 10 1 3 5 7 9 \n"
},
{
"code": null,
"e": 28945,
"s": 28747,
"text": "Complexity: Exactly end-start applications of the predicate and at most (end-start)*log(end-start) swaps if there is insufficient memory or linear number of swaps if sufficient memory is available."
},
{
"code": null,
"e": 29250,
"s": 28945,
"text": "This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29375,
"s": 29250,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29397,
"s": 29375,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 29401,
"s": 29397,
"text": "STL"
},
{
"code": null,
"e": 29405,
"s": 29401,
"text": "C++"
},
{
"code": null,
"e": 29409,
"s": 29405,
"text": "STL"
},
{
"code": null,
"e": 29413,
"s": 29409,
"text": "CPP"
},
{
"code": null,
"e": 29511,
"s": 29413,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29539,
"s": 29511,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29559,
"s": 29539,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29592,
"s": 29559,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29616,
"s": 29592,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 29641,
"s": 29616,
"text": "std::string class in C++"
},
{
"code": null,
"e": 29685,
"s": 29641,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 29709,
"s": 29685,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 29762,
"s": 29709,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 29807,
"s": 29762,
"text": "Queue in C++ Standard Template Library (STL)"
}
]
|
D3.js | Path.arc() Function - GeeksforGeeks | 22 Jun, 2020
D3.js is mostly used for making of graph and visualizing data on the HTML SVG elements. D3.js has many functions one of which is arc() function. The Path.arc() function is used to make a arc and a circle and other shapes. D3 stands for Data Driven Documents and mostly used for data visualization.
Syntax:
path.arc(x, y, radius, startAngle, endAngle[anticlockwise])
Parameters: This function accepts five parameter as mentioned above and described below:
x: This parameter holds the x-position of the arc in the SVG.
y: This parameter holds the y-position of the arc in the SVG.
radius: This parameter holds the radius of which the arc is to be made.
startAngle: This parameter holds the start angle of the arc.
endAngle[anticlockwise]: This parameter holds the angle to which the arc is to be made, if anticlockwise is true, the arc is drawn in the anticlockwise direction.
Note: If the current point is not equal to the starting point of the arc, a straight line is drawn from the current point to the start of the arc.
Below example illustrate the D3.js | Path.arc() Function in D3.js:
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <title>D3.js| Path.arc() Function</title> </head> <style> body { text-align: center; } h1 { color: green; } svg{ background-color: green; } .path1{ fill: aliceblue; } </style> <body> <h1>GeeksforGeeks</h1> <b>D3.js | Path.arc() Function</b> <div> <svg width="300" height="300"> <text x="50" y="50" font-family="Verdana" font-size="22" fill="white"> SVG Element </text> <path class="path1"> </svg> </div> <script src = "https://d3js.org/d3.v4.min.js"> </script> <script> // Creating path object var path1= d3.path(); // Creating arc of radius 100 path1.arc(150,150,100,0,3.14) d3.select(".path1").attr("d",path1); </script> </body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <title>D3.js| Path.arc() Function</title> </head> <style> body { text-align: center; } h1 { color: green; } svg{ background-color: green; } .path1{ fill: aliceblue; } </style> <body> <h1>GeeksforGeeks</h1> <b>D3.js | Path.arc() Function</b> <div> <svg width="300" height="300"> <text x="40" y="40" font-family="Verdana" font-size="22" fill="white"> SVG Element </text> <path class="path1"> </svg> </div> <script src = "https://d3js.org/d3.v4.min.js"> </script> <script> // Creating path object var path1= d3.path(); // Creating arc of radius 100 path1.arc(150,150,100,0,2*3.14) d3.select(".path1").attr("d",path1); </script> </body></html>
Output:
D3.js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
How do you run JavaScript script through the Terminal? | [
{
"code": null,
"e": 25871,
"s": 25843,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 26169,
"s": 25871,
"text": "D3.js is mostly used for making of graph and visualizing data on the HTML SVG elements. D3.js has many functions one of which is arc() function. The Path.arc() function is used to make a arc and a circle and other shapes. D3 stands for Data Driven Documents and mostly used for data visualization."
},
{
"code": null,
"e": 26177,
"s": 26169,
"text": "Syntax:"
},
{
"code": null,
"e": 26238,
"s": 26177,
"text": "path.arc(x, y, radius, startAngle, endAngle[anticlockwise])\n"
},
{
"code": null,
"e": 26327,
"s": 26238,
"text": "Parameters: This function accepts five parameter as mentioned above and described below:"
},
{
"code": null,
"e": 26389,
"s": 26327,
"text": "x: This parameter holds the x-position of the arc in the SVG."
},
{
"code": null,
"e": 26451,
"s": 26389,
"text": "y: This parameter holds the y-position of the arc in the SVG."
},
{
"code": null,
"e": 26523,
"s": 26451,
"text": "radius: This parameter holds the radius of which the arc is to be made."
},
{
"code": null,
"e": 26584,
"s": 26523,
"text": "startAngle: This parameter holds the start angle of the arc."
},
{
"code": null,
"e": 26749,
"s": 26584,
"text": "endAngle[anticlockwise]: This parameter holds the angle to which the arc is to be made, if anticlockwise is true, the arc is drawn in the anticlockwise direction."
},
{
"code": null,
"e": 26896,
"s": 26749,
"text": "Note: If the current point is not equal to the starting point of the arc, a straight line is drawn from the current point to the start of the arc."
},
{
"code": null,
"e": 26963,
"s": 26896,
"text": "Below example illustrate the D3.js | Path.arc() Function in D3.js:"
},
{
"code": null,
"e": 26974,
"s": 26963,
"text": "Example 1:"
},
{
"code": null,
"e": 26979,
"s": 26974,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <title>D3.js| Path.arc() Function</title> </head> <style> body { text-align: center; } h1 { color: green; } svg{ background-color: green; } .path1{ fill: aliceblue; } </style> <body> <h1>GeeksforGeeks</h1> <b>D3.js | Path.arc() Function</b> <div> <svg width=\"300\" height=\"300\"> <text x=\"50\" y=\"50\" font-family=\"Verdana\" font-size=\"22\" fill=\"white\"> SVG Element </text> <path class=\"path1\"> </svg> </div> <script src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> // Creating path object var path1= d3.path(); // Creating arc of radius 100 path1.arc(150,150,100,0,3.14) d3.select(\".path1\").attr(\"d\",path1); </script> </body></html>",
"e": 28056,
"s": 26979,
"text": null
},
{
"code": null,
"e": 28064,
"s": 28056,
"text": "Output:"
},
{
"code": null,
"e": 28075,
"s": 28064,
"text": "Example 2:"
},
{
"code": null,
"e": 28080,
"s": 28075,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <title>D3.js| Path.arc() Function</title> </head> <style> body { text-align: center; } h1 { color: green; } svg{ background-color: green; } .path1{ fill: aliceblue; } </style> <body> <h1>GeeksforGeeks</h1> <b>D3.js | Path.arc() Function</b> <div> <svg width=\"300\" height=\"300\"> <text x=\"40\" y=\"40\" font-family=\"Verdana\" font-size=\"22\" fill=\"white\"> SVG Element </text> <path class=\"path1\"> </svg> </div> <script src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> // Creating path object var path1= d3.path(); // Creating arc of radius 100 path1.arc(150,150,100,0,2*3.14) d3.select(\".path1\").attr(\"d\",path1); </script> </body></html>",
"e": 29159,
"s": 28080,
"text": null
},
{
"code": null,
"e": 29167,
"s": 29159,
"text": "Output:"
},
{
"code": null,
"e": 29173,
"s": 29167,
"text": "D3.js"
},
{
"code": null,
"e": 29184,
"s": 29173,
"text": "JavaScript"
},
{
"code": null,
"e": 29282,
"s": 29184,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29322,
"s": 29282,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29367,
"s": 29322,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29428,
"s": 29367,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29500,
"s": 29428,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29546,
"s": 29500,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29587,
"s": 29546,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29635,
"s": 29587,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 29671,
"s": 29635,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 29720,
"s": 29671,
"text": "How to Use the JavaScript Fetch API to Get Data?"
}
]
|
Recon-ng Information gathering tool in Kali Linux - GeeksforGeeks | 16 Apr, 2021
Recon-ng is free and open source tool available on GitHub. Recon-ng is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. Recon-ng interface is very similar to Metasploit 1 and Metasploit 2.Recon-ng provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). The interactive console provides a number of helpful features, such as command completion and contextual help. Recon-ng is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, Recon-ng provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information.
First look of Recon-ng framework
Recon-ng is free and open source tool this means you can download and use it at free of cost.
Recon-ng is a complete package of information gathering modules. It has so many modules that you can use for information gathering.
Recon-ng works and acts as a web application/website scanner.
Recon-ng is one of the easiest and useful tool for performing reconnaissance.
Recon-ng interface is very similar to metasploitable 1 and metasploitable 2 that makes is easy to use.
Recon-ng’s interactive console provides a number of helpful features.
Recon-ng is used for information gathering and vulnerability assessment of web applications.
Recon-ng uses shodan search engine to scan iot devices.
Recon-ng can easily find loopholes in the code of web applications and websites.
Recon-ng has following modules Geoip lookup, Banner grabbing, DNS lookup, port scanning, These modules makes this tool so powerful.
Recon-ng can target a single domain and can found all the subdomains of that domain which makes work easy for pentesters.
Recon-ng is a complete package of Information gathering tools.
Recon-ng can be used to find IP Addresses of target.
Recon-ng can be used to look for error based SQL injections.
Recon-ng can be used to find sensitive files such as robots.txt.
Recon-ng can be used to find information about Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP using WHOIS lookup .
Recon-ng can be used to detects Content Management Systems (CMS) in use of a target web application,
InfoSploit can be used for WHOIS data collection, Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP, and MX records lookup
Recon-ng is a complete package (TOOL) for information gathering. This tool is free and Open Source.
Recon-ng subdomain finder modules is used to find subdomains of a singer domain.
Recon-ng can be used to find robots.txt file of a website.
Recon-ng port scanner modules find closes and open ports which can be used to maintain access to the server.
Recon-ng has various modules that can be used to get the information about target.
Step 1: Open Terminal of your Kali Linux
Step 2: On Terminal now type command.
git clone https://github.com/lanmaster53/recon-ng.git
Congratulations recon-ng has been installed on your Kali Linux .now you just have to run recon-ng.
Step 3: Type command.
recon-ng
Now Recon-ng has been downloaded and running successfully.
Step 4: To launch recon-ng on your kali Linux type the following the command and press enter.
recon-ng
Step 5: Now to do Reconnaissance first you have to create a workspace for that. Basically, workspaces are like separate spaces in which you can perform reconnaissance of different targets. To know about workspaces just type the following command.
workspaces
Step 6. You have created workspace for you now you have to go to marketplace to install modules to initiate your Reconnaissance here we have created a workspace called GeeksForGeeks. Now we will Reconnaissance within GeeksForGeeks workspace. Now go to marketplace and install modules.
marketplace search
Step 7: As you can now see a list of modules and so many of them are not installed so to install those modules type following command.
marketplace install (module name)
Step 8: As you can see we have installed the module names recon/companies-domains/viewdns_reverse_whois. Now we will load this module in our workspace GeeksForGeeks.
modules load (module name)
Step 9: As you can see now we are under those modules i.e viewdns_reverse_whois. Now to use this module we have to set the source.
options set SOURCE (domain name)
We have set google.com as a source by command options set SOURCE google.com. Recon-ng is Open Source Intelligence, the easiest and useful tool for reconnaissance. Recon-ng interface is very similar to Metasploit 1 and Metasploit 2.Recon-ng provide command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). The interactive console provides a number of helpful features, such as command completion and contextual help. Recon-ng is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, Recon-ng provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information.
mohdshariq
Kali-Linux
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples | [
{
"code": null,
"e": 26022,
"s": 25994,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 26824,
"s": 26022,
"text": "Recon-ng is free and open source tool available on GitHub. Recon-ng is based upon Open Source Intelligence (OSINT), the easiest and useful tool for reconnaissance. Recon-ng interface is very similar to Metasploit 1 and Metasploit 2.Recon-ng provides a command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). The interactive console provides a number of helpful features, such as command completion and contextual help. Recon-ng is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, Recon-ng provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information."
},
{
"code": null,
"e": 26857,
"s": 26824,
"text": "First look of Recon-ng framework"
},
{
"code": null,
"e": 26951,
"s": 26857,
"text": "Recon-ng is free and open source tool this means you can download and use it at free of cost."
},
{
"code": null,
"e": 27083,
"s": 26951,
"text": "Recon-ng is a complete package of information gathering modules. It has so many modules that you can use for information gathering."
},
{
"code": null,
"e": 27145,
"s": 27083,
"text": "Recon-ng works and acts as a web application/website scanner."
},
{
"code": null,
"e": 27223,
"s": 27145,
"text": "Recon-ng is one of the easiest and useful tool for performing reconnaissance."
},
{
"code": null,
"e": 27326,
"s": 27223,
"text": "Recon-ng interface is very similar to metasploitable 1 and metasploitable 2 that makes is easy to use."
},
{
"code": null,
"e": 27396,
"s": 27326,
"text": "Recon-ng’s interactive console provides a number of helpful features."
},
{
"code": null,
"e": 27489,
"s": 27396,
"text": "Recon-ng is used for information gathering and vulnerability assessment of web applications."
},
{
"code": null,
"e": 27545,
"s": 27489,
"text": "Recon-ng uses shodan search engine to scan iot devices."
},
{
"code": null,
"e": 27626,
"s": 27545,
"text": "Recon-ng can easily find loopholes in the code of web applications and websites."
},
{
"code": null,
"e": 27758,
"s": 27626,
"text": "Recon-ng has following modules Geoip lookup, Banner grabbing, DNS lookup, port scanning, These modules makes this tool so powerful."
},
{
"code": null,
"e": 27880,
"s": 27758,
"text": "Recon-ng can target a single domain and can found all the subdomains of that domain which makes work easy for pentesters."
},
{
"code": null,
"e": 27943,
"s": 27880,
"text": "Recon-ng is a complete package of Information gathering tools."
},
{
"code": null,
"e": 27996,
"s": 27943,
"text": "Recon-ng can be used to find IP Addresses of target."
},
{
"code": null,
"e": 28057,
"s": 27996,
"text": "Recon-ng can be used to look for error based SQL injections."
},
{
"code": null,
"e": 28122,
"s": 28057,
"text": "Recon-ng can be used to find sensitive files such as robots.txt."
},
{
"code": null,
"e": 28284,
"s": 28122,
"text": "Recon-ng can be used to find information about Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP using WHOIS lookup ."
},
{
"code": null,
"e": 28385,
"s": 28284,
"text": "Recon-ng can be used to detects Content Management Systems (CMS) in use of a target web application,"
},
{
"code": null,
"e": 28553,
"s": 28385,
"text": "InfoSploit can be used for WHOIS data collection, Geo-IP lookup, Banner grabbing, DNS lookup, port scanning, sub-domain information, reverse IP, and MX records lookup"
},
{
"code": null,
"e": 28654,
"s": 28553,
"text": "Recon-ng is a complete package (TOOL) for information gathering. This tool is free and Open Source."
},
{
"code": null,
"e": 28735,
"s": 28654,
"text": "Recon-ng subdomain finder modules is used to find subdomains of a singer domain."
},
{
"code": null,
"e": 28794,
"s": 28735,
"text": "Recon-ng can be used to find robots.txt file of a website."
},
{
"code": null,
"e": 28903,
"s": 28794,
"text": "Recon-ng port scanner modules find closes and open ports which can be used to maintain access to the server."
},
{
"code": null,
"e": 28986,
"s": 28903,
"text": "Recon-ng has various modules that can be used to get the information about target."
},
{
"code": null,
"e": 29027,
"s": 28986,
"text": "Step 1: Open Terminal of your Kali Linux"
},
{
"code": null,
"e": 29065,
"s": 29027,
"text": "Step 2: On Terminal now type command."
},
{
"code": null,
"e": 29119,
"s": 29065,
"text": "git clone https://github.com/lanmaster53/recon-ng.git"
},
{
"code": null,
"e": 29218,
"s": 29119,
"text": "Congratulations recon-ng has been installed on your Kali Linux .now you just have to run recon-ng."
},
{
"code": null,
"e": 29240,
"s": 29218,
"text": "Step 3: Type command."
},
{
"code": null,
"e": 29249,
"s": 29240,
"text": "recon-ng"
},
{
"code": null,
"e": 29309,
"s": 29249,
"text": "Now Recon-ng has been downloaded and running successfully. "
},
{
"code": null,
"e": 29403,
"s": 29309,
"text": "Step 4: To launch recon-ng on your kali Linux type the following the command and press enter."
},
{
"code": null,
"e": 29412,
"s": 29403,
"text": "recon-ng"
},
{
"code": null,
"e": 29659,
"s": 29412,
"text": "Step 5: Now to do Reconnaissance first you have to create a workspace for that. Basically, workspaces are like separate spaces in which you can perform reconnaissance of different targets. To know about workspaces just type the following command."
},
{
"code": null,
"e": 29670,
"s": 29659,
"text": "workspaces"
},
{
"code": null,
"e": 29955,
"s": 29670,
"text": "Step 6. You have created workspace for you now you have to go to marketplace to install modules to initiate your Reconnaissance here we have created a workspace called GeeksForGeeks. Now we will Reconnaissance within GeeksForGeeks workspace. Now go to marketplace and install modules."
},
{
"code": null,
"e": 29975,
"s": 29955,
"text": "marketplace search "
},
{
"code": null,
"e": 30110,
"s": 29975,
"text": "Step 7: As you can now see a list of modules and so many of them are not installed so to install those modules type following command."
},
{
"code": null,
"e": 30146,
"s": 30110,
"text": " marketplace install (module name) "
},
{
"code": null,
"e": 30312,
"s": 30146,
"text": "Step 8: As you can see we have installed the module names recon/companies-domains/viewdns_reverse_whois. Now we will load this module in our workspace GeeksForGeeks."
},
{
"code": null,
"e": 30339,
"s": 30312,
"text": "modules load (module name)"
},
{
"code": null,
"e": 30471,
"s": 30339,
"text": "Step 9: As you can see now we are under those modules i.e viewdns_reverse_whois. Now to use this module we have to set the source."
},
{
"code": null,
"e": 30504,
"s": 30471,
"text": "options set SOURCE (domain name)"
},
{
"code": null,
"e": 31302,
"s": 30504,
"text": "We have set google.com as a source by command options set SOURCE google.com. Recon-ng is Open Source Intelligence, the easiest and useful tool for reconnaissance. Recon-ng interface is very similar to Metasploit 1 and Metasploit 2.Recon-ng provide command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). The interactive console provides a number of helpful features, such as command completion and contextual help. Recon-ng is a Web Reconnaissance tool written in Python. It has so many modules, database interaction, built-in convenience functions, interactive help, and command completion, Recon-ng provides a powerful environment in which open source web-based reconnaissance can be conducted, and we can gather all information."
},
{
"code": null,
"e": 31313,
"s": 31302,
"text": "mohdshariq"
},
{
"code": null,
"e": 31324,
"s": 31313,
"text": "Kali-Linux"
},
{
"code": null,
"e": 31331,
"s": 31324,
"text": "How To"
},
{
"code": null,
"e": 31342,
"s": 31331,
"text": "Linux-Unix"
},
{
"code": null,
"e": 31440,
"s": 31342,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31467,
"s": 31440,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 31515,
"s": 31467,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 31529,
"s": 31515,
"text": "Java Tutorial"
},
{
"code": null,
"e": 31563,
"s": 31529,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 31599,
"s": 31563,
"text": "How to Install Anaconda on Windows?"
},
{
"code": null,
"e": 31639,
"s": 31599,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 31679,
"s": 31639,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 31706,
"s": 31679,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 31741,
"s": 31706,
"text": "cut command in Linux with examples"
}
]
|
Rope Cutting | Practice | GeeksforGeeks | You are given N ropes. A cut operation is performed on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut operation until the length of each rope is zero.
Example 1:
Input : arr[ ] = {5, 1, 1, 2, 3, 5}
Output : 4 3 2
Explanation: In the first operation, the
minimum ropes are 1 So, we reduce length 1
from all of them after reducing we left with
4 ropes and we do the same for rest.
Example 2:
Input : arr[ ] = {5, 1, 6, 9, 8, 11, 2,
2, 6, 5}
Output : 9 7 5 3 2 1
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function longest_Subsequence() that takes an array (arr), sizeOfArray (n), and return the number of ropes that are left after each operation with space if no ropes left after one operation, in this case, return 0. The driver code takes care of the printing.
Expected Time Complexity: O(N*LOG(N)).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ N ≤ 105
0
sainithinssjcin 5 hours
class Solution{
// Function for finding maximum and value pair
public static ArrayList<Integer> RopeCutting (int arr[], int n) {
// Complete the Function
Arrays.sort(arr);
int k = n;
ArrayList<Integer> ans = new ArrayList<Integer>();
int count = 1;
int max= Integer.MIN_VALUE;
for(int i=0; i<n-1; i++){
if(arr[i] == arr[i+1]){
count++;
if(count>max){
max = count;
}
}else{
if(count>max){
max = count;
}
k = k - max;
ans.add(k);
count = 1;
max= 0;
}
}
return ans;
}
}
0
abhigyanpatek3 days ago
Simple C++ Solution:
We just need to check the number of remaining elements in every iteration after removing pointer from the minimum
vector<int> RopeCutting(int arr[], int n) { sort(arr, arr+n); vector<int> v; int i = 0; while(i < n){ int minimum = arr[i]; while(arr[i] == minimum) i++; int r = n-i; if(r != 0) v.push_back(r); } return v; }
0
arvind16yadav1 month ago
/*JAVA CODE*/
public static ArrayList<Integer> RopeCutting (int arr[], int n) { // Complete the Function ArrayList<Integer> ans = new ArrayList<>(); Arrays.sort(arr); int total = n; int freq = 1; int element = arr[0]; for(int i=1; i<n; i++){ if(arr[i] == element){ freq++; } else{ total -= freq; ans.add(total); freq = 1; element = arr[i]; } } return ans; }
0
s37randive1 month ago
vector<int> RopeCutting(int a[], int n)
{
// Complete the function
sort(a,a+n);
vector<int> ans;
int co,e,l=n;
for(int i=0;i<n;i++){
e=a[i];
co=0;
while(i<n && a[i]==e){
co+=1;
i++;
}
i--;
l-=co;
if(l==0){
break;
}
ans.push_back(l);
}
return ans;
}
0
rayalravi20013 months ago
c++ solution
vector<int> res; sort(arr,arr+n); int cut = arr[0]; for(int i=0; i<n; i++){ if(arr[i]-cut >0 ){ res.push_back(n-i); } cut = arr[i]; } return res;
0
mohankumarit20013 months ago
vector<int> RopeCutting(int arr[], int n)
{
// Complete the function
vector<int> res;
priority_queue<int,vector<int>,greater<int>> q(arr,arr+n);
while(!q.empty()){
int cut = q.top();q.pop();
priority_queue<int,vector<int>,greater<int>> temp;
while(!q.empty()){
int val = q.top()-cut;q.pop();
if(val)temp.push(val);
}
if(temp.size())res.push_back(temp.size());
q = temp;
}
return res;
}
0
anannyagta4 months ago
ArrayList<Integer> list = new ArrayList<>();
Arrays.sort(arr);
for(int i=0; i<n-1; i++)
{
if(arr[i]!=arr[i+1])
{
list.add(n-i-1);
}
}
return list;
0
manishkumar04 months ago
public static ArrayList<Integer> RopeCutting (int arr[], int n) {
ArrayList<Integer>res=new ArrayList<>();
Arrays.sort(arr);
int cuttingLen=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i]-cuttingLen>0)
{
res.add(n-i);
cuttingLen+=arr[i]-cuttingLen;
}
}
return res;
}
0
chessnoobdj4 months ago
C++
vector<int> RopeCutting(int arr[], int n)
{
vector <int> res;
sort(arr, arr+n);
int cnt = 0, i=0;
while(i<n){
while(i<n-1 && arr[i] == arr[i+1]){
i += 1;
cnt += 1;
}
cnt += 1;
res.push_back(n-cnt);
i += 1;
}
res.pop_back();
return res;
}
-5
neznajko7 months ago
0.7/5.9 Python
class Solution:
def RopeCutting( self, arr, n):
arr = sorted( arr)
res = []
# add guardian
arr.append( 0) # no negative length ropes
i, j = 0, 1
while True:
while arr[ j] == arr[ i]: j += 1
if j == n: break
res.append( n - j)
i = j
j += 1
return res
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 467,
"s": 238,
"text": "You are given N ropes. A cut operation is performed on ropes such that all of them are reduced by the length of the smallest rope. Display the number of ropes left after every cut operation until the length of each rope is zero."
},
{
"code": null,
"e": 478,
"s": 467,
"text": "Example 1:"
},
{
"code": null,
"e": 701,
"s": 478,
"text": "Input : arr[ ] = {5, 1, 1, 2, 3, 5} \nOutput : 4 3 2 \nExplanation: In the first operation, the \nminimum ropes are 1 So, we reduce length 1 \nfrom all of them after reducing we left with \n4 ropes and we do the same for rest. "
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Example 2:"
},
{
"code": null,
"e": 818,
"s": 714,
"text": "Input : arr[ ] = {5, 1, 6, 9, 8, 11, 2, \n 2, 6, 5} \nOutput : 9 7 5 3 2 1"
},
{
"code": null,
"e": 1202,
"s": 818,
"text": "\n\nYour Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function longest_Subsequence() that takes an array (arr), sizeOfArray (n), and return the number of ropes that are left after each operation with space if no ropes left after one operation, in this case, return 0. The driver code takes care of the printing."
},
{
"code": null,
"e": 1273,
"s": 1202,
"text": "Expected Time Complexity: O(N*LOG(N)).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 1288,
"s": 1275,
"text": "Constraints:"
},
{
"code": null,
"e": 1300,
"s": 1288,
"text": "1 ≤ N ≤ 105"
},
{
"code": null,
"e": 1302,
"s": 1300,
"text": "0"
},
{
"code": null,
"e": 1326,
"s": 1302,
"text": "sainithinssjcin 5 hours"
},
{
"code": null,
"e": 2102,
"s": 1326,
"text": "class Solution{\n \n // Function for finding maximum and value pair\n public static ArrayList<Integer> RopeCutting (int arr[], int n) {\n // Complete the Function\n Arrays.sort(arr);\n int k = n;\n ArrayList<Integer> ans = new ArrayList<Integer>();\n int count = 1;\n int max= Integer.MIN_VALUE;\n for(int i=0; i<n-1; i++){\n if(arr[i] == arr[i+1]){\n count++;\n if(count>max){\n max = count;\n }\n }else{\n if(count>max){\n max = count;\n }\n k = k - max;\n ans.add(k);\n count = 1;\n max= 0;\n }\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 2104,
"s": 2102,
"text": "0"
},
{
"code": null,
"e": 2128,
"s": 2104,
"text": "abhigyanpatek3 days ago"
},
{
"code": null,
"e": 2149,
"s": 2128,
"text": "Simple C++ Solution:"
},
{
"code": null,
"e": 2264,
"s": 2149,
"text": "We just need to check the number of remaining elements in every iteration after removing pointer from the minimum "
},
{
"code": null,
"e": 2600,
"s": 2264,
"text": "vector<int> RopeCutting(int arr[], int n) { sort(arr, arr+n); vector<int> v; int i = 0; while(i < n){ int minimum = arr[i]; while(arr[i] == minimum) i++; int r = n-i; if(r != 0) v.push_back(r); } return v; }"
},
{
"code": null,
"e": 2602,
"s": 2600,
"text": "0"
},
{
"code": null,
"e": 2627,
"s": 2602,
"text": "arvind16yadav1 month ago"
},
{
"code": null,
"e": 2641,
"s": 2627,
"text": "/*JAVA CODE*/"
},
{
"code": null,
"e": 3186,
"s": 2641,
"text": "public static ArrayList<Integer> RopeCutting (int arr[], int n) { // Complete the Function ArrayList<Integer> ans = new ArrayList<>(); Arrays.sort(arr); int total = n; int freq = 1; int element = arr[0]; for(int i=1; i<n; i++){ if(arr[i] == element){ freq++; } else{ total -= freq; ans.add(total); freq = 1; element = arr[i]; } } return ans; }"
},
{
"code": null,
"e": 3188,
"s": 3186,
"text": "0"
},
{
"code": null,
"e": 3210,
"s": 3188,
"text": "s37randive1 month ago"
},
{
"code": null,
"e": 3658,
"s": 3210,
"text": "vector<int> RopeCutting(int a[], int n)\n {\n // Complete the function\n sort(a,a+n);\n vector<int> ans;\n int co,e,l=n;\n for(int i=0;i<n;i++){\n e=a[i];\n co=0;\n while(i<n && a[i]==e){\n co+=1;\n i++;\n }\n i--;\n l-=co;\n if(l==0){\n break;\n }\n ans.push_back(l);\n }\n return ans;\n }"
},
{
"code": null,
"e": 3660,
"s": 3658,
"text": "0"
},
{
"code": null,
"e": 3686,
"s": 3660,
"text": "rayalravi20013 months ago"
},
{
"code": null,
"e": 3699,
"s": 3686,
"text": "c++ solution"
},
{
"code": null,
"e": 3939,
"s": 3701,
"text": " vector<int> res; sort(arr,arr+n); int cut = arr[0]; for(int i=0; i<n; i++){ if(arr[i]-cut >0 ){ res.push_back(n-i); } cut = arr[i]; } return res;"
},
{
"code": null,
"e": 3941,
"s": 3939,
"text": "0"
},
{
"code": null,
"e": 3970,
"s": 3941,
"text": "mohankumarit20013 months ago"
},
{
"code": null,
"e": 4538,
"s": 3970,
"text": " vector<int> RopeCutting(int arr[], int n)\n {\n // Complete the function\n vector<int> res;\n priority_queue<int,vector<int>,greater<int>> q(arr,arr+n);\n while(!q.empty()){\n int cut = q.top();q.pop();\n priority_queue<int,vector<int>,greater<int>> temp;\n while(!q.empty()){\n int val = q.top()-cut;q.pop();\n if(val)temp.push(val);\n }\n if(temp.size())res.push_back(temp.size());\n q = temp;\n }\n return res;\n \n \n }"
},
{
"code": null,
"e": 4540,
"s": 4538,
"text": "0"
},
{
"code": null,
"e": 4563,
"s": 4540,
"text": "anannyagta4 months ago"
},
{
"code": null,
"e": 4803,
"s": 4563,
"text": " ArrayList<Integer> list = new ArrayList<>();\n Arrays.sort(arr);\n for(int i=0; i<n-1; i++)\n {\n if(arr[i]!=arr[i+1])\n {\n list.add(n-i-1);\n }\n }\n return list;"
},
{
"code": null,
"e": 4805,
"s": 4803,
"text": "0"
},
{
"code": null,
"e": 4830,
"s": 4805,
"text": "manishkumar04 months ago"
},
{
"code": null,
"e": 5231,
"s": 4830,
"text": "public static ArrayList<Integer> RopeCutting (int arr[], int n) {\n ArrayList<Integer>res=new ArrayList<>();\n Arrays.sort(arr);\n int cuttingLen=arr[0];\n for(int i=0;i<n;i++)\n {\n if(arr[i]-cuttingLen>0)\n {\n res.add(n-i);\n cuttingLen+=arr[i]-cuttingLen;\n }\n \n }\n return res;\n }"
},
{
"code": null,
"e": 5233,
"s": 5231,
"text": "0"
},
{
"code": null,
"e": 5257,
"s": 5233,
"text": "chessnoobdj4 months ago"
},
{
"code": null,
"e": 5261,
"s": 5257,
"text": "C++"
},
{
"code": null,
"e": 5655,
"s": 5261,
"text": "vector<int> RopeCutting(int arr[], int n)\n {\n vector <int> res;\n sort(arr, arr+n);\n int cnt = 0, i=0;\n while(i<n){\n while(i<n-1 && arr[i] == arr[i+1]){\n i += 1;\n cnt += 1;\n }\n cnt += 1;\n res.push_back(n-cnt);\n i += 1;\n }\n res.pop_back();\n return res;\n }"
},
{
"code": null,
"e": 5658,
"s": 5655,
"text": "-5"
},
{
"code": null,
"e": 5679,
"s": 5658,
"text": "neznajko7 months ago"
},
{
"code": null,
"e": 5694,
"s": 5679,
"text": "0.7/5.9 Python"
},
{
"code": null,
"e": 6064,
"s": 5694,
"text": "class Solution:\n def RopeCutting( self, arr, n):\n arr = sorted( arr)\n res = []\n # add guardian\n arr.append( 0) # no negative length ropes\n i, j = 0, 1\n while True:\n while arr[ j] == arr[ i]: j += 1\n if j == n: break\n res.append( n - j)\n i = j\n j += 1\n return res"
},
{
"code": null,
"e": 6210,
"s": 6064,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6246,
"s": 6210,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6256,
"s": 6246,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6266,
"s": 6256,
"text": "\nContest\n"
},
{
"code": null,
"e": 6329,
"s": 6266,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6477,
"s": 6329,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6685,
"s": 6477,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6791,
"s": 6685,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
p5.js | getURL() Function - GeeksforGeeks | 09 Jul, 2019
The getURL() function in p5.js is used to return the current URL.
Syntax:
getURL()
Parameters: This function does not accept any parameter.
Return Value: It returns the current URL string.
Below program illustrates the getURL() function in p5.js:
Example:
// Declare a URL variablelet url; // Function to set the height and// width of windowfunction setup() { createCanvas(350, 200); // Use getURL() function to // get the current URL url = getURL();} function draw() { // Set the background color background(0, 200, 0); // Set the font-size textSize(30); // Set the text alignment textAlign(LEFT); text(url, 100, height / 2);}
Output:
Reference: https://p5js.org/reference/#/p5/getURL
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26627,
"s": 26599,
"text": "\n09 Jul, 2019"
},
{
"code": null,
"e": 26693,
"s": 26627,
"text": "The getURL() function in p5.js is used to return the current URL."
},
{
"code": null,
"e": 26701,
"s": 26693,
"text": "Syntax:"
},
{
"code": null,
"e": 26710,
"s": 26701,
"text": "getURL()"
},
{
"code": null,
"e": 26767,
"s": 26710,
"text": "Parameters: This function does not accept any parameter."
},
{
"code": null,
"e": 26816,
"s": 26767,
"text": "Return Value: It returns the current URL string."
},
{
"code": null,
"e": 26874,
"s": 26816,
"text": "Below program illustrates the getURL() function in p5.js:"
},
{
"code": null,
"e": 26883,
"s": 26874,
"text": "Example:"
},
{
"code": "// Declare a URL variablelet url; // Function to set the height and// width of windowfunction setup() { createCanvas(350, 200); // Use getURL() function to // get the current URL url = getURL();} function draw() { // Set the background color background(0, 200, 0); // Set the font-size textSize(30); // Set the text alignment textAlign(LEFT); text(url, 100, height / 2);}",
"e": 27315,
"s": 26883,
"text": null
},
{
"code": null,
"e": 27323,
"s": 27315,
"text": "Output:"
},
{
"code": null,
"e": 27373,
"s": 27323,
"text": "Reference: https://p5js.org/reference/#/p5/getURL"
},
{
"code": null,
"e": 27390,
"s": 27373,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27401,
"s": 27390,
"text": "JavaScript"
},
{
"code": null,
"e": 27418,
"s": 27401,
"text": "Web Technologies"
},
{
"code": null,
"e": 27516,
"s": 27418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27556,
"s": 27516,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27617,
"s": 27556,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27658,
"s": 27617,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27680,
"s": 27658,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 27734,
"s": 27680,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27774,
"s": 27734,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27807,
"s": 27774,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27850,
"s": 27807,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27912,
"s": 27850,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
JQuery | isEmptyObject() method - GeeksforGeeks | 27 Apr, 2020
This isEmptyObject() Method in jQuery is used to determines if an object is empty.
Syntax:
jQuery.isEmptyObject( object )
Parameters: The isEmptyObject() method accepts only one parameter that is mentioned above and described below:
object : This parameter is the object that will be checked to see if it’s empty.
Return Value: It returns the boolean value.
Below examples illustrate the use of isEmptyObject() method in jQuery:
Example 1: In this example, the isEmptyObject() method checks an object to see if it’s empty.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | isEmptyObject() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | isEmptyObject() method</h3> <b>Whether '{}' is a Empty Object : </b> <p></p> <script> $( "p" ).append( "" + $.isEmptyObject({})); </script></body></html>
Output:
Example 2: In this example, the isEmptyObject() method also checks an object to see if it’s empty.
<!DOCTYPE html><html><head><meta charset="utf-8"><title>JQuery | isEmptyObject() method</title> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> </head><body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <h3>JQuery | isEmptyObject() method</h3> <b>Whether String is a Empty Object : </b> <p id ="gfg"></p> <b>Whether Array is a Empty Object : </b> <p id ="gfg1"></p> <script> // string ="Shubham" $( "#gfg" ).append( "Shubham : " + $.isEmptyObject("Shubham")); // array $( "#gfg1" ).append( "[1, 3, 4, 6, 8] : " + $.isEmptyObject([1, 3, 4, 6, 8])); </script></body></html>
Output:
jQuery-Misc
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 26442,
"s": 26414,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 26525,
"s": 26442,
"text": "This isEmptyObject() Method in jQuery is used to determines if an object is empty."
},
{
"code": null,
"e": 26533,
"s": 26525,
"text": "Syntax:"
},
{
"code": null,
"e": 26565,
"s": 26533,
"text": "jQuery.isEmptyObject( object )\n"
},
{
"code": null,
"e": 26676,
"s": 26565,
"text": "Parameters: The isEmptyObject() method accepts only one parameter that is mentioned above and described below:"
},
{
"code": null,
"e": 26757,
"s": 26676,
"text": "object : This parameter is the object that will be checked to see if it’s empty."
},
{
"code": null,
"e": 26801,
"s": 26757,
"text": "Return Value: It returns the boolean value."
},
{
"code": null,
"e": 26872,
"s": 26801,
"text": "Below examples illustrate the use of isEmptyObject() method in jQuery:"
},
{
"code": null,
"e": 26966,
"s": 26872,
"text": "Example 1: In this example, the isEmptyObject() method checks an object to see if it’s empty."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | isEmptyObject() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | isEmptyObject() method</h3> <b>Whether '{}' is a Empty Object : </b> <p></p> <script> $( \"p\" ).append( \"\" + $.isEmptyObject({})); </script></body></html> ",
"e": 27506,
"s": 26966,
"text": null
},
{
"code": null,
"e": 27514,
"s": 27506,
"text": "Output:"
},
{
"code": null,
"e": 27613,
"s": 27514,
"text": "Example 2: In this example, the isEmptyObject() method also checks an object to see if it’s empty."
},
{
"code": "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>JQuery | isEmptyObject() method</title> <script src=\"https://code.jquery.com/jquery-3.4.1.js\"></script> </head><body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <h3>JQuery | isEmptyObject() method</h3> <b>Whether String is a Empty Object : </b> <p id =\"gfg\"></p> <b>Whether Array is a Empty Object : </b> <p id =\"gfg1\"></p> <script> // string =\"Shubham\" $( \"#gfg\" ).append( \"Shubham : \" + $.isEmptyObject(\"Shubham\")); // array $( \"#gfg1\" ).append( \"[1, 3, 4, 6, 8] : \" + $.isEmptyObject([1, 3, 4, 6, 8])); </script></body></html> ",
"e": 28426,
"s": 27613,
"text": null
},
{
"code": null,
"e": 28434,
"s": 28426,
"text": "Output:"
},
{
"code": null,
"e": 28446,
"s": 28434,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28453,
"s": 28446,
"text": "JQuery"
},
{
"code": null,
"e": 28470,
"s": 28453,
"text": "Web Technologies"
},
{
"code": null,
"e": 28568,
"s": 28470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28597,
"s": 28568,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28653,
"s": 28597,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 28707,
"s": 28653,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 28741,
"s": 28707,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 28796,
"s": 28741,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 28836,
"s": 28796,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28869,
"s": 28836,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28914,
"s": 28869,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28957,
"s": 28914,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Deconstructing Interpreter: Understanding Behind the Python Bytecode - GeeksforGeeks | 10 May, 2020
When the CPython interpreter executes your program, it first translates onto a sequence of bytecode instructions. Bytecode is an intermediate language for the Python virtual machine that’s used as a performance optimization.
Instead of directly executing the human-readable source code, compact numeric codes, constants, and references are used that represent the result of compiler parsing and semantic analysis. This saves time and memory for repeated executions of programs or part of programs. For example, the bytecode resulting from this compilation step is cached on disk in .pyc and .pyo files so that executing the same Python file is faster the second time around. All of this is completely transparent to the programmer. You don’t have to be aware that this intermediate translation step happens, or how the Python virtual machine deals with the bytecode. In fact, the bytecode format is deemed an implementation detail and not guaranteed to remain stable or compatible between Python versions. And yet, one may find it very enlightening to see how the sausage is made and to peek behind the abstractions provided by the CPython interpreter. Understanding at least some of the inner workings can help you write more performant code.
Example: Let’s take this simple showMeByte() function as a lab sample and Understand’s Python’s bytecode:
def showMeByte(name): return "hello "+name+" !!!" print(showMeByte("amit kumra"))
Output:
hello amit kumra !!!
CPython first translates our source code into an intermediate language before it runs it. We can see the results of this compilation step. Each function has a __code__ attribute(in Python 3) that we can use to get at the virtual machine instructions, constants, and variables used by our showMeByte function:
Example:
def showMeByte(name): return "hello "+name+" !!!" print(showMeByte.__code__.co_code) print(showMeByte.__code__.co_consts) print(showMeByte.__code__.co_stacksize) print(showMeByte.__code__.co_varnames) print(showMeByte.__code__.co_flags) print(showMeByte.__code__.co_name) print(showMeByte.__code__.co_names)
Output:
b'd\x01|\x00\x17\x00d\x02\x17\x00S\x00'
(None, 'hello ', ' !!!')
2
('name',)
67
showMeByte
()
You can see co_consts contains parts of the greeting string our function assembles. Constants and code are kept separate to save memory space. So instead of repeating the actual constant values in the co_code instruction stream, Python stores constants separately in a lookup table. The instruction stream can then refer to a constant with an index into the lookup table. The same is true for variables stored in the co_varnames field. CPython developers gave us another tool called a disassembler to make inspecting the bytecode easier. Python’s bytecode disassembler lives in the dis module that’s part of the standard library. So we can just import it and call dis.dis() on our greet function to get a slightly easier-to-read representation of its bytecode:
Example:
import dis def showMeByte(name): return "hello "+name+" !!!" dis.dis(showMeByte)bytecode = dis.code_info(showMeByte)print(bytecode) bytecode = dis.Bytecode(showMeByte)print(bytecode) for i in bytecode: print(i)
Output:
The executable instructions or simple instructions tell the processor what to do. Each instruction consists of an operation code (opcode). Each executable instruction generates one machine language instruction. The main thing disassembling did was split up the instruction stream and give each opcode in it a human-readable name like LOAD_CONST. You can also see how constant and variable references are now interleaved with the bytecode and printed in full to spare us the mental gymnastics of a co_const and co_varnames table lookup.
It first retrieves the constant at index 1(‘Hello’) and puts it on the stack. It then loads the contents of the name variable and also puts them on the stack. The stack is the data structure used as internal working storage for the virtual machine. There are different classes of virtual machines and one of them is called a stack machine. CPython’s virtual machine is an implementation of such a stack machine. CPython’s virtual machine is an implementation of such a stack machine. Let’s assume the stack starts out empty. After the first two opcodes have been executed, this is what contents of the VM look like(0 is the topmost element):
0: ’amit kumra’(contents of “name”)
1: ‘hello ‘
The BINARY_ADD instruction pops the two string values off the stack, concatenation them, and then pushes the result on the stack again:
0: ‘hello amit kumra’
Then there’s another LOAD_CONST to get the exclamation mark string on the stack:
0 : ‘ !!!’
1:’Hello amit kumra’
The next BINARY_ADD opcode again combines the two to generate the final greeting string:
0: ‘hello amit kumra !!!’
The last bytecode instruction is RETURN_VALUE which tells the virtual machine that what’s currently on top of the stack is the return value for this function so it can be passed on to the caller. So, finally, we traced back how our showMeCode() function gets executed internally by the CPython virtual machine.
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Factory method design pattern in Java | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 25788,
"s": 25563,
"text": "When the CPython interpreter executes your program, it first translates onto a sequence of bytecode instructions. Bytecode is an intermediate language for the Python virtual machine that’s used as a performance optimization."
},
{
"code": null,
"e": 26807,
"s": 25788,
"text": "Instead of directly executing the human-readable source code, compact numeric codes, constants, and references are used that represent the result of compiler parsing and semantic analysis. This saves time and memory for repeated executions of programs or part of programs. For example, the bytecode resulting from this compilation step is cached on disk in .pyc and .pyo files so that executing the same Python file is faster the second time around. All of this is completely transparent to the programmer. You don’t have to be aware that this intermediate translation step happens, or how the Python virtual machine deals with the bytecode. In fact, the bytecode format is deemed an implementation detail and not guaranteed to remain stable or compatible between Python versions. And yet, one may find it very enlightening to see how the sausage is made and to peek behind the abstractions provided by the CPython interpreter. Understanding at least some of the inner workings can help you write more performant code."
},
{
"code": null,
"e": 26913,
"s": 26807,
"text": "Example: Let’s take this simple showMeByte() function as a lab sample and Understand’s Python’s bytecode:"
},
{
"code": "def showMeByte(name): return \"hello \"+name+\" !!!\" print(showMeByte(\"amit kumra\"))",
"e": 27001,
"s": 26913,
"text": null
},
{
"code": null,
"e": 27009,
"s": 27001,
"text": "Output:"
},
{
"code": null,
"e": 27030,
"s": 27009,
"text": "hello amit kumra !!!"
},
{
"code": null,
"e": 27339,
"s": 27030,
"text": "CPython first translates our source code into an intermediate language before it runs it. We can see the results of this compilation step. Each function has a __code__ attribute(in Python 3) that we can use to get at the virtual machine instructions, constants, and variables used by our showMeByte function:"
},
{
"code": null,
"e": 27348,
"s": 27339,
"text": "Example:"
},
{
"code": "def showMeByte(name): return \"hello \"+name+\" !!!\" print(showMeByte.__code__.co_code) print(showMeByte.__code__.co_consts) print(showMeByte.__code__.co_stacksize) print(showMeByte.__code__.co_varnames) print(showMeByte.__code__.co_flags) print(showMeByte.__code__.co_name) print(showMeByte.__code__.co_names)",
"e": 27668,
"s": 27348,
"text": null
},
{
"code": null,
"e": 27676,
"s": 27668,
"text": "Output:"
},
{
"code": null,
"e": 27770,
"s": 27676,
"text": "b'd\\x01|\\x00\\x17\\x00d\\x02\\x17\\x00S\\x00'\n(None, 'hello ', ' !!!')\n2\n('name',)\n67\nshowMeByte\n()"
},
{
"code": null,
"e": 28531,
"s": 27770,
"text": "You can see co_consts contains parts of the greeting string our function assembles. Constants and code are kept separate to save memory space. So instead of repeating the actual constant values in the co_code instruction stream, Python stores constants separately in a lookup table. The instruction stream can then refer to a constant with an index into the lookup table. The same is true for variables stored in the co_varnames field. CPython developers gave us another tool called a disassembler to make inspecting the bytecode easier. Python’s bytecode disassembler lives in the dis module that’s part of the standard library. So we can just import it and call dis.dis() on our greet function to get a slightly easier-to-read representation of its bytecode:"
},
{
"code": null,
"e": 28540,
"s": 28531,
"text": "Example:"
},
{
"code": "import dis def showMeByte(name): return \"hello \"+name+\" !!!\" dis.dis(showMeByte)bytecode = dis.code_info(showMeByte)print(bytecode) bytecode = dis.Bytecode(showMeByte)print(bytecode) for i in bytecode: print(i)",
"e": 28763,
"s": 28540,
"text": null
},
{
"code": null,
"e": 28771,
"s": 28763,
"text": "Output:"
},
{
"code": null,
"e": 29307,
"s": 28771,
"text": "The executable instructions or simple instructions tell the processor what to do. Each instruction consists of an operation code (opcode). Each executable instruction generates one machine language instruction. The main thing disassembling did was split up the instruction stream and give each opcode in it a human-readable name like LOAD_CONST. You can also see how constant and variable references are now interleaved with the bytecode and printed in full to spare us the mental gymnastics of a co_const and co_varnames table lookup."
},
{
"code": null,
"e": 29949,
"s": 29307,
"text": "It first retrieves the constant at index 1(‘Hello’) and puts it on the stack. It then loads the contents of the name variable and also puts them on the stack. The stack is the data structure used as internal working storage for the virtual machine. There are different classes of virtual machines and one of them is called a stack machine. CPython’s virtual machine is an implementation of such a stack machine. CPython’s virtual machine is an implementation of such a stack machine. Let’s assume the stack starts out empty. After the first two opcodes have been executed, this is what contents of the VM look like(0 is the topmost element):"
},
{
"code": null,
"e": 29997,
"s": 29949,
"text": "0: ’amit kumra’(contents of “name”)\n1: ‘hello ‘"
},
{
"code": null,
"e": 30133,
"s": 29997,
"text": "The BINARY_ADD instruction pops the two string values off the stack, concatenation them, and then pushes the result on the stack again:"
},
{
"code": null,
"e": 30155,
"s": 30133,
"text": "0: ‘hello amit kumra’"
},
{
"code": null,
"e": 30236,
"s": 30155,
"text": "Then there’s another LOAD_CONST to get the exclamation mark string on the stack:"
},
{
"code": null,
"e": 30268,
"s": 30236,
"text": "0 : ‘ !!!’\n1:’Hello amit kumra’"
},
{
"code": null,
"e": 30357,
"s": 30268,
"text": "The next BINARY_ADD opcode again combines the two to generate the final greeting string:"
},
{
"code": null,
"e": 30383,
"s": 30357,
"text": "0: ‘hello amit kumra !!!’"
},
{
"code": null,
"e": 30694,
"s": 30383,
"text": "The last bytecode instruction is RETURN_VALUE which tells the virtual machine that what’s currently on top of the stack is the return value for this function so it can be passed on to the caller. So, finally, we traced back how our showMeCode() function gets executed internally by the CPython virtual machine."
},
{
"code": null,
"e": 30701,
"s": 30694,
"text": "Python"
},
{
"code": null,
"e": 30717,
"s": 30701,
"text": "Write From Home"
},
{
"code": null,
"e": 30815,
"s": 30717,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30847,
"s": 30815,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30889,
"s": 30847,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30931,
"s": 30889,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30958,
"s": 30931,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31014,
"s": 30958,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31050,
"s": 31014,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 31111,
"s": 31050,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31127,
"s": 31111,
"text": "Python infinity"
},
{
"code": null,
"e": 31163,
"s": 31127,
"text": "Matplotlib.pyplot.title() in Python"
}
]
|
Instant parse() method in Java with Examples - GeeksforGeeks | 28 Nov, 2018
The parse() method of Instant class help to get an instance of Instant from a string value passed as parameter. This string is an instant in the UTC time zone. It is parsed using DateTimeFormatter.ISO_INSTANT.
Syntax:
public static Instant
parse(CharSequence text)
Parameters: This method accepts one parameter text which is the text to parse in instant. It should not be null.
Returns: This method returns an Instant which is the valid instant in the UTC time xone of the String passed as the parameter.
Exception: This method throws DateTimeException if the text cannot be parsed.
Below programs illustrate the parse() method:
Program 1:
// Java program to demonstrate// Instant.parse() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using parse method Instant instant = Instant.parse("2018-11-30T18:35:24.00Z"); // print result System.out.println("Instant: " + instant); }}
Instant: 2018-11-30T18:35:24Z
Program 2:
// Java program to demonstrate// Instant.parse() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using parse method Instant instant = Instant.parse("2019-10-01T08:25:24.00Z"); // print result System.out.println("Instant: " + instant); }}
Instant: 2019-10-01T08:25:24Z
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#parse(java.lang.CharSequence)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25797,
"s": 25769,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 26007,
"s": 25797,
"text": "The parse() method of Instant class help to get an instance of Instant from a string value passed as parameter. This string is an instant in the UTC time zone. It is parsed using DateTimeFormatter.ISO_INSTANT."
},
{
"code": null,
"e": 26015,
"s": 26007,
"text": "Syntax:"
},
{
"code": null,
"e": 26067,
"s": 26015,
"text": "public static Instant \n parse(CharSequence text)"
},
{
"code": null,
"e": 26180,
"s": 26067,
"text": "Parameters: This method accepts one parameter text which is the text to parse in instant. It should not be null."
},
{
"code": null,
"e": 26307,
"s": 26180,
"text": "Returns: This method returns an Instant which is the valid instant in the UTC time xone of the String passed as the parameter."
},
{
"code": null,
"e": 26385,
"s": 26307,
"text": "Exception: This method throws DateTimeException if the text cannot be parsed."
},
{
"code": null,
"e": 26431,
"s": 26385,
"text": "Below programs illustrate the parse() method:"
},
{
"code": null,
"e": 26442,
"s": 26431,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// Instant.parse() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using parse method Instant instant = Instant.parse(\"2018-11-30T18:35:24.00Z\"); // print result System.out.println(\"Instant: \" + instant); }}",
"e": 26814,
"s": 26442,
"text": null
},
{
"code": null,
"e": 26845,
"s": 26814,
"text": "Instant: 2018-11-30T18:35:24Z\n"
},
{
"code": null,
"e": 26856,
"s": 26845,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Instant.parse() method import java.time.*; public class GFG { public static void main(String[] args) { // get Instant using parse method Instant instant = Instant.parse(\"2019-10-01T08:25:24.00Z\"); // print result System.out.println(\"Instant: \" + instant); }}",
"e": 27228,
"s": 26856,
"text": null
},
{
"code": null,
"e": 27259,
"s": 27228,
"text": "Instant: 2019-10-01T08:25:24Z\n"
},
{
"code": null,
"e": 27367,
"s": 27259,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#parse(java.lang.CharSequence)"
},
{
"code": null,
"e": 27382,
"s": 27367,
"text": "Java-Functions"
},
{
"code": null,
"e": 27395,
"s": 27382,
"text": "Java-Instant"
},
{
"code": null,
"e": 27413,
"s": 27395,
"text": "Java-time package"
},
{
"code": null,
"e": 27418,
"s": 27413,
"text": "Java"
},
{
"code": null,
"e": 27423,
"s": 27418,
"text": "Java"
},
{
"code": null,
"e": 27521,
"s": 27423,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27572,
"s": 27521,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27602,
"s": 27572,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27621,
"s": 27602,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27636,
"s": 27621,
"text": "Stream In Java"
},
{
"code": null,
"e": 27667,
"s": 27636,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27685,
"s": 27667,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27717,
"s": 27685,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27737,
"s": 27717,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27769,
"s": 27737,
"text": "Multidimensional Arrays in Java"
}
]
|
Python | Find maximum length sub-list in a nested list - GeeksforGeeks | 19 Feb, 2019
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length).
Examples:
Input : [['A'], ['A', 'B'], ['A', 'B', 'C']]
Output : (['A', 'B', 'C'], 3)
Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]]
Output : ([1, 2, 3, 9, 4], 5)
Let’s discuss different approaches to solve this problem.
Approach #1 : Using for loop (Naive)This is a brute force method in which we iterate through each list item(list) and find the list with maximum length. Similarly, we use the for loop to find length of each list and output the maximum length.
# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max((x) for x in lst) maxLength = max(len(x) for x in lst ) return maxList, maxLength # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)
Approach #2 : Using mapIn this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function.
# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max(lst, key = len) maxLength = max(map(len, lst)) return maxList, maxLength # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C'], ]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)
Approach #3 : Using lambda operatorOne more method in Python to find the longest length list is the lambda operator. It is used for creating small, one-time and anonymous function objects in Python. Here we pass a variable i as argument in the len(i) expression and find the maximum length.
# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max(lst, key = lambda i: len(i)) maxLength = len(maxList) return maxList, maxLength# Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))
(['A', 'B', 'C'], 3)
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n19 Feb, 2019"
},
{
"code": null,
"e": 26233,
"s": 26095,
"text": "Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length)."
},
{
"code": null,
"e": 26243,
"s": 26233,
"text": "Examples:"
},
{
"code": null,
"e": 26394,
"s": 26243,
"text": "Input : [['A'], ['A', 'B'], ['A', 'B', 'C']]\nOutput : (['A', 'B', 'C'], 3)\n\nInput : [[1, 2, 3, 9, 4], [5], [3, 8], [2]]\nOutput : ([1, 2, 3, 9, 4], 5)\n"
},
{
"code": null,
"e": 26453,
"s": 26394,
"text": " Let’s discuss different approaches to solve this problem."
},
{
"code": null,
"e": 26696,
"s": 26453,
"text": "Approach #1 : Using for loop (Naive)This is a brute force method in which we iterate through each list item(list) and find the list with maximum length. Similarly, we use the for loop to find length of each list and output the maximum length."
},
{
"code": "# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max((x) for x in lst) maxLength = max(len(x) for x in lst ) return maxList, maxLength # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))",
"e": 26979,
"s": 26696,
"text": null
},
{
"code": null,
"e": 27001,
"s": 26979,
"text": "(['A', 'B', 'C'], 3)\n"
},
{
"code": null,
"e": 27168,
"s": 27001,
"text": " Approach #2 : Using mapIn this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function."
},
{
"code": "# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max(lst, key = len) maxLength = max(map(len, lst)) return maxList, maxLength # Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C'], ]print(FindMaxLength(lst))",
"e": 27444,
"s": 27168,
"text": null
},
{
"code": null,
"e": 27466,
"s": 27444,
"text": "(['A', 'B', 'C'], 3)\n"
},
{
"code": null,
"e": 27758,
"s": 27466,
"text": " Approach #3 : Using lambda operatorOne more method in Python to find the longest length list is the lambda operator. It is used for creating small, one-time and anonymous function objects in Python. Here we pass a variable i as argument in the len(i) expression and find the maximum length."
},
{
"code": "# Python3 program to Find maximum # length list in a nested list def FindMaxLength(lst): maxList = max(lst, key = lambda i: len(i)) maxLength = len(maxList) return maxList, maxLength# Driver Codelst = [['A'], ['A', 'B'], ['A', 'B', 'C']]print(FindMaxLength(lst))",
"e": 28037,
"s": 27758,
"text": null
},
{
"code": null,
"e": 28059,
"s": 28037,
"text": "(['A', 'B', 'C'], 3)\n"
},
{
"code": null,
"e": 28080,
"s": 28059,
"text": "Python list-programs"
},
{
"code": null,
"e": 28092,
"s": 28080,
"text": "python-list"
},
{
"code": null,
"e": 28099,
"s": 28092,
"text": "Python"
},
{
"code": null,
"e": 28115,
"s": 28099,
"text": "Python Programs"
},
{
"code": null,
"e": 28127,
"s": 28115,
"text": "python-list"
},
{
"code": null,
"e": 28225,
"s": 28127,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28243,
"s": 28225,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28275,
"s": 28243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28297,
"s": 28275,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28339,
"s": 28297,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28365,
"s": 28339,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28387,
"s": 28365,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28433,
"s": 28387,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28471,
"s": 28433,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 28511,
"s": 28471,
"text": "How to print without newline in Python?"
}
]
|
Maximise the number of toys that can be purchased with amount K using min Heap - GeeksforGeeks | 05 May, 2022
Given an array arr[] consisting of the cost of toys and an integer K depicting the amount of money available to purchase toys. The task is to find the maximum number of toys one can buy with the amount K.Note: One can buy only 1 quantity of a particular toy.
Examples:
Input: arr[] = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15}, K = 50 Output: 6 Toys with amount 1, 5, 9, 10, 12, and 12 can be purchased resulting in a total amount of 49. Hence, the maximum number of toys are 6.
Input: arr[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4
Approach: Insert all the elements of the given array in a priority_queue now one by one remove elements from this priority queue and add these costs in a variable sum initialised to 0. Keep removing the elements while the new addition keep the sum smaller than K. In the end, the count of elements removed will be the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// maximum toys that can be boughtint maxToys(int arr[], int n, int k){ // Create a priority_queue and push // all the array elements in it priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < n; i++) { pq.push(arr[i]); } // To store the count of maximum // toys that can be bought int count = 0; while (pq.top() <= k) { count++; k = k - pq.top(); pq.pop(); } return count;} // Driver codeint main(){ int arr[] = { 1, 12, 5, 111, 200, 1000, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 50; cout << maxToys(arr, n, k); return 0;}
// Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to return the count of// maximum toys that can be bought public static int maxToys(int[] arr, int k){ int n = arr.length; // Create a priority_queue and push // all the array elements in it PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int i = 0; i < n; i++) { pq.offer(arr[i]); } // To store the count of maximum // toys that can be bought int count = 0; while (!pq.isEmpty() && pq.peek() <= k) { k = k - pq.poll(); count++; } return count;} // Driver codepublic static void main (String[] args){ int[] arr = new int[]{ 1, 12, 5, 111, 200, 1000, 10 }; int k = 50; System.out.println(maxToys(arr, k)); }} // This code is contributed by ankit bajpai
# Python3 implementation of the approach # Function to return the count of# maximum toys that can be bought # importing heapq moduleimport heapq def maxToys(arr, n, k): # Create a priority_queue and push # all the array elements in it pq = arr heapq.heapify(pq) # To store the count of maximum # toys that can be bought count = 0 while (pq[0] <= k): count += 1 k -= pq[0] # assigning last element of the min heap # to top of the heap pq[0] = pq[-1] # deleting the last element. pq.pop() # pq.pop() is an O(1) operation # maintaining the heap property again heapq.heapify(pq) return count # Driver codearr = [1, 12, 5, 111, 200, 1000, 10]n = len(arr)k = 50print(maxToys(arr, n, k))
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of // maximum toys that can be bought static int maxToys(int[] arr, int n, int k) { // Create a priority_queue and push // all the array elements in it List<int> pq = new List<int>(); for (int i = 0; i < n; i++) { pq.Add(arr[i]); } pq.Sort(); // To store the count of maximum // toys that can be bought int count = 0; while (pq[0] <= k) { count++; k = k - pq[0]; pq.RemoveAt(0); } return count; } // Driver code static void Main() { int[] arr = { 1, 12, 5, 111, 200, 1000, 10 }; int n = arr.Length; int k = 50; Console.WriteLine(maxToys(arr, n, k)); }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript implementation of the approach // Function to return the count of // maximum toys that can be bought function maxToys(arr, n, k) { // Create a priority_queue and push // all the array elements in it let pq = []; for (let i = 0; i < n; i++) { pq.push(arr[i]); } pq.sort(function(a, b){return a - b}); // To store the count of maximum // toys that can be bought let count = 0; while (pq[0] <= k) { count++; k = k - pq[0]; pq.shift(); } return count; } let arr = [ 1, 12, 5, 111, 200, 1000, 10 ]; let n = arr.length; let k = 50; document.write(maxToys(arr, n, k)); </script>
4
Time Complexity: O(N*logN)Auxiliary Space: O(N)
ankit bajpai
divyeshrabadiya07
divyesh072019
mukesh07
pankajsharmagfg
rajatkumargla19
priority-queue
Advanced Data Structure
Algorithms
Arrays
Heap
Arrays
Heap
priority-queue
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
Segment Tree | Set 1 (Sum of given range)
AVL Tree | Set 2 (Deletion)
Ordered Set and GNU C++ PBDS
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
How to write a Pseudo Code? | [
{
"code": null,
"e": 26335,
"s": 26307,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 26594,
"s": 26335,
"text": "Given an array arr[] consisting of the cost of toys and an integer K depicting the amount of money available to purchase toys. The task is to find the maximum number of toys one can buy with the amount K.Note: One can buy only 1 quantity of a particular toy."
},
{
"code": null,
"e": 26606,
"s": 26594,
"text": "Examples: "
},
{
"code": null,
"e": 26815,
"s": 26606,
"text": "Input: arr[] = {1, 12, 5, 111, 200, 1000, 10, 9, 12, 15}, K = 50 Output: 6 Toys with amount 1, 5, 9, 10, 12, and 12 can be purchased resulting in a total amount of 49. Hence, the maximum number of toys are 6."
},
{
"code": null,
"e": 26879,
"s": 26815,
"text": "Input: arr[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4"
},
{
"code": null,
"e": 27214,
"s": 26879,
"text": "Approach: Insert all the elements of the given array in a priority_queue now one by one remove elements from this priority queue and add these costs in a variable sum initialised to 0. Keep removing the elements while the new addition keep the sum smaller than K. In the end, the count of elements removed will be the required answer."
},
{
"code": null,
"e": 27265,
"s": 27214,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27269,
"s": 27265,
"text": "C++"
},
{
"code": null,
"e": 27274,
"s": 27269,
"text": "Java"
},
{
"code": null,
"e": 27282,
"s": 27274,
"text": "Python3"
},
{
"code": null,
"e": 27285,
"s": 27282,
"text": "C#"
},
{
"code": null,
"e": 27296,
"s": 27285,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// maximum toys that can be boughtint maxToys(int arr[], int n, int k){ // Create a priority_queue and push // all the array elements in it priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < n; i++) { pq.push(arr[i]); } // To store the count of maximum // toys that can be bought int count = 0; while (pq.top() <= k) { count++; k = k - pq.top(); pq.pop(); } return count;} // Driver codeint main(){ int arr[] = { 1, 12, 5, 111, 200, 1000, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 50; cout << maxToys(arr, n, k); return 0;}",
"e": 28047,
"s": 27296,
"text": null
},
{
"code": "// Java implementation of the approachimport java.io.*;import java.util.*; class GFG{ // Function to return the count of// maximum toys that can be bought public static int maxToys(int[] arr, int k){ int n = arr.length; // Create a priority_queue and push // all the array elements in it PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int i = 0; i < n; i++) { pq.offer(arr[i]); } // To store the count of maximum // toys that can be bought int count = 0; while (!pq.isEmpty() && pq.peek() <= k) { k = k - pq.poll(); count++; } return count;} // Driver codepublic static void main (String[] args){ int[] arr = new int[]{ 1, 12, 5, 111, 200, 1000, 10 }; int k = 50; System.out.println(maxToys(arr, k)); }} // This code is contributed by ankit bajpai",
"e": 28958,
"s": 28047,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of# maximum toys that can be bought # importing heapq moduleimport heapq def maxToys(arr, n, k): # Create a priority_queue and push # all the array elements in it pq = arr heapq.heapify(pq) # To store the count of maximum # toys that can be bought count = 0 while (pq[0] <= k): count += 1 k -= pq[0] # assigning last element of the min heap # to top of the heap pq[0] = pq[-1] # deleting the last element. pq.pop() # pq.pop() is an O(1) operation # maintaining the heap property again heapq.heapify(pq) return count # Driver codearr = [1, 12, 5, 111, 200, 1000, 10]n = len(arr)k = 50print(maxToys(arr, n, k))",
"e": 29740,
"s": 28958,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count of // maximum toys that can be bought static int maxToys(int[] arr, int n, int k) { // Create a priority_queue and push // all the array elements in it List<int> pq = new List<int>(); for (int i = 0; i < n; i++) { pq.Add(arr[i]); } pq.Sort(); // To store the count of maximum // toys that can be bought int count = 0; while (pq[0] <= k) { count++; k = k - pq[0]; pq.RemoveAt(0); } return count; } // Driver code static void Main() { int[] arr = { 1, 12, 5, 111, 200, 1000, 10 }; int n = arr.Length; int k = 50; Console.WriteLine(maxToys(arr, n, k)); }} // This code is contributed by divyeshrabadiya07.",
"e": 30668,
"s": 29740,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of // maximum toys that can be bought function maxToys(arr, n, k) { // Create a priority_queue and push // all the array elements in it let pq = []; for (let i = 0; i < n; i++) { pq.push(arr[i]); } pq.sort(function(a, b){return a - b}); // To store the count of maximum // toys that can be bought let count = 0; while (pq[0] <= k) { count++; k = k - pq[0]; pq.shift(); } return count; } let arr = [ 1, 12, 5, 111, 200, 1000, 10 ]; let n = arr.length; let k = 50; document.write(maxToys(arr, n, k)); </script>",
"e": 31476,
"s": 30668,
"text": null
},
{
"code": null,
"e": 31478,
"s": 31476,
"text": "4"
},
{
"code": null,
"e": 31528,
"s": 31480,
"text": "Time Complexity: O(N*logN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31541,
"s": 31528,
"text": "ankit bajpai"
},
{
"code": null,
"e": 31559,
"s": 31541,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 31573,
"s": 31559,
"text": "divyesh072019"
},
{
"code": null,
"e": 31582,
"s": 31573,
"text": "mukesh07"
},
{
"code": null,
"e": 31598,
"s": 31582,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 31614,
"s": 31598,
"text": "rajatkumargla19"
},
{
"code": null,
"e": 31629,
"s": 31614,
"text": "priority-queue"
},
{
"code": null,
"e": 31653,
"s": 31629,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31664,
"s": 31653,
"text": "Algorithms"
},
{
"code": null,
"e": 31671,
"s": 31664,
"text": "Arrays"
},
{
"code": null,
"e": 31676,
"s": 31671,
"text": "Heap"
},
{
"code": null,
"e": 31683,
"s": 31676,
"text": "Arrays"
},
{
"code": null,
"e": 31688,
"s": 31683,
"text": "Heap"
},
{
"code": null,
"e": 31703,
"s": 31688,
"text": "priority-queue"
},
{
"code": null,
"e": 31714,
"s": 31703,
"text": "Algorithms"
},
{
"code": null,
"e": 31812,
"s": 31714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31846,
"s": 31812,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 31886,
"s": 31846,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 31928,
"s": 31886,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 31956,
"s": 31928,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 31985,
"s": 31956,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 32034,
"s": 31985,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32078,
"s": 32034,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32103,
"s": 32078,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32134,
"s": 32103,
"text": "Difference between BFS and DFS"
}
]
|
Apache Storm - Working Example | We have gone through the core technical details of the Apache Storm and now it is time to code some simple scenarios.
Mobile call and its duration will be given as input to Apache Storm and the Storm will process and group the call between the same caller and receiver and their total number of calls.
Spout is a component which is used for data generation. Basically, a spout will implement an IRichSpout interface. “IRichSpout” interface has the following important methods −
open − Provides the spout with an environment to execute. The executors will run this method to initialize the spout.
open − Provides the spout with an environment to execute. The executors will run this method to initialize the spout.
nextTuple − Emits the generated data through the collector.
nextTuple − Emits the generated data through the collector.
close − This method is called when a spout is going to shutdown.
close − This method is called when a spout is going to shutdown.
declareOutputFields − Declares the output schema of the tuple.
declareOutputFields − Declares the output schema of the tuple.
ack − Acknowledges that a specific tuple is processed
ack − Acknowledges that a specific tuple is processed
fail − Specifies that a specific tuple is not processed and not to be reprocessed.
fail − Specifies that a specific tuple is not processed and not to be reprocessed.
The signature of the open method is as follows −
open(Map conf, TopologyContext context, SpoutOutputCollector collector)
conf − Provides storm configuration for this spout.
conf − Provides storm configuration for this spout.
context − Provides complete information about the spout place within the topology, its task id, input and output information.
context − Provides complete information about the spout place within the topology, its task id, input and output information.
collector − Enables us to emit the tuple that will be processed by the bolts.
collector − Enables us to emit the tuple that will be processed by the bolts.
The signature of the nextTuple method is as follows −
nextTuple()
nextTuple() is called periodically from the same loop as the ack() and fail() methods. It must release control of the thread when there is no work to do, so that the other methods have a chance to be called. So the first line of nextTuple checks to see if processing has finished. If so, it should sleep for at least one millisecond to reduce load on the processor before returning.
The signature of the close method is as follows −
close()
The signature of the declareOutputFields method is as follows −
declareOutputFields(OutputFieldsDeclarer declarer)
declarer − It is used to declare output stream ids, output fields, etc.
This method is used to specify the output schema of the tuple.
The signature of the ack method is as follows −
ack(Object msgId)
This method acknowledges that a specific tuple has been processed.
The signature of the nextTuple method is as follows −
ack(Object msgId)
This method informs that a specific tuple has not been fully processed. Storm will reprocess the specific tuple.
In our scenario, we need to collect the call log details. The information of the call log contains.
caller number
receiver number
duration
Since, we don’t have real-time information of call logs, we will generate fake call logs. The fake information will be created using Random class. The complete program code is given below.
import java.util.*;
//import storm tuple packages
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
//import Spout interface packages
import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
//Create a class FakeLogReaderSpout which implement IRichSpout interface
to access functionalities
public class FakeCallLogReaderSpout implements IRichSpout {
//Create instance for SpoutOutputCollector which passes tuples to bolt.
private SpoutOutputCollector collector;
private boolean completed = false;
//Create instance for TopologyContext which contains topology data.
private TopologyContext context;
//Create instance for Random class.
private Random randomGenerator = new Random();
private Integer idx = 0;
@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
this.context = context;
this.collector = collector;
}
@Override
public void nextTuple() {
if(this.idx <= 1000) {
List<String> mobileNumbers = new ArrayList<String>();
mobileNumbers.add("1234123401");
mobileNumbers.add("1234123402");
mobileNumbers.add("1234123403");
mobileNumbers.add("1234123404");
Integer localIdx = 0;
while(localIdx++ < 100 && this.idx++ < 1000) {
String fromMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
String toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
while(fromMobileNumber == toMobileNumber) {
toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));
}
Integer duration = randomGenerator.nextInt(60);
this.collector.emit(new Values(fromMobileNumber, toMobileNumber, duration));
}
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("from", "to", "duration"));
}
//Override all the interface methods
@Override
public void close() {}
public boolean isDistributed() {
return false;
}
@Override
public void activate() {}
@Override
public void deactivate() {}
@Override
public void ack(Object msgId) {}
@Override
public void fail(Object msgId) {}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes CallLogCreatorBolt and CallLogCounterBolt are used to perform the operations.
IRichBolt interface has the following methods −
prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout.
prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout.
execute − Process a single tuple of input.
execute − Process a single tuple of input.
cleanup − Called when a bolt is going to shutdown.
cleanup − Called when a bolt is going to shutdown.
declareOutputFields − Declares the output schema of the tuple.
declareOutputFields − Declares the output schema of the tuple.
The signature of the prepare method is as follows −
prepare(Map conf, TopologyContext context, OutputCollector collector)
conf − Provides Storm configuration for this bolt.
conf − Provides Storm configuration for this bolt.
context − Provides complete information about the bolt place within the topology, its task id, input and output information, etc.
context − Provides complete information about the bolt place within the topology, its task id, input and output information, etc.
collector − Enables us to emit the processed tuple.
collector − Enables us to emit the processed tuple.
The signature of the execute method is as follows −
execute(Tuple tuple)
Here tuple is the input tuple to be processed.
The execute method processes a single tuple at a time. The tuple data can be accessed by getValue method of Tuple class. It is not necessary to process the input tuple immediately. Multiple tuple can be processed and output as a single output tuple. The processed tuple can be emitted by using the OutputCollector class.
The signature of the cleanup method is as follows −
cleanup()
The signature of the declareOutputFields method is as follows −
declareOutputFields(OutputFieldsDeclarer declarer)
Here the parameter declarer is used to declare output stream ids, output fields, etc.
This method is used to specify the output schema of the tuple
Call log creator bolt receives the call log tuple. The call log tuple has caller number, receiver number, and call duration. This bolt simply creates a new value by combining the caller number and the receiver number. The format of the new value is "Caller number – Receiver number" and it is named as new field, "call". The complete code is given below.
//import util packages
import java.util.HashMap;
import java.util.Map;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
//import Storm IRichBolt package
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;
//Create a class CallLogCreatorBolt which implement IRichBolt interface
public class CallLogCreatorBolt implements IRichBolt {
//Create instance for OutputCollector which collects and emits tuples to produce output
private OutputCollector collector;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(Tuple tuple) {
String from = tuple.getString(0);
String to = tuple.getString(1);
Integer duration = tuple.getInteger(2);
collector.emit(new Values(from + " - " + to, duration));
}
@Override
public void cleanup() {}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("call", "duration"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
Call log counter bolt receives call and its duration as a tuple. This bolt initializes a dictionary (Map) object in the prepare method. In execute method, it checks the tuple and creates a new entry in the dictionary object for every new “call” value in the tuple and sets a value 1 in the dictionary object. For the already available entry in the dictionary, it just increment its value. In simple terms, this bolt saves the call and its count in the dictionary object. Instead of saving the call and its count in the dictionary, we can also save it to a datasource. The complete program code is as follows −
import java.util.HashMap;
import java.util.Map;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Tuple;
public class CallLogCounterBolt implements IRichBolt {
Map<String, Integer> counterMap;
private OutputCollector collector;
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.counterMap = new HashMap<String, Integer>();
this.collector = collector;
}
@Override
public void execute(Tuple tuple) {
String call = tuple.getString(0);
Integer duration = tuple.getInteger(1);
if(!counterMap.containsKey(call)){
counterMap.put(call, 1);
}else{
Integer c = counterMap.get(call) + 1;
counterMap.put(call, c);
}
collector.ack(tuple);
}
@Override
public void cleanup() {
for(Map.Entry<String, Integer> entry:counterMap.entrySet()){
System.out.println(entry.getKey()+" : " + entry.getValue());
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("call"));
}
@Override
public Map<String, Object> getComponentConfiguration() {
return null;
}
}
The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create topology. Use the following code snippet to create a topology −
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("call-log-reader-spout", new FakeCallLogReaderSpout());
builder.setBolt("call-log-creator-bolt", new CallLogCreatorBolt())
.shuffleGrouping("call-log-reader-spout");
builder.setBolt("call-log-counter-bolt", new CallLogCounterBolt())
.fieldsGrouping("call-log-creator-bolt", new Fields("call"));
shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts.
For development purpose, we can create a local cluster using "LocalCluster" object and then submit the topology using "submitTopology" method of "LocalCluster" class. One of the arguments for "submitTopology" is an instance of "Config" class. The "Config" class is used to set configuration options before submitting the topology. This configuration option will be merged with the cluster configuration at run time and sent to all task (spout and bolt) with the prepare method. Once topology is submitted to the cluster, we will wait 10 seconds for the cluster to compute the submitted topology and then shutdown the cluster using “shutdown” method of "LocalCluster". The complete program code is as follows −
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
//import storm configuration packages
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.topology.TopologyBuilder;
//Create main class LogAnalyserStorm submit topology.
public class LogAnalyserStorm {
public static void main(String[] args) throws Exception{
//Create Config instance for cluster configuration
Config config = new Config();
config.setDebug(true);
//
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("call-log-reader-spout", new FakeCallLogReaderSpout());
builder.setBolt("call-log-creator-bolt", new CallLogCreatorBolt())
.shuffleGrouping("call-log-reader-spout");
builder.setBolt("call-log-counter-bolt", new CallLogCounterBolt())
.fieldsGrouping("call-log-creator-bolt", new Fields("call"));
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("LogAnalyserStorm", config, builder.createTopology());
Thread.sleep(10000);
//Stop the topology
cluster.shutdown();
}
}
The complete application has four Java codes. They are −
FakeCallLogReaderSpout.java
CallLogCreaterBolt.java
CallLogCounterBolt.java
LogAnalyerStorm.java
The application can be built using the following command −
javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*” *.java
The application can be run using the following command −
java -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:. LogAnalyserStorm
Once the application is started, it will output the complete details about the cluster startup process, spout and bolt processing, and finally, the cluster shutdown process. In "CallLogCounterBolt", we have printed the call and its count details. This information will be displayed on the console as follows −
1234123402 - 1234123401 : 78
1234123402 - 1234123404 : 88
1234123402 - 1234123403 : 105
1234123401 - 1234123404 : 74
1234123401 - 1234123403 : 81
1234123401 - 1234123402 : 81
1234123403 - 1234123404 : 86
1234123404 - 1234123401 : 63
1234123404 - 1234123402 : 82
1234123403 - 1234123402 : 83
1234123404 - 1234123403 : 86
1234123403 - 1234123401 : 93
Storm topologies are implemented by Thrift interfaces which makes it easy to submit topologies in any language. Storm supports Ruby, Python and many other languages. Let’s take a look at python binding.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Storm supports Python to implement its topology. Python supports emitting, anchoring, acking, and logging operations.
As you know, bolts can be defined in any language. Bolts written in another language are executed as sub-processes, and Storm communicates with those sub-processes with JSON messages over stdin/stdout. First take a sample bolt WordCount that supports python binding.
public static class WordCount implements IRichBolt {
public WordSplit() {
super("python", "splitword.py");
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
Here the class WordCount implements the IRichBolt interface and running with python implementation specified super method argument "splitword.py". Now create a python implementation named "splitword.py".
import storm
class WordCountBolt(storm.BasicBolt):
def process(self, tup):
words = tup.values[0].split(" ")
for word in words:
storm.emit([word])
WordCountBolt().run()
This is the sample implementation for Python that counts the words in a given sentence. Similarly you can bind with other supporting languages as well.
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": 2045,
"s": 1927,
"text": "We have gone through the core technical details of the Apache Storm and now it is time to code some simple scenarios."
},
{
"code": null,
"e": 2229,
"s": 2045,
"text": "Mobile call and its duration will be given as input to Apache Storm and the Storm will process and group the call between the same caller and receiver and their total number of calls."
},
{
"code": null,
"e": 2405,
"s": 2229,
"text": "Spout is a component which is used for data generation. Basically, a spout will implement an IRichSpout interface. “IRichSpout” interface has the following important methods −"
},
{
"code": null,
"e": 2523,
"s": 2405,
"text": "open − Provides the spout with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 2641,
"s": 2523,
"text": "open − Provides the spout with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 2701,
"s": 2641,
"text": "nextTuple − Emits the generated data through the collector."
},
{
"code": null,
"e": 2761,
"s": 2701,
"text": "nextTuple − Emits the generated data through the collector."
},
{
"code": null,
"e": 2826,
"s": 2761,
"text": "close − This method is called when a spout is going to shutdown."
},
{
"code": null,
"e": 2891,
"s": 2826,
"text": "close − This method is called when a spout is going to shutdown."
},
{
"code": null,
"e": 2954,
"s": 2891,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 3017,
"s": 2954,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 3071,
"s": 3017,
"text": "ack − Acknowledges that a specific tuple is processed"
},
{
"code": null,
"e": 3125,
"s": 3071,
"text": "ack − Acknowledges that a specific tuple is processed"
},
{
"code": null,
"e": 3208,
"s": 3125,
"text": "fail − Specifies that a specific tuple is not processed and not to be reprocessed."
},
{
"code": null,
"e": 3291,
"s": 3208,
"text": "fail − Specifies that a specific tuple is not processed and not to be reprocessed."
},
{
"code": null,
"e": 3340,
"s": 3291,
"text": "The signature of the open method is as follows −"
},
{
"code": null,
"e": 3413,
"s": 3340,
"text": "open(Map conf, TopologyContext context, SpoutOutputCollector collector)\n"
},
{
"code": null,
"e": 3465,
"s": 3413,
"text": "conf − Provides storm configuration for this spout."
},
{
"code": null,
"e": 3517,
"s": 3465,
"text": "conf − Provides storm configuration for this spout."
},
{
"code": null,
"e": 3643,
"s": 3517,
"text": "context − Provides complete information about the spout place within the topology, its task id, input and output information."
},
{
"code": null,
"e": 3769,
"s": 3643,
"text": "context − Provides complete information about the spout place within the topology, its task id, input and output information."
},
{
"code": null,
"e": 3847,
"s": 3769,
"text": "collector − Enables us to emit the tuple that will be processed by the bolts."
},
{
"code": null,
"e": 3925,
"s": 3847,
"text": "collector − Enables us to emit the tuple that will be processed by the bolts."
},
{
"code": null,
"e": 3979,
"s": 3925,
"text": "The signature of the nextTuple method is as follows −"
},
{
"code": null,
"e": 3992,
"s": 3979,
"text": "nextTuple()\n"
},
{
"code": null,
"e": 4375,
"s": 3992,
"text": "nextTuple() is called periodically from the same loop as the ack() and fail() methods. It must release control of the thread when there is no work to do, so that the other methods have a chance to be called. So the first line of nextTuple checks to see if processing has finished. If so, it should sleep for at least one millisecond to reduce load on the processor before returning."
},
{
"code": null,
"e": 4425,
"s": 4375,
"text": "The signature of the close method is as follows −"
},
{
"code": null,
"e": 4434,
"s": 4425,
"text": "close()\n"
},
{
"code": null,
"e": 4498,
"s": 4434,
"text": "The signature of the declareOutputFields method is as follows −"
},
{
"code": null,
"e": 4550,
"s": 4498,
"text": "declareOutputFields(OutputFieldsDeclarer declarer)\n"
},
{
"code": null,
"e": 4622,
"s": 4550,
"text": "declarer − It is used to declare output stream ids, output fields, etc."
},
{
"code": null,
"e": 4685,
"s": 4622,
"text": "This method is used to specify the output schema of the tuple."
},
{
"code": null,
"e": 4733,
"s": 4685,
"text": "The signature of the ack method is as follows −"
},
{
"code": null,
"e": 4752,
"s": 4733,
"text": "ack(Object msgId)\n"
},
{
"code": null,
"e": 4819,
"s": 4752,
"text": "This method acknowledges that a specific tuple has been processed."
},
{
"code": null,
"e": 4873,
"s": 4819,
"text": "The signature of the nextTuple method is as follows −"
},
{
"code": null,
"e": 4892,
"s": 4873,
"text": "ack(Object msgId)\n"
},
{
"code": null,
"e": 5005,
"s": 4892,
"text": "This method informs that a specific tuple has not been fully processed. Storm will reprocess the specific tuple."
},
{
"code": null,
"e": 5105,
"s": 5005,
"text": "In our scenario, we need to collect the call log details. The information of the call log contains."
},
{
"code": null,
"e": 5119,
"s": 5105,
"text": "caller number"
},
{
"code": null,
"e": 5135,
"s": 5119,
"text": "receiver number"
},
{
"code": null,
"e": 5144,
"s": 5135,
"text": "duration"
},
{
"code": null,
"e": 5333,
"s": 5144,
"text": "Since, we don’t have real-time information of call logs, we will generate fake call logs. The fake information will be created using Random class. The complete program code is given below."
},
{
"code": null,
"e": 7874,
"s": 5333,
"text": "import java.util.*;\n//import storm tuple packages\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\n//import Spout interface packages\nimport backtype.storm.topology.IRichSpout;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.spout.SpoutOutputCollector;\nimport backtype.storm.task.TopologyContext;\n\n//Create a class FakeLogReaderSpout which implement IRichSpout interface \n to access functionalities\n\t\npublic class FakeCallLogReaderSpout implements IRichSpout {\n //Create instance for SpoutOutputCollector which passes tuples to bolt.\n private SpoutOutputCollector collector;\n private boolean completed = false;\n\t\n //Create instance for TopologyContext which contains topology data.\n private TopologyContext context;\n\t\n //Create instance for Random class.\n private Random randomGenerator = new Random();\n private Integer idx = 0;\n\n @Override\n public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {\n this.context = context;\n this.collector = collector;\n }\n\n @Override\n public void nextTuple() {\n if(this.idx <= 1000) {\n List<String> mobileNumbers = new ArrayList<String>();\n mobileNumbers.add(\"1234123401\");\n mobileNumbers.add(\"1234123402\");\n mobileNumbers.add(\"1234123403\");\n mobileNumbers.add(\"1234123404\");\n\n Integer localIdx = 0;\n while(localIdx++ < 100 && this.idx++ < 1000) {\n String fromMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));\n String toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));\n\t\t\t\t\n while(fromMobileNumber == toMobileNumber) {\n toMobileNumber = mobileNumbers.get(randomGenerator.nextInt(4));\n }\n\t\t\t\t\n Integer duration = randomGenerator.nextInt(60);\n this.collector.emit(new Values(fromMobileNumber, toMobileNumber, duration));\n }\n }\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"from\", \"to\", \"duration\"));\n }\n\n //Override all the interface methods\n @Override\n public void close() {}\n\n public boolean isDistributed() {\n return false;\n }\n\n @Override\n public void activate() {}\n\n @Override \n public void deactivate() {}\n\n @Override\n public void ack(Object msgId) {}\n\n @Override\n public void fail(Object msgId) {}\n\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n}"
},
{
"code": null,
"e": 8132,
"s": 7874,
"text": "Bolt is a component that takes tuples as input, processes the tuple, and produces new tuples as output. Bolts will implement IRichBolt interface. In this program, two bolt classes CallLogCreatorBolt and CallLogCounterBolt are used to perform the operations."
},
{
"code": null,
"e": 8180,
"s": 8132,
"text": "IRichBolt interface has the following methods −"
},
{
"code": null,
"e": 8300,
"s": 8180,
"text": "prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 8420,
"s": 8300,
"text": "prepare − Provides the bolt with an environment to execute. The executors will run this method to initialize the spout."
},
{
"code": null,
"e": 8463,
"s": 8420,
"text": "execute − Process a single tuple of input."
},
{
"code": null,
"e": 8506,
"s": 8463,
"text": "execute − Process a single tuple of input."
},
{
"code": null,
"e": 8557,
"s": 8506,
"text": "cleanup − Called when a bolt is going to shutdown."
},
{
"code": null,
"e": 8608,
"s": 8557,
"text": "cleanup − Called when a bolt is going to shutdown."
},
{
"code": null,
"e": 8671,
"s": 8608,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 8734,
"s": 8671,
"text": "declareOutputFields − Declares the output schema of the tuple."
},
{
"code": null,
"e": 8786,
"s": 8734,
"text": "The signature of the prepare method is as follows −"
},
{
"code": null,
"e": 8857,
"s": 8786,
"text": "prepare(Map conf, TopologyContext context, OutputCollector collector)\n"
},
{
"code": null,
"e": 8908,
"s": 8857,
"text": "conf − Provides Storm configuration for this bolt."
},
{
"code": null,
"e": 8959,
"s": 8908,
"text": "conf − Provides Storm configuration for this bolt."
},
{
"code": null,
"e": 9089,
"s": 8959,
"text": "context − Provides complete information about the bolt place within the topology, its task id, input and output information, etc."
},
{
"code": null,
"e": 9219,
"s": 9089,
"text": "context − Provides complete information about the bolt place within the topology, its task id, input and output information, etc."
},
{
"code": null,
"e": 9271,
"s": 9219,
"text": "collector − Enables us to emit the processed tuple."
},
{
"code": null,
"e": 9323,
"s": 9271,
"text": "collector − Enables us to emit the processed tuple."
},
{
"code": null,
"e": 9375,
"s": 9323,
"text": "The signature of the execute method is as follows −"
},
{
"code": null,
"e": 9397,
"s": 9375,
"text": "execute(Tuple tuple)\n"
},
{
"code": null,
"e": 9444,
"s": 9397,
"text": "Here tuple is the input tuple to be processed."
},
{
"code": null,
"e": 9765,
"s": 9444,
"text": "The execute method processes a single tuple at a time. The tuple data can be accessed by getValue method of Tuple class. It is not necessary to process the input tuple immediately. Multiple tuple can be processed and output as a single output tuple. The processed tuple can be emitted by using the OutputCollector class."
},
{
"code": null,
"e": 9817,
"s": 9765,
"text": "The signature of the cleanup method is as follows −"
},
{
"code": null,
"e": 9828,
"s": 9817,
"text": "cleanup()\n"
},
{
"code": null,
"e": 9892,
"s": 9828,
"text": "The signature of the declareOutputFields method is as follows −"
},
{
"code": null,
"e": 9944,
"s": 9892,
"text": "declareOutputFields(OutputFieldsDeclarer declarer)\n"
},
{
"code": null,
"e": 10030,
"s": 9944,
"text": "Here the parameter declarer is used to declare output stream ids, output fields, etc."
},
{
"code": null,
"e": 10092,
"s": 10030,
"text": "This method is used to specify the output schema of the tuple"
},
{
"code": null,
"e": 10447,
"s": 10092,
"text": "Call log creator bolt receives the call log tuple. The call log tuple has caller number, receiver number, and call duration. This bolt simply creates a new value by combining the caller number and the receiver number. The format of the new value is \"Caller number – Receiver number\" and it is named as new field, \"call\". The complete code is given below."
},
{
"code": null,
"e": 11770,
"s": 10447,
"text": "//import util packages\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.task.TopologyContext;\n\n//import Storm IRichBolt package\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.tuple.Tuple;\n\n//Create a class CallLogCreatorBolt which implement IRichBolt interface\npublic class CallLogCreatorBolt implements IRichBolt {\n //Create instance for OutputCollector which collects and emits tuples to produce output\n private OutputCollector collector;\n\n @Override\n public void prepare(Map conf, TopologyContext context, OutputCollector collector) {\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple tuple) {\n String from = tuple.getString(0);\n String to = tuple.getString(1);\n Integer duration = tuple.getInteger(2);\n collector.emit(new Values(from + \" - \" + to, duration));\n }\n\n @Override\n public void cleanup() {}\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"call\", \"duration\"));\n }\n\t\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n}"
},
{
"code": null,
"e": 12380,
"s": 11770,
"text": "Call log counter bolt receives call and its duration as a tuple. This bolt initializes a dictionary (Map) object in the prepare method. In execute method, it checks the tuple and creates a new entry in the dictionary object for every new “call” value in the tuple and sets a value 1 in the dictionary object. For the already available entry in the dictionary, it just increment its value. In simple terms, this bolt saves the call and its count in the dictionary object. Instead of saving the call and its count in the dictionary, we can also save it to a datasource. The complete program code is as follows −"
},
{
"code": null,
"e": 13824,
"s": 12380,
"text": "import java.util.HashMap;\nimport java.util.Map;\n\nimport backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\nimport backtype.storm.task.OutputCollector;\nimport backtype.storm.task.TopologyContext;\nimport backtype.storm.topology.IRichBolt;\nimport backtype.storm.topology.OutputFieldsDeclarer;\nimport backtype.storm.tuple.Tuple;\n\npublic class CallLogCounterBolt implements IRichBolt {\n Map<String, Integer> counterMap;\n private OutputCollector collector;\n\n @Override\n public void prepare(Map conf, TopologyContext context, OutputCollector collector) {\n this.counterMap = new HashMap<String, Integer>();\n this.collector = collector;\n }\n\n @Override\n public void execute(Tuple tuple) {\n String call = tuple.getString(0);\n Integer duration = tuple.getInteger(1);\n\t\t\n if(!counterMap.containsKey(call)){\n counterMap.put(call, 1);\n }else{\n Integer c = counterMap.get(call) + 1;\n counterMap.put(call, c);\n }\n\t\t\n collector.ack(tuple);\n }\n\n @Override\n public void cleanup() {\n for(Map.Entry<String, Integer> entry:counterMap.entrySet()){\n System.out.println(entry.getKey()+\" : \" + entry.getValue());\n }\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"call\"));\n }\n\t\n @Override\n public Map<String, Object> getComponentConfiguration() {\n return null;\n }\n\t\n}"
},
{
"code": null,
"e": 14168,
"s": 13824,
"text": "The Storm topology is basically a Thrift structure. TopologyBuilder class provides simple and easy methods to create complex topologies. The TopologyBuilder class has methods to set spout (setSpout) and to set bolt (setBolt). Finally, TopologyBuilder has createTopology to create topology. Use the following code snippet to create a topology −"
},
{
"code": null,
"e": 14538,
"s": 14168,
"text": "TopologyBuilder builder = new TopologyBuilder();\n\nbuilder.setSpout(\"call-log-reader-spout\", new FakeCallLogReaderSpout());\n\nbuilder.setBolt(\"call-log-creator-bolt\", new CallLogCreatorBolt())\n .shuffleGrouping(\"call-log-reader-spout\");\n\nbuilder.setBolt(\"call-log-counter-bolt\", new CallLogCounterBolt())\n .fieldsGrouping(\"call-log-creator-bolt\", new Fields(\"call\"));"
},
{
"code": null,
"e": 14630,
"s": 14538,
"text": "shuffleGrouping and fieldsGrouping methods help to set stream grouping for spout and bolts."
},
{
"code": null,
"e": 15340,
"s": 14630,
"text": "For development purpose, we can create a local cluster using \"LocalCluster\" object and then submit the topology using \"submitTopology\" method of \"LocalCluster\" class. One of the arguments for \"submitTopology\" is an instance of \"Config\" class. The \"Config\" class is used to set configuration options before submitting the topology. This configuration option will be merged with the cluster configuration at run time and sent to all task (spout and bolt) with the prepare method. Once topology is submitted to the cluster, we will wait 10 seconds for the cluster to compute the submitted topology and then shutdown the cluster using “shutdown” method of \"LocalCluster\". The complete program code is as follows −"
},
{
"code": null,
"e": 16480,
"s": 15340,
"text": "import backtype.storm.tuple.Fields;\nimport backtype.storm.tuple.Values;\n\n//import storm configuration packages\nimport backtype.storm.Config;\nimport backtype.storm.LocalCluster;\nimport backtype.storm.topology.TopologyBuilder;\n\n//Create main class LogAnalyserStorm submit topology.\npublic class LogAnalyserStorm {\n public static void main(String[] args) throws Exception{\n //Create Config instance for cluster configuration\n Config config = new Config();\n config.setDebug(true);\n\t\t\n //\n TopologyBuilder builder = new TopologyBuilder();\n builder.setSpout(\"call-log-reader-spout\", new FakeCallLogReaderSpout());\n\n builder.setBolt(\"call-log-creator-bolt\", new CallLogCreatorBolt())\n .shuffleGrouping(\"call-log-reader-spout\");\n\n builder.setBolt(\"call-log-counter-bolt\", new CallLogCounterBolt())\n .fieldsGrouping(\"call-log-creator-bolt\", new Fields(\"call\"));\n\t\t\t\n LocalCluster cluster = new LocalCluster();\n cluster.submitTopology(\"LogAnalyserStorm\", config, builder.createTopology());\n Thread.sleep(10000);\n\t\t\n //Stop the topology\n\t\t\n cluster.shutdown();\n }\n}"
},
{
"code": null,
"e": 16537,
"s": 16480,
"text": "The complete application has four Java codes. They are −"
},
{
"code": null,
"e": 16565,
"s": 16537,
"text": "FakeCallLogReaderSpout.java"
},
{
"code": null,
"e": 16589,
"s": 16565,
"text": "CallLogCreaterBolt.java"
},
{
"code": null,
"e": 16613,
"s": 16589,
"text": "CallLogCounterBolt.java"
},
{
"code": null,
"e": 16634,
"s": 16613,
"text": "LogAnalyerStorm.java"
},
{
"code": null,
"e": 16693,
"s": 16634,
"text": "The application can be built using the following command −"
},
{
"code": null,
"e": 16753,
"s": 16693,
"text": "javac -cp “/path/to/storm/apache-storm-0.9.5/lib/*” *.java\n"
},
{
"code": null,
"e": 16810,
"s": 16753,
"text": "The application can be run using the following command −"
},
{
"code": null,
"e": 16881,
"s": 16810,
"text": "java -cp “/path/to/storm/apache-storm-0.9.5/lib/*”:. LogAnalyserStorm\n"
},
{
"code": null,
"e": 17191,
"s": 16881,
"text": "Once the application is started, it will output the complete details about the cluster startup process, spout and bolt processing, and finally, the cluster shutdown process. In \"CallLogCounterBolt\", we have printed the call and its count details. This information will be displayed on the console as follows −"
},
{
"code": null,
"e": 17541,
"s": 17191,
"text": "1234123402 - 1234123401 : 78\n1234123402 - 1234123404 : 88\n1234123402 - 1234123403 : 105\n1234123401 - 1234123404 : 74\n1234123401 - 1234123403 : 81\n1234123401 - 1234123402 : 81\n1234123403 - 1234123404 : 86\n1234123404 - 1234123401 : 63\n1234123404 - 1234123402 : 82\n1234123403 - 1234123402 : 83\n1234123404 - 1234123403 : 86\n1234123403 - 1234123401 : 93\n"
},
{
"code": null,
"e": 17744,
"s": 17541,
"text": "Storm topologies are implemented by Thrift interfaces which makes it easy to submit topologies in any language. Storm supports Ruby, Python and many other languages. Let’s take a look at python binding."
},
{
"code": null,
"e": 17970,
"s": 17744,
"text": "Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Storm supports Python to implement its topology. Python supports emitting, anchoring, acking, and logging operations."
},
{
"code": null,
"e": 18237,
"s": 17970,
"text": "As you know, bolts can be defined in any language. Bolts written in another language are executed as sub-processes, and Storm communicates with those sub-processes with JSON messages over stdin/stdout. First take a sample bolt WordCount that supports python binding."
},
{
"code": null,
"e": 18479,
"s": 18237,
"text": "public static class WordCount implements IRichBolt {\n public WordSplit() {\n super(\"python\", \"splitword.py\");\n }\n\t\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n declarer.declare(new Fields(\"word\"));\n }\n}"
},
{
"code": null,
"e": 18683,
"s": 18479,
"text": "Here the class WordCount implements the IRichBolt interface and running with python implementation specified super method argument \"splitword.py\". Now create a python implementation named \"splitword.py\"."
},
{
"code": null,
"e": 18887,
"s": 18683,
"text": "import storm\n class WordCountBolt(storm.BasicBolt):\n def process(self, tup):\n words = tup.values[0].split(\" \")\n for word in words:\n storm.emit([word])\nWordCountBolt().run()"
},
{
"code": null,
"e": 19039,
"s": 18887,
"text": "This is the sample implementation for Python that counts the words in a given sentence. Similarly you can bind with other supporting languages as well."
},
{
"code": null,
"e": 19074,
"s": 19039,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 19093,
"s": 19074,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 19128,
"s": 19093,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 19149,
"s": 19128,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 19182,
"s": 19149,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 19195,
"s": 19182,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 19230,
"s": 19195,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 19248,
"s": 19230,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 19281,
"s": 19248,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 19299,
"s": 19281,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 19332,
"s": 19299,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 19350,
"s": 19332,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 19357,
"s": 19350,
"text": " Print"
},
{
"code": null,
"e": 19368,
"s": 19357,
"text": " Add Notes"
}
]
|
PyQt - QPushButton Widget | In any GUI design, the command button is the most important and most often used control. Buttons with Save, Open, OK, Yes, No and Cancel etc. as caption are familiar to any computer user. In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function.
QPushButton class inherits its core functionality from QAbstractButton class. It is rectangular in shape and a text caption or icon can be displayed on its face.
Following are some of the most commonly used methods of QPushButton class −
setCheckable()
Recognizes pressed and released states of button if set to true
toggle()
Toggles between checkable states
setIcon()
Shows an icon formed out of pixmap of an image file
setEnabled()
When set to false, the button becomes disabled, hence clicking it doesn’t emit a signal
isChecked()
Returns Boolean state of button
setDefault()
Sets the button as default
setText()
Programmatically sets buttons’ caption
text()
Retrieves buttons’ caption
Four QPushButton objects are set with some of the above attributes. The example is written in object oriented form, because the source of the event is needed to be passed as an argument to slot function.
Four QPushButton objects are defined as instance variables in the class. First button b1 is converted into toggle button by the statements −
self.b1.setCheckable(True)
self.b1.toggle()
Clicked signal of this button is connected to a member method btnstate() which identifies whether button is pressed or released by checking isChecked() property.
def btnstate(self):
if self.b1.isChecked():
print "button pressed"
else:
print "button released"
Second button b2 displays an icon on the face. setIcon() method takes a pixmap object of any image file as argument.
b2.setIcon(QIcon(QPixmap("python.gif")))
Button b3 is set to be disabled by using setEnabled() method −
b3.setEnabled(False)
PushButton b4 is set to default button by setDefault() method. Shortcut to its caption is created by prefixing & to the caption (&Default). As a result, by using the keyboard combination Alt+D, connected slot method will be called.
Buttons b1 and b4 are connected to whichbtn() slot method. Since the function is intended to retrieve caption of the clicked button, the button object should be passed as an argument. This is achieved by the use of lambda function.
For example,
b4.clicked.connect(lambda:self.whichbtn(self.b4))
The complete code is given below −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
layout = QVBoxLayout()
self.b1 = QPushButton("Button1")
self.b1.setCheckable(True)
self.b1.toggle()
self.b1.clicked.connect(lambda:self.whichbtn(self.b1))
self.b1.clicked.connect(self.btnstate)
layout.addWidget(self.b1)
self.b2 = QPushButton()
self.b2.setIcon(QIcon(QPixmap("python.gif")))
self.b2.clicked.connect(lambda:self.whichbtn(self.b2))
layout.addWidget(self.b2)
self.setLayout(layout)
self.b3 = QPushButton("Disabled")
self.b3.setEnabled(False)
layout.addWidget(self.b3)
self.b4 = QPushButton("&Default")
self.b4.setDefault(True)
self.b4.clicked.connect(lambda:self.whichbtn(self.b4))
layout.addWidget(self.b4)
self.setWindowTitle("Button demo")
def btnstate(self):
if self.b1.isChecked():
print "button pressed"
else:
print "button released"
def whichbtn(self,b):
print "clicked button is "+b.text()
def main():
app = QApplication(sys.argv)
ex = Form()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output.
clicked button is Button1
button released
clicked button is Button1
button pressed
clicked button is &Default
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2241,
"s": 1926,
"text": "In any GUI design, the command button is the most important and most often used control. Buttons with Save, Open, OK, Yes, No and Cancel etc. as caption are familiar to any computer user. In PyQt API, the QPushButton class object presents a button which when clicked can be programmed to invoke a certain function."
},
{
"code": null,
"e": 2403,
"s": 2241,
"text": "QPushButton class inherits its core functionality from QAbstractButton class. It is rectangular in shape and a text caption or icon can be displayed on its face."
},
{
"code": null,
"e": 2479,
"s": 2403,
"text": "Following are some of the most commonly used methods of QPushButton class −"
},
{
"code": null,
"e": 2494,
"s": 2479,
"text": "setCheckable()"
},
{
"code": null,
"e": 2558,
"s": 2494,
"text": "Recognizes pressed and released states of button if set to true"
},
{
"code": null,
"e": 2567,
"s": 2558,
"text": "toggle()"
},
{
"code": null,
"e": 2600,
"s": 2567,
"text": "Toggles between checkable states"
},
{
"code": null,
"e": 2610,
"s": 2600,
"text": "setIcon()"
},
{
"code": null,
"e": 2662,
"s": 2610,
"text": "Shows an icon formed out of pixmap of an image file"
},
{
"code": null,
"e": 2675,
"s": 2662,
"text": "setEnabled()"
},
{
"code": null,
"e": 2763,
"s": 2675,
"text": "When set to false, the button becomes disabled, hence clicking it doesn’t emit a signal"
},
{
"code": null,
"e": 2775,
"s": 2763,
"text": "isChecked()"
},
{
"code": null,
"e": 2807,
"s": 2775,
"text": "Returns Boolean state of button"
},
{
"code": null,
"e": 2820,
"s": 2807,
"text": "setDefault()"
},
{
"code": null,
"e": 2847,
"s": 2820,
"text": "Sets the button as default"
},
{
"code": null,
"e": 2857,
"s": 2847,
"text": "setText()"
},
{
"code": null,
"e": 2896,
"s": 2857,
"text": "Programmatically sets buttons’ caption"
},
{
"code": null,
"e": 2903,
"s": 2896,
"text": "text()"
},
{
"code": null,
"e": 2930,
"s": 2903,
"text": "Retrieves buttons’ caption"
},
{
"code": null,
"e": 3134,
"s": 2930,
"text": "Four QPushButton objects are set with some of the above attributes. The example is written in object oriented form, because the source of the event is needed to be passed as an argument to slot function."
},
{
"code": null,
"e": 3275,
"s": 3134,
"text": "Four QPushButton objects are defined as instance variables in the class. First button b1 is converted into toggle button by the statements −"
},
{
"code": null,
"e": 3320,
"s": 3275,
"text": "self.b1.setCheckable(True)\nself.b1.toggle()\n"
},
{
"code": null,
"e": 3482,
"s": 3320,
"text": "Clicked signal of this button is connected to a member method btnstate() which identifies whether button is pressed or released by checking isChecked() property."
},
{
"code": null,
"e": 3597,
"s": 3482,
"text": "def btnstate(self):\n if self.b1.isChecked():\n print \"button pressed\"\n else:\n print \"button released\""
},
{
"code": null,
"e": 3714,
"s": 3597,
"text": "Second button b2 displays an icon on the face. setIcon() method takes a pixmap object of any image file as argument."
},
{
"code": null,
"e": 3756,
"s": 3714,
"text": "b2.setIcon(QIcon(QPixmap(\"python.gif\")))\n"
},
{
"code": null,
"e": 3819,
"s": 3756,
"text": "Button b3 is set to be disabled by using setEnabled() method −"
},
{
"code": null,
"e": 3841,
"s": 3819,
"text": "b3.setEnabled(False)\n"
},
{
"code": null,
"e": 4073,
"s": 3841,
"text": "PushButton b4 is set to default button by setDefault() method. Shortcut to its caption is created by prefixing & to the caption (&Default). As a result, by using the keyboard combination Alt+D, connected slot method will be called."
},
{
"code": null,
"e": 4305,
"s": 4073,
"text": "Buttons b1 and b4 are connected to whichbtn() slot method. Since the function is intended to retrieve caption of the clicked button, the button object should be passed as an argument. This is achieved by the use of lambda function."
},
{
"code": null,
"e": 4318,
"s": 4305,
"text": "For example,"
},
{
"code": null,
"e": 4369,
"s": 4318,
"text": "b4.clicked.connect(lambda:self.whichbtn(self.b4))\n"
},
{
"code": null,
"e": 4404,
"s": 4369,
"text": "The complete code is given below −"
},
{
"code": null,
"e": 5697,
"s": 4404,
"text": "import sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nclass Form(QDialog):\n def __init__(self, parent=None):\n super(Form, self).__init__(parent)\n\t\t\n layout = QVBoxLayout()\n self.b1 = QPushButton(\"Button1\")\n self.b1.setCheckable(True)\n self.b1.toggle()\n self.b1.clicked.connect(lambda:self.whichbtn(self.b1))\n self.b1.clicked.connect(self.btnstate)\n layout.addWidget(self.b1)\n\t\t\n self.b2 = QPushButton()\n self.b2.setIcon(QIcon(QPixmap(\"python.gif\")))\n self.b2.clicked.connect(lambda:self.whichbtn(self.b2))\n layout.addWidget(self.b2)\n self.setLayout(layout)\n self.b3 = QPushButton(\"Disabled\")\n self.b3.setEnabled(False)\n layout.addWidget(self.b3)\n\t\t\n self.b4 = QPushButton(\"&Default\")\n self.b4.setDefault(True)\n self.b4.clicked.connect(lambda:self.whichbtn(self.b4))\n layout.addWidget(self.b4)\n \n self.setWindowTitle(\"Button demo\")\n\n def btnstate(self):\n if self.b1.isChecked():\n print \"button pressed\"\n else:\n print \"button released\"\n\t\t\t\n def whichbtn(self,b):\n print \"clicked button is \"+b.text()\n\ndef main():\n app = QApplication(sys.argv)\n ex = Form()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 5743,
"s": 5697,
"text": "The above code produces the following output."
},
{
"code": null,
"e": 5854,
"s": 5743,
"text": "clicked button is Button1\nbutton released\nclicked button is Button1\nbutton pressed\nclicked button is &Default\n"
},
{
"code": null,
"e": 5891,
"s": 5854,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 5901,
"s": 5891,
"text": " ALAA EID"
},
{
"code": null,
"e": 5908,
"s": 5901,
"text": " Print"
},
{
"code": null,
"e": 5919,
"s": 5908,
"text": " Add Notes"
}
]
|
Boruta Feature Selection (an Example in Python) | by Aaron Lee | Towards Data Science | If you aren’t using Boruta for feature selection, you should try it out. It can be used on any classification model. Boruta is a random forest based method, so it works for tree models like Random Forest or XGBoost, but is also valid with other classification models like Logistic Regression or SVM.
Boruta iteratively removes features that are statistically less relevant than a random probe (artificial noise variables introduced by the Boruta algorithm). In each iteration, rejected variables are removed from consideration in the next iteration. It generally ends up with a good global optimization for feature selection which is why I like it.
We will take a look at a simple random forest example for feature selection. The only intention of this story is to show you an easy working example so you too can use Boruta.
This example will use the breast_cancer dataset that comes with sklearn. You can use the optional return_X_y to have it output arrays directly as shown.
Simply fit the data to your chosen model, and now it is ready for Boruta.
Note: I fit entire dataset when doing feature selection. You can do the train/test split after you have eliminated features.
Now create a BorutaPy feature selection object and fit your entire data to it. During the fit, Boruta will do a number of iterations of feature testing depending on the size of your dataset. Boruta creates random shadow copies of your features (noise) and tests the feature against those copies to determine if it is better than the noise, and therefore worth keeping. It automatically checks for interactions that might hurt your model. Boruta will output confirmed, tentative, and rejected variables for every iteration.
After being fit, the Boruta object has useful attributes and methods:
.support_ attribute is a boolean array that answers — should feature should be kept?
.ranking_ attribute is an int array for the rank (1 is the best feature(s))
.transform(X) method applies the suggestions and returns an array of adjusted data. In this way, you could just let Boruta manage the entire ordeal.
Note: If you get an error (TypeError: invalid key), try converting your X and y to numpy arrays before fitting them to the selector. Let me know if you run into this error and need help.
Here is some quick code I wrote to look output Boruta’s results. Looks like 5 of my 30 features were recommended to be dropped. The output of the code is shown below.
Feature: mean radius Rank: 1, Keep: TrueFeature: mean texture Rank: 1, Keep: TrueFeature: mean perimeter Rank: 1, Keep: TrueFeature: mean area Rank: 1, Keep: TrueFeature: mean smoothness Rank: 1, Keep: TrueFeature: mean compactness Rank: 1, Keep: TrueFeature: mean concavity Rank: 1, Keep: TrueFeature: mean concave points Rank: 1, Keep: TrueFeature: mean symmetry Rank: 1, Keep: TrueFeature: mean fractal dimension Rank: 2, Keep: FalseFeature: radius error Rank: 1, Keep: TrueFeature: texture error Rank: 2, Keep: FalseFeature: perimeter error Rank: 1, Keep: TrueFeature: area error Rank: 1, Keep: TrueFeature: smoothness error Rank: 3, Keep: FalseFeature: compactness error Rank: 1, Keep: TrueFeature: concavity error Rank: 1, Keep: TrueFeature: concave points error Rank: 1, Keep: TrueFeature: symmetry error Rank: 2, Keep: FalseFeature: fractal dimension error Rank: 2, Keep: FalseFeature: worst radius Rank: 1, Keep: TrueFeature: worst texture Rank: 1, Keep: TrueFeature: worst perimeter Rank: 1, Keep: TrueFeature: worst area Rank: 1, Keep: TrueFeature: worst smoothness Rank: 1, Keep: TrueFeature: worst compactness Rank: 1, Keep: TrueFeature: worst concavity Rank: 1, Keep: TrueFeature: worst concave points Rank: 1, Keep: TrueFeature: worst symmetry Rank: 1, Keep: TrueFeature: worst fractal dimension Rank: 1, Keep: True
Now that we have identified the features to drop, we can confidently drop them and proceed with our normal routine. You can even use the .transform()method to automatically drop them. You may want to try other feature selection methods to suit your needs, but Boruta uses one of the most powerful algorithms out there, and is quick and easy to use.
Good luck!
Feel free to reply if you run into trouble, and I will help out if I can. | [
{
"code": null,
"e": 472,
"s": 172,
"text": "If you aren’t using Boruta for feature selection, you should try it out. It can be used on any classification model. Boruta is a random forest based method, so it works for tree models like Random Forest or XGBoost, but is also valid with other classification models like Logistic Regression or SVM."
},
{
"code": null,
"e": 821,
"s": 472,
"text": "Boruta iteratively removes features that are statistically less relevant than a random probe (artificial noise variables introduced by the Boruta algorithm). In each iteration, rejected variables are removed from consideration in the next iteration. It generally ends up with a good global optimization for feature selection which is why I like it."
},
{
"code": null,
"e": 997,
"s": 821,
"text": "We will take a look at a simple random forest example for feature selection. The only intention of this story is to show you an easy working example so you too can use Boruta."
},
{
"code": null,
"e": 1150,
"s": 997,
"text": "This example will use the breast_cancer dataset that comes with sklearn. You can use the optional return_X_y to have it output arrays directly as shown."
},
{
"code": null,
"e": 1224,
"s": 1150,
"text": "Simply fit the data to your chosen model, and now it is ready for Boruta."
},
{
"code": null,
"e": 1349,
"s": 1224,
"text": "Note: I fit entire dataset when doing feature selection. You can do the train/test split after you have eliminated features."
},
{
"code": null,
"e": 1872,
"s": 1349,
"text": "Now create a BorutaPy feature selection object and fit your entire data to it. During the fit, Boruta will do a number of iterations of feature testing depending on the size of your dataset. Boruta creates random shadow copies of your features (noise) and tests the feature against those copies to determine if it is better than the noise, and therefore worth keeping. It automatically checks for interactions that might hurt your model. Boruta will output confirmed, tentative, and rejected variables for every iteration."
},
{
"code": null,
"e": 1942,
"s": 1872,
"text": "After being fit, the Boruta object has useful attributes and methods:"
},
{
"code": null,
"e": 2027,
"s": 1942,
"text": ".support_ attribute is a boolean array that answers — should feature should be kept?"
},
{
"code": null,
"e": 2103,
"s": 2027,
"text": ".ranking_ attribute is an int array for the rank (1 is the best feature(s))"
},
{
"code": null,
"e": 2252,
"s": 2103,
"text": ".transform(X) method applies the suggestions and returns an array of adjusted data. In this way, you could just let Boruta manage the entire ordeal."
},
{
"code": null,
"e": 2439,
"s": 2252,
"text": "Note: If you get an error (TypeError: invalid key), try converting your X and y to numpy arrays before fitting them to the selector. Let me know if you run into this error and need help."
},
{
"code": null,
"e": 2606,
"s": 2439,
"text": "Here is some quick code I wrote to look output Boruta’s results. Looks like 5 of my 30 features were recommended to be dropped. The output of the code is shown below."
},
{
"code": null,
"e": 4262,
"s": 2606,
"text": "Feature: mean radius Rank: 1, Keep: TrueFeature: mean texture Rank: 1, Keep: TrueFeature: mean perimeter Rank: 1, Keep: TrueFeature: mean area Rank: 1, Keep: TrueFeature: mean smoothness Rank: 1, Keep: TrueFeature: mean compactness Rank: 1, Keep: TrueFeature: mean concavity Rank: 1, Keep: TrueFeature: mean concave points Rank: 1, Keep: TrueFeature: mean symmetry Rank: 1, Keep: TrueFeature: mean fractal dimension Rank: 2, Keep: FalseFeature: radius error Rank: 1, Keep: TrueFeature: texture error Rank: 2, Keep: FalseFeature: perimeter error Rank: 1, Keep: TrueFeature: area error Rank: 1, Keep: TrueFeature: smoothness error Rank: 3, Keep: FalseFeature: compactness error Rank: 1, Keep: TrueFeature: concavity error Rank: 1, Keep: TrueFeature: concave points error Rank: 1, Keep: TrueFeature: symmetry error Rank: 2, Keep: FalseFeature: fractal dimension error Rank: 2, Keep: FalseFeature: worst radius Rank: 1, Keep: TrueFeature: worst texture Rank: 1, Keep: TrueFeature: worst perimeter Rank: 1, Keep: TrueFeature: worst area Rank: 1, Keep: TrueFeature: worst smoothness Rank: 1, Keep: TrueFeature: worst compactness Rank: 1, Keep: TrueFeature: worst concavity Rank: 1, Keep: TrueFeature: worst concave points Rank: 1, Keep: TrueFeature: worst symmetry Rank: 1, Keep: TrueFeature: worst fractal dimension Rank: 1, Keep: True"
},
{
"code": null,
"e": 4611,
"s": 4262,
"text": "Now that we have identified the features to drop, we can confidently drop them and proceed with our normal routine. You can even use the .transform()method to automatically drop them. You may want to try other feature selection methods to suit your needs, but Boruta uses one of the most powerful algorithms out there, and is quick and easy to use."
},
{
"code": null,
"e": 4622,
"s": 4611,
"text": "Good luck!"
}
]
|
Area of largest Circle inscribe in N-sided Regular polygon - GeeksforGeeks | 19 Jan, 2022
Given a regular polygon of N sides with side length a. The task is to find the area of the Circle which inscribed in the polygon. Note : This problem is mixed version of This and This Examples:
Input: N = 6, a = 4
Output: 37.6801
Explanation:
In this, the polygon have 6 faces
and as we see in fig.1 we clearly see
that the angle x is 30 degree
so the radius of circle will be ( a / (2 * tan(30)))
Therefore, r = a√3/2
Input: N = 8, a = 8
Output: 292.81
Explanation:
In this, the polygon have 8 faces
and as we see in fig.2 we clearly see
that the angle x is 22.5 degree
so the radius of circle will be ( a / (2 * tan(22.5)))
Therefore, r = a/0.828
Approach: In the figure above, we see the polygon can be divided into N equal triangles. Looking into one of the triangles, we see that the whole angle at the center can be divided into = 360/NSo, angle x = 180/n Now, tan(x) = (a / 2) * rSo, r = a / ( 2 * tan(x))So, Area of the Inscribed Circle is,
A = Πr2 = Π * (a / (2 * tan(x))) * (a / (2*tan(x)))
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find the area of a circle in// inscribed in polygon #include <bits/stdc++.h>using namespace std; // Function to find the area// of a circlefloat InscribedCircleArea(float n, float a){ // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (2 * tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (3.14) * (r) * (r); return Area;} // Driver codeint main(){ // no. of sides float n = 6; // side length float a = 4; cout << InscribedCircleArea(n, a) << endl; return 0;}
// Java Program to find the area of a circle// inscribed in a polygonimport java.io.*; class GFG { // Function to find the area // of a regular polygon static float InscribedCircleArea(float n, float a) { // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (float)(2 * Math.tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (float)(3.14) * (r) * (r); return Area; } // Driver code public static void main(String[] args) { // no. of sides float n = 6; // side length float a = 4; System.out.println(InscribedCircleArea(n, a)); }}
# Python 3 Program to find the area# of a circle inscribed# in a polygonfrom math import tan # Function to find the area of a# circledef InscribedCircleArea(n, a): # Side and side length cannot # be negative if (a < 0 and n < 0): return -1 # degree converted to radians r = a/(2 * tan((180 / n) * 3.14159 / 180)); # area of circle Area = 3.14 * r * r return Area # Driver codeif __name__ == '__main__': a = 4 n = 6 print('{0:.6}'.format(InscribedCircleArea(n, a))) # This code is contributed by# Chandan Agrawal
// C# Program to find the area of a circle// inscribed in a polygonusing System; class GFG{ // Function to find the area// of a regular polygonstatic float InscribedCircleArea(float n, float a){ // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (float)(2 * Math.Tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (float)(3.14) * (r) * (r); return Area;} // Driver codepublic static void Main(){ // no. of sides float n = 6; // side length float a = 4; Console.WriteLine(InscribedCircleArea(n, a));}} // This code is contributed by Ryuga
<?php// PHP Program to find the area// of a circle inscribed// in a polygon // Function to find the area of a// circlefunction InscribedCircleArea($n, $a){ // Side and side length cannot // be negative if ($a < 0 && $n < 0) return -1; // degree converted to radians $r = $a / (2 * tan((180 / $n) * 3.14159 / 180)); // area of circle $Area = 3.14 * $r * $r; return $Area;} // Driver code$a = 4;$n = 6;echo(InscribedCircleArea($n, $a)); // This code contributed by PrinciRaj1992?>
<script>// Javascript Program to find the area of a circle// inscribed in a polygon // Function to find the area // of a regular polygon function InscribedCircleArea( n ,a) { // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians let r = a / (2 * Math.tan((180 / n) * 3.14159 / 180)); // area of circle let Area = (3.14) * (r) * (r); return Area; } // Driver code // no. of sides let n = 6; // side length let a = 4; document.write(InscribedCircleArea(n, a).toFixed(4)); // This code is contributed by 29AjayKumar</script>
37.6801
ankthon
princiraj1992
29AjayKumar
sumitgumber28
area-volume-programs
math
school-programming
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convex Hull | Set 2 (Graham Scan)
Given n line segments, find if any two segments intersect
Closest Pair of Points | O(nlogn) Implementation
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Check whether a given point lies inside a triangle or not
Polygon Clipping | Sutherland–Hodgman Algorithm
Program To Check whether a Triangle is Equilateral, Isosceles or Scalene
Check if two given circles touch or intersect each other
Window to Viewport Transformation in Computer Graphics with Implementation
Sum of Manhattan distances between all pairs of points | [
{
"code": null,
"e": 25062,
"s": 25034,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 25258,
"s": 25062,
"text": "Given a regular polygon of N sides with side length a. The task is to find the area of the Circle which inscribed in the polygon. Note : This problem is mixed version of This and This Examples: "
},
{
"code": null,
"e": 25307,
"s": 25258,
"text": "Input: N = 6, a = 4\nOutput: 37.6801\nExplanation:"
},
{
"code": null,
"e": 25540,
"s": 25307,
"text": "In this, the polygon have 6 faces \nand as we see in fig.1 we clearly see \nthat the angle x is 30 degree \nso the radius of circle will be ( a / (2 * tan(30))) \nTherefore, r = a√3/2\n\nInput: N = 8, a = 8\nOutput: 292.81\nExplanation:"
},
{
"code": null,
"e": 25730,
"s": 25540,
"text": "In this, the polygon have 8 faces \nand as we see in fig.2 we clearly see \nthat the angle x is 22.5 degree \nso the radius of circle will be ( a / (2 * tan(22.5))) \nTherefore, r = a/0.828"
},
{
"code": null,
"e": 26032,
"s": 25730,
"text": "Approach: In the figure above, we see the polygon can be divided into N equal triangles. Looking into one of the triangles, we see that the whole angle at the center can be divided into = 360/NSo, angle x = 180/n Now, tan(x) = (a / 2) * rSo, r = a / ( 2 * tan(x))So, Area of the Inscribed Circle is, "
},
{
"code": null,
"e": 26085,
"s": 26032,
"text": " A = Πr2 = Π * (a / (2 * tan(x))) * (a / (2*tan(x)))"
},
{
"code": null,
"e": 26138,
"s": 26085,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26142,
"s": 26138,
"text": "C++"
},
{
"code": null,
"e": 26147,
"s": 26142,
"text": "Java"
},
{
"code": null,
"e": 26155,
"s": 26147,
"text": "Python3"
},
{
"code": null,
"e": 26158,
"s": 26155,
"text": "C#"
},
{
"code": null,
"e": 26162,
"s": 26158,
"text": "PHP"
},
{
"code": null,
"e": 26173,
"s": 26162,
"text": "Javascript"
},
{
"code": "// C++ Program to find the area of a circle in// inscribed in polygon #include <bits/stdc++.h>using namespace std; // Function to find the area// of a circlefloat InscribedCircleArea(float n, float a){ // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (2 * tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (3.14) * (r) * (r); return Area;} // Driver codeint main(){ // no. of sides float n = 6; // side length float a = 4; cout << InscribedCircleArea(n, a) << endl; return 0;}",
"e": 26788,
"s": 26173,
"text": null
},
{
"code": "// Java Program to find the area of a circle// inscribed in a polygonimport java.io.*; class GFG { // Function to find the area // of a regular polygon static float InscribedCircleArea(float n, float a) { // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (float)(2 * Math.tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (float)(3.14) * (r) * (r); return Area; } // Driver code public static void main(String[] args) { // no. of sides float n = 6; // side length float a = 4; System.out.println(InscribedCircleArea(n, a)); }}",
"e": 27530,
"s": 26788,
"text": null
},
{
"code": "# Python 3 Program to find the area# of a circle inscribed# in a polygonfrom math import tan # Function to find the area of a# circledef InscribedCircleArea(n, a): # Side and side length cannot # be negative if (a < 0 and n < 0): return -1 # degree converted to radians r = a/(2 * tan((180 / n) * 3.14159 / 180)); # area of circle Area = 3.14 * r * r return Area # Driver codeif __name__ == '__main__': a = 4 n = 6 print('{0:.6}'.format(InscribedCircleArea(n, a))) # This code is contributed by# Chandan Agrawal",
"e": 28086,
"s": 27530,
"text": null
},
{
"code": "// C# Program to find the area of a circle// inscribed in a polygonusing System; class GFG{ // Function to find the area// of a regular polygonstatic float InscribedCircleArea(float n, float a){ // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians float r = a / (float)(2 * Math.Tan((180 / n) * 3.14159 / 180)); // area of circle float Area = (float)(3.14) * (r) * (r); return Area;} // Driver codepublic static void Main(){ // no. of sides float n = 6; // side length float a = 4; Console.WriteLine(InscribedCircleArea(n, a));}} // This code is contributed by Ryuga",
"e": 28786,
"s": 28086,
"text": null
},
{
"code": "<?php// PHP Program to find the area// of a circle inscribed// in a polygon // Function to find the area of a// circlefunction InscribedCircleArea($n, $a){ // Side and side length cannot // be negative if ($a < 0 && $n < 0) return -1; // degree converted to radians $r = $a / (2 * tan((180 / $n) * 3.14159 / 180)); // area of circle $Area = 3.14 * $r * $r; return $Area;} // Driver code$a = 4;$n = 6;echo(InscribedCircleArea($n, $a)); // This code contributed by PrinciRaj1992?>",
"e": 29299,
"s": 28786,
"text": null
},
{
"code": "<script>// Javascript Program to find the area of a circle// inscribed in a polygon // Function to find the area // of a regular polygon function InscribedCircleArea( n ,a) { // Side and side length cannot be negative if (a < 0 && n < 0) return -1; // degree converted to radians let r = a / (2 * Math.tan((180 / n) * 3.14159 / 180)); // area of circle let Area = (3.14) * (r) * (r); return Area; } // Driver code // no. of sides let n = 6; // side length let a = 4; document.write(InscribedCircleArea(n, a).toFixed(4)); // This code is contributed by 29AjayKumar</script>",
"e": 29983,
"s": 29299,
"text": null
},
{
"code": null,
"e": 29991,
"s": 29983,
"text": "37.6801"
},
{
"code": null,
"e": 30001,
"s": 29993,
"text": "ankthon"
},
{
"code": null,
"e": 30015,
"s": 30001,
"text": "princiraj1992"
},
{
"code": null,
"e": 30027,
"s": 30015,
"text": "29AjayKumar"
},
{
"code": null,
"e": 30041,
"s": 30027,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30062,
"s": 30041,
"text": "area-volume-programs"
},
{
"code": null,
"e": 30067,
"s": 30062,
"text": "math"
},
{
"code": null,
"e": 30086,
"s": 30067,
"text": "school-programming"
},
{
"code": null,
"e": 30096,
"s": 30086,
"text": "Geometric"
},
{
"code": null,
"e": 30106,
"s": 30096,
"text": "Geometric"
},
{
"code": null,
"e": 30204,
"s": 30106,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30238,
"s": 30204,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 30296,
"s": 30238,
"text": "Given n line segments, find if any two segments intersect"
},
{
"code": null,
"e": 30345,
"s": 30296,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 30396,
"s": 30345,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 30454,
"s": 30396,
"text": "Check whether a given point lies inside a triangle or not"
},
{
"code": null,
"e": 30502,
"s": 30454,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 30575,
"s": 30502,
"text": "Program To Check whether a Triangle is Equilateral, Isosceles or Scalene"
},
{
"code": null,
"e": 30632,
"s": 30575,
"text": "Check if two given circles touch or intersect each other"
},
{
"code": null,
"e": 30707,
"s": 30632,
"text": "Window to Viewport Transformation in Computer Graphics with Implementation"
}
]
|
HTML - Color Names | The following table shows the 16 color names that were introduced in HTML 3.2 −
There are other colors which are not part of HTML or XHTML but they are supported by most of the versions of major browsers.
Some characters are reserved in HTML and they have special meaning when used in HTML document. For example, you cannot use the greater than and less than signs or angle brackets within your HTML text because the browser will treat them differently and will try to draw a meaning related to HTML tag.
HTML processors must support following five special characters listed in the table that follows.
If you want to write <div id = "character"> as a code, then you will have to write as follows −
<!DOCTYPE html>
<html>
<head>
<title>HTML Entities</title>
</head>
<body>
<div id = "character">
</body>
</html>
This will produce the following result −
There is also a long list of special characters in HTML 4.0. In order for these to appear in your document, you can use either the numerical codes or the entity names. For example, to insert a copyright symbol you can use either of the following −
© 2007
or
© 2007
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2454,
"s": 2374,
"text": "The following table shows the 16 color names that were introduced in HTML 3.2 −"
},
{
"code": null,
"e": 2579,
"s": 2454,
"text": "There are other colors which are not part of HTML or XHTML but they are supported by most of the versions of major browsers."
},
{
"code": null,
"e": 2879,
"s": 2579,
"text": "Some characters are reserved in HTML and they have special meaning when used in HTML document. For example, you cannot use the greater than and less than signs or angle brackets within your HTML text because the browser will treat them differently and will try to draw a meaning related to HTML tag."
},
{
"code": null,
"e": 2976,
"s": 2879,
"text": "HTML processors must support following five special characters listed in the table that follows."
},
{
"code": null,
"e": 3072,
"s": 2976,
"text": "If you want to write <div id = \"character\"> as a code, then you will have to write as follows −"
},
{
"code": null,
"e": 3218,
"s": 3072,
"text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML Entities</title>\n </head>\n\n <body>\n <div id = \"character\">\n </body>\n\n</html>"
},
{
"code": null,
"e": 3259,
"s": 3218,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3507,
"s": 3259,
"text": "There is also a long list of special characters in HTML 4.0. In order for these to appear in your document, you can use either the numerical codes or the entity names. For example, to insert a copyright symbol you can use either of the following −"
},
{
"code": null,
"e": 3535,
"s": 3507,
"text": "© 2007\nor\n© 2007\n"
},
{
"code": null,
"e": 3568,
"s": 3535,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3582,
"s": 3568,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3617,
"s": 3582,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3631,
"s": 3617,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3666,
"s": 3631,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3683,
"s": 3666,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3718,
"s": 3683,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3749,
"s": 3718,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3782,
"s": 3749,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3813,
"s": 3782,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3848,
"s": 3813,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3879,
"s": 3848,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 3886,
"s": 3879,
"text": " Print"
},
{
"code": null,
"e": 3897,
"s": 3886,
"text": " Add Notes"
}
]
|
Construct a Turing machine for L = {aibjck | i>j>k; k ≥ 1} - GeeksforGeeks | 24 Aug, 2021
Prerequisite – Turing Machine
In given language L = {aibjck | i>j>k; k ≥ 1}, every string of ‘a’, ‘b’ and ‘c’ have certain number of a’s, then certain number of b’s and then certain number of c’s. The condition is that count of 3rd symbols should be atleast 1. ‘a’ and ‘b’ can have thereafter be as many but count of c is less than count of ‘b’ and count of ‘b’ is less than count of ‘a’. Assume that string is ending with ‘$’. Examples:
Input: a a a b b c
Here a = 3, b = 2, c = 1
Output: ACCEPTED
Input: a a b b c c c
Here a = 2, b = 2, c = 3 but |a|>|b|>|c|
Output: NOT ACCEPTED
Tape Representation:
Approach:
Comparing two elements by making A & D as a single element.After that Comparing A & D.If |C| is greater than |(A, D)|, then it is not accepted.If |D| is greater than |A|, then it is not accepted.Else it is accepted.
Comparing two elements by making A & D as a single element.
After that Comparing A & D.
If |C| is greater than |(A, D)|, then it is not accepted.
If |D| is greater than |A|, then it is not accepted.
Else it is accepted.
Steps:
Step-1: Convert A into X and move right and goto step 2.
Step-2: Keep ignoring A and Y and move towards right. Convert D into Y and move right and goto step-3.
Step-3: Keep ignoring D and Z and move towards right.If C is found make it Z and move left to step 4.If B is found ignore it and move left and goto step-5.
Step-4: Keep ignoring Z, A, Y and D and move towards left.If X is found ignore it and move right and goto step-1.
Step-5: Keep ignoring D, Y and A and move towards left. Ignore X move right and goto step-6.
Step-6: Convert A into X and move right and goto step-7.
Step-7: Keep ignoring Y and A and move towards right.If B is found ignore it and move left and goto step-8.If D make it Y and move right and goto step-5.
Step-8: Stop the Machine (String is accepted)
State transition diagram :
Here, Q0 shows the initial state and Q1, Q2, Q3, Q4, Q5, Q6 shows the transition state and Q7 shows the final state. A, C, D are the variables used and R, L shows right and left.
Explanation:
Using Q0, when A is found make it X and go to right and to state Q1.
On the state Q1, ignore all A and Y and goto right.If D found make it Y and goto right into next state Q2.
In Q2, ignore all D, Z and move right.If B found ignore it, move left and goto the state Q4, If C found make it Z move left and to Q3.
In Q3 state, ignore all Z, D, Y, A and move left.If X found ignore it move right to Q0.
In Q4, ignore all A, Y, D and move left.If X found ignore it move right to state Q6.
In Q6 state, if A found make it X move right to state Q5
In Q5, ignore all A, Y and move right.If D found make it Y and move right to state Q4.If B is found ignore it and move left to Q7
If Q7 state is reached it will produced the result of acceptance of string.
Note: For comparison of |A|, |D|, |C|, the concept of Turing Machine as Comparator is used.
ruhelaa48
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between TCP and UDP
Difference between Process and Thread
Data encryption standard (DES) | Set 1
Types of Network Topology
Difference between Clustered and Non-clustered index
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation | [
{
"code": null,
"e": 24714,
"s": 24686,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 24744,
"s": 24714,
"text": "Prerequisite – Turing Machine"
},
{
"code": null,
"e": 25154,
"s": 24744,
"text": "In given language L = {aibjck | i>j>k; k ≥ 1}, every string of ‘a’, ‘b’ and ‘c’ have certain number of a’s, then certain number of b’s and then certain number of c’s. The condition is that count of 3rd symbols should be atleast 1. ‘a’ and ‘b’ can have thereafter be as many but count of c is less than count of ‘b’ and count of ‘b’ is less than count of ‘a’. Assume that string is ending with ‘$’. Examples: "
},
{
"code": null,
"e": 25326,
"s": 25154,
"text": "Input: a a a b b c \n Here a = 3, b = 2, c = 1\nOutput: ACCEPTED\n \nInput: a a b b c c c\n Here a = 2, b = 2, c = 3 but |a|>|b|>|c|\nOutput: NOT ACCEPTED "
},
{
"code": null,
"e": 25348,
"s": 25326,
"text": "Tape Representation: "
},
{
"code": null,
"e": 25362,
"s": 25350,
"text": "Approach: "
},
{
"code": null,
"e": 25578,
"s": 25362,
"text": "Comparing two elements by making A & D as a single element.After that Comparing A & D.If |C| is greater than |(A, D)|, then it is not accepted.If |D| is greater than |A|, then it is not accepted.Else it is accepted."
},
{
"code": null,
"e": 25638,
"s": 25578,
"text": "Comparing two elements by making A & D as a single element."
},
{
"code": null,
"e": 25666,
"s": 25638,
"text": "After that Comparing A & D."
},
{
"code": null,
"e": 25724,
"s": 25666,
"text": "If |C| is greater than |(A, D)|, then it is not accepted."
},
{
"code": null,
"e": 25777,
"s": 25724,
"text": "If |D| is greater than |A|, then it is not accepted."
},
{
"code": null,
"e": 25798,
"s": 25777,
"text": "Else it is accepted."
},
{
"code": null,
"e": 25807,
"s": 25798,
"text": "Steps: "
},
{
"code": null,
"e": 25866,
"s": 25807,
"text": "Step-1: Convert A into X and move right and goto step 2. "
},
{
"code": null,
"e": 25969,
"s": 25866,
"text": "Step-2: Keep ignoring A and Y and move towards right. Convert D into Y and move right and goto step-3."
},
{
"code": null,
"e": 26125,
"s": 25969,
"text": "Step-3: Keep ignoring D and Z and move towards right.If C is found make it Z and move left to step 4.If B is found ignore it and move left and goto step-5."
},
{
"code": null,
"e": 26239,
"s": 26125,
"text": "Step-4: Keep ignoring Z, A, Y and D and move towards left.If X is found ignore it and move right and goto step-1."
},
{
"code": null,
"e": 26332,
"s": 26239,
"text": "Step-5: Keep ignoring D, Y and A and move towards left. Ignore X move right and goto step-6."
},
{
"code": null,
"e": 26389,
"s": 26332,
"text": "Step-6: Convert A into X and move right and goto step-7."
},
{
"code": null,
"e": 26543,
"s": 26389,
"text": "Step-7: Keep ignoring Y and A and move towards right.If B is found ignore it and move left and goto step-8.If D make it Y and move right and goto step-5."
},
{
"code": null,
"e": 26589,
"s": 26543,
"text": "Step-8: Stop the Machine (String is accepted)"
},
{
"code": null,
"e": 26617,
"s": 26589,
"text": "State transition diagram : "
},
{
"code": null,
"e": 26799,
"s": 26619,
"text": "Here, Q0 shows the initial state and Q1, Q2, Q3, Q4, Q5, Q6 shows the transition state and Q7 shows the final state. A, C, D are the variables used and R, L shows right and left. "
},
{
"code": null,
"e": 26814,
"s": 26799,
"text": "Explanation: "
},
{
"code": null,
"e": 26883,
"s": 26814,
"text": "Using Q0, when A is found make it X and go to right and to state Q1."
},
{
"code": null,
"e": 26990,
"s": 26883,
"text": "On the state Q1, ignore all A and Y and goto right.If D found make it Y and goto right into next state Q2."
},
{
"code": null,
"e": 27125,
"s": 26990,
"text": "In Q2, ignore all D, Z and move right.If B found ignore it, move left and goto the state Q4, If C found make it Z move left and to Q3."
},
{
"code": null,
"e": 27213,
"s": 27125,
"text": "In Q3 state, ignore all Z, D, Y, A and move left.If X found ignore it move right to Q0."
},
{
"code": null,
"e": 27298,
"s": 27213,
"text": "In Q4, ignore all A, Y, D and move left.If X found ignore it move right to state Q6."
},
{
"code": null,
"e": 27355,
"s": 27298,
"text": "In Q6 state, if A found make it X move right to state Q5"
},
{
"code": null,
"e": 27485,
"s": 27355,
"text": "In Q5, ignore all A, Y and move right.If D found make it Y and move right to state Q4.If B is found ignore it and move left to Q7"
},
{
"code": null,
"e": 27561,
"s": 27485,
"text": "If Q7 state is reached it will produced the result of acceptance of string."
},
{
"code": null,
"e": 27654,
"s": 27561,
"text": "Note: For comparison of |A|, |D|, |C|, the concept of Turing Machine as Comparator is used. "
},
{
"code": null,
"e": 27664,
"s": 27654,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27672,
"s": 27664,
"text": "GATE CS"
},
{
"code": null,
"e": 27705,
"s": 27672,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 27803,
"s": 27705,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27835,
"s": 27803,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 27873,
"s": 27835,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 27912,
"s": 27873,
"text": "Data encryption standard (DES) | Set 1"
},
{
"code": null,
"e": 27938,
"s": 27912,
"text": "Types of Network Topology"
},
{
"code": null,
"e": 27991,
"s": 27938,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28050,
"s": 27991,
"text": "Regular Expressions, Regular Grammar and Regular Languages"
},
{
"code": null,
"e": 28081,
"s": 28050,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 28113,
"s": 28081,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 28164,
"s": 28113,
"text": "Difference between Mealy machine and Moore machine"
}
]
|
TF-IDF : A visual explainer and Python Implementation on Presidential Inauguration Speeches | by Anupama Garla | Towards Data Science | Ever asked to explain TF-IDF to non-technical audiences? Here is a visual unpacking of TF-IDF (Term Frequency — Inverse Document Frequency) to share with non-technical colleagues and gain an intuition for the equation that drives ranking search engines from Google to Amazon, and many industry standard Natural Language Processing algorithms. Python example and implementation follows.
We convert a group of texts into numbers to answer questions like:
What are the prevailing themes in each of these documents?
Can you order the documents from most similar to least?
What are the most meaningful words being used?
There are many more questions that can be answered with TF-IDF and Natural Language Processing. But first, let’s understand the terminology data scientists and a lot of our literature like to use.
Terminology
We use document to refer to the pieces of text that we are comparing — these could be newspaper articles, chapters of a book, product descriptions, reviews, homepages, etc. Corpus is a group of such documents. A term is a word.
The two ways to convert words to meaningful numbers are the ‘bag of words’ count vectorizer approach, and TF-IDF vectorizer. Count vectorizer ranks words based on how many times each word appears in each document. TF-IDF takes into account how many words are in the document in relation to this count, as well as how frequently this word is in a document in the corpus. Therefore the TF-IDF value indicates the relative importance of each word in a corpus. Let’s look at how to derive this value.
IDF — Inverse Document Frequency
Is this term a common theme in all documents within our corpus?
IDF answers this question. A value close to 0 indicates the term is very common — and not very helpful in differentiating this document from another. A higher value indicates the term is not very common and could be crucial to understanding the theme of this document.
TF — Term Frequency
Is this term important in this document?
The TF answers this question. A value close to 1 indicates this term is very important to the document — and primarily composed of it. A low value could mean this term is not very important.
TF-IDF — Term Frequency-Inverse Document Frequency
What is the importance of this term in this document, which also accounts for the frequency of this term in the corpus?
TF-IDF answers this question. A value close to 0 indicates the term is not important either in the corpus or the document or both. A larger value indicates the term is unique for the document or the corpus or both. This value works best in relation to other terms in the same document, and other documents.
TF-IDF Matrix
How can I use TF-IDF values to generate insights about documents and terms?
Corpus TF-IDF Values become valuable when you are able to compare terms to each other across documents. You can tell which documents are similar, and which are different — which documents have nothing novel in them, and which ones do. Terms that are in fewer documents, have higher scores, whereas terms in all documents have a score of 0.
Term Document Matrix
By examining the Term Document Matrix that shows the TF-IDF Values for each term in each document, we can learn which documents are most similar, and which terms are most important. This is useful when searching for an item on Google or Amazon, or creating a recommendation system that finds the most similar books, movies, partners, etc.
The uses of the TF-IDF Document — Term matrix are endless, and is built on a relatively simple equation. The power of machine learning is taking these little logics and repeating them across huge datasets to generate new products, tools, insight, and impact. Heck, even small datasets can be used to generate insight. Here is an example in python that looks at Presidential Inauguration Speeches, which were extracted from The American Presidency Project at UCSB.
First, you want to import the Python Libraries you will need.
TfidfVectorizer from the scikit learn library to process text
pandas to use dataframes
from sklearn.feature_extraction.text import TfidfVectorizerimport pandas as pd
Next, select your corpus of documents. I extracted text from the previous 4 President’s inauguration addresses and stored each of them in strings. My corpus list is a list of those strings.
corpus = [document_bush_2001, document_obama_2009, document_trump_2017, document_biden_2021]
There is a lot of options to pre-process your strings by using stemming or lemmatization, but I will skip that here as the focus is on TF-IDF. To use TF-IDF Vectorizer, you store the model in a variable, where you can set many settings. Some starter settings are stop words, ngrams, min and max df. I recommend looking into the scikit learn documentation to find out more.
Stop words are common words you don’t want to consider like ‘the’ or ‘of’. You can always add to stop words, but I find that min and max df takes care of this automatically.
N-grams allows you to choose a range of word lengths — 1, 2, or more — I’m sticking with single words
max-df ignores terms whose document frequency is greater than the selected threshold
min-df ignores terms whose document frequency is less than the selected threshold
vectorizer = TfidfVectorizer(stop_words='english', ngram_range = (1,1), max_df = .6, min_df = .01)
Apply TfidfVectorizer to speech texts. X is a sparse matrix which holds the location of all non-zero values.
X = vectorizer.fit_transform(corpus)
Extract words aka ‘feature names’ from vectorizer.
feature_names = vectorizer.get_feature_names()
Create a dense matrix to convert into a list, and finally a dataframe.
dense = X.todense()denselist = dense.tolist()df = pd.DataFrame(denselist, columns=feature_names)df.head()
My TF-IDF Document-Term Matrix output looks like this:
There it is! Not very interesting, right? What about if we name the Documents, order the words by highest TF-IDF score per Document, and show the 15 most meaningful words by Presidential Inauguration Speech? Let’s see:
data = df.transpose()data.columns = ['document_bush_2001', 'document_obama_2009', 'document_trump_2017', 'document_biden_2021']# Find the top 30 words said by each Presidenttop_dict = {}for c in range(4): top = data.iloc[:,c].sort_values(ascending=False).head(30) top_dict[data.columns[c]]= list(zip(top.index, top.values))# Print the top 15 words said by each Presidentfor president, top_words in top_dict.items(): print(president) print(', '.join([word for word, count in top_words[0:14]])) print('---')
For NLP lovers and political buffs, these results are very revealing. Words are powerful, and we can clearly see what the focus of each candidate was following their election, as well as the state of the union. For instance, Trump is focussed on wealth, dreams, and left vs right. Biden is focussed on democracy, soul, the virus and loss, and doing better. One interesting theme is ‘story’ in both Bush and Biden’s speeches. I wonder what each of them were saying about ‘story’ in their speeches. This is just the tip of the iceberg but I hope that you can see how powerful TF-IDF is at extracting meaning from text. In fact, I used a TFIDF Vectorizer to build Storytimes, a Content-Based Illustrated Children’s Book Recommender for Parents, which you can read about here.
For data scientists in general, the methodology that went into generating TF-IDF can be used in non-textual applications. For instance, if you want to do some feature engineering on already numerical data to make already meaningful features more powerful, you can. For instance let’s say you find that the number of bathrooms and bedrooms in a house are important features in predicting the price of the house, you can engineer an even more predictive feature than the raw number of bathrooms or bedrooms. you can look at the density of bathrooms per bedrooms, let’s call it bathroom_frequency = (2 bathrooms / 3 bedrooms) and multiply that by the rarity of this feature for the neighborhood, let’s call it inverse_neighborhood_frequency = log(# of neighborhood houses / # of neighborhood houses with 2 bathrooms) to get a ‘BF-INF’ feature. In fact, I did something similar in my feature engineering to predict the rental price of airbnb’s in LA, which you can read about here.
TF-IDF is great, and it’s applications are extensive inside and outside of Natural Language Processing. | [
{
"code": null,
"e": 557,
"s": 171,
"text": "Ever asked to explain TF-IDF to non-technical audiences? Here is a visual unpacking of TF-IDF (Term Frequency — Inverse Document Frequency) to share with non-technical colleagues and gain an intuition for the equation that drives ranking search engines from Google to Amazon, and many industry standard Natural Language Processing algorithms. Python example and implementation follows."
},
{
"code": null,
"e": 624,
"s": 557,
"text": "We convert a group of texts into numbers to answer questions like:"
},
{
"code": null,
"e": 683,
"s": 624,
"text": "What are the prevailing themes in each of these documents?"
},
{
"code": null,
"e": 739,
"s": 683,
"text": "Can you order the documents from most similar to least?"
},
{
"code": null,
"e": 786,
"s": 739,
"text": "What are the most meaningful words being used?"
},
{
"code": null,
"e": 983,
"s": 786,
"text": "There are many more questions that can be answered with TF-IDF and Natural Language Processing. But first, let’s understand the terminology data scientists and a lot of our literature like to use."
},
{
"code": null,
"e": 995,
"s": 983,
"text": "Terminology"
},
{
"code": null,
"e": 1223,
"s": 995,
"text": "We use document to refer to the pieces of text that we are comparing — these could be newspaper articles, chapters of a book, product descriptions, reviews, homepages, etc. Corpus is a group of such documents. A term is a word."
},
{
"code": null,
"e": 1720,
"s": 1223,
"text": "The two ways to convert words to meaningful numbers are the ‘bag of words’ count vectorizer approach, and TF-IDF vectorizer. Count vectorizer ranks words based on how many times each word appears in each document. TF-IDF takes into account how many words are in the document in relation to this count, as well as how frequently this word is in a document in the corpus. Therefore the TF-IDF value indicates the relative importance of each word in a corpus. Let’s look at how to derive this value."
},
{
"code": null,
"e": 1753,
"s": 1720,
"text": "IDF — Inverse Document Frequency"
},
{
"code": null,
"e": 1817,
"s": 1753,
"text": "Is this term a common theme in all documents within our corpus?"
},
{
"code": null,
"e": 2086,
"s": 1817,
"text": "IDF answers this question. A value close to 0 indicates the term is very common — and not very helpful in differentiating this document from another. A higher value indicates the term is not very common and could be crucial to understanding the theme of this document."
},
{
"code": null,
"e": 2106,
"s": 2086,
"text": "TF — Term Frequency"
},
{
"code": null,
"e": 2147,
"s": 2106,
"text": "Is this term important in this document?"
},
{
"code": null,
"e": 2338,
"s": 2147,
"text": "The TF answers this question. A value close to 1 indicates this term is very important to the document — and primarily composed of it. A low value could mean this term is not very important."
},
{
"code": null,
"e": 2389,
"s": 2338,
"text": "TF-IDF — Term Frequency-Inverse Document Frequency"
},
{
"code": null,
"e": 2509,
"s": 2389,
"text": "What is the importance of this term in this document, which also accounts for the frequency of this term in the corpus?"
},
{
"code": null,
"e": 2816,
"s": 2509,
"text": "TF-IDF answers this question. A value close to 0 indicates the term is not important either in the corpus or the document or both. A larger value indicates the term is unique for the document or the corpus or both. This value works best in relation to other terms in the same document, and other documents."
},
{
"code": null,
"e": 2830,
"s": 2816,
"text": "TF-IDF Matrix"
},
{
"code": null,
"e": 2906,
"s": 2830,
"text": "How can I use TF-IDF values to generate insights about documents and terms?"
},
{
"code": null,
"e": 3246,
"s": 2906,
"text": "Corpus TF-IDF Values become valuable when you are able to compare terms to each other across documents. You can tell which documents are similar, and which are different — which documents have nothing novel in them, and which ones do. Terms that are in fewer documents, have higher scores, whereas terms in all documents have a score of 0."
},
{
"code": null,
"e": 3267,
"s": 3246,
"text": "Term Document Matrix"
},
{
"code": null,
"e": 3606,
"s": 3267,
"text": "By examining the Term Document Matrix that shows the TF-IDF Values for each term in each document, we can learn which documents are most similar, and which terms are most important. This is useful when searching for an item on Google or Amazon, or creating a recommendation system that finds the most similar books, movies, partners, etc."
},
{
"code": null,
"e": 4070,
"s": 3606,
"text": "The uses of the TF-IDF Document — Term matrix are endless, and is built on a relatively simple equation. The power of machine learning is taking these little logics and repeating them across huge datasets to generate new products, tools, insight, and impact. Heck, even small datasets can be used to generate insight. Here is an example in python that looks at Presidential Inauguration Speeches, which were extracted from The American Presidency Project at UCSB."
},
{
"code": null,
"e": 4132,
"s": 4070,
"text": "First, you want to import the Python Libraries you will need."
},
{
"code": null,
"e": 4194,
"s": 4132,
"text": "TfidfVectorizer from the scikit learn library to process text"
},
{
"code": null,
"e": 4219,
"s": 4194,
"text": "pandas to use dataframes"
},
{
"code": null,
"e": 4298,
"s": 4219,
"text": "from sklearn.feature_extraction.text import TfidfVectorizerimport pandas as pd"
},
{
"code": null,
"e": 4488,
"s": 4298,
"text": "Next, select your corpus of documents. I extracted text from the previous 4 President’s inauguration addresses and stored each of them in strings. My corpus list is a list of those strings."
},
{
"code": null,
"e": 4583,
"s": 4488,
"text": "corpus = [document_bush_2001, document_obama_2009, document_trump_2017, document_biden_2021]"
},
{
"code": null,
"e": 4956,
"s": 4583,
"text": "There is a lot of options to pre-process your strings by using stemming or lemmatization, but I will skip that here as the focus is on TF-IDF. To use TF-IDF Vectorizer, you store the model in a variable, where you can set many settings. Some starter settings are stop words, ngrams, min and max df. I recommend looking into the scikit learn documentation to find out more."
},
{
"code": null,
"e": 5130,
"s": 4956,
"text": "Stop words are common words you don’t want to consider like ‘the’ or ‘of’. You can always add to stop words, but I find that min and max df takes care of this automatically."
},
{
"code": null,
"e": 5232,
"s": 5130,
"text": "N-grams allows you to choose a range of word lengths — 1, 2, or more — I’m sticking with single words"
},
{
"code": null,
"e": 5317,
"s": 5232,
"text": "max-df ignores terms whose document frequency is greater than the selected threshold"
},
{
"code": null,
"e": 5399,
"s": 5317,
"text": "min-df ignores terms whose document frequency is less than the selected threshold"
},
{
"code": null,
"e": 5498,
"s": 5399,
"text": "vectorizer = TfidfVectorizer(stop_words='english', ngram_range = (1,1), max_df = .6, min_df = .01)"
},
{
"code": null,
"e": 5607,
"s": 5498,
"text": "Apply TfidfVectorizer to speech texts. X is a sparse matrix which holds the location of all non-zero values."
},
{
"code": null,
"e": 5644,
"s": 5607,
"text": "X = vectorizer.fit_transform(corpus)"
},
{
"code": null,
"e": 5695,
"s": 5644,
"text": "Extract words aka ‘feature names’ from vectorizer."
},
{
"code": null,
"e": 5742,
"s": 5695,
"text": "feature_names = vectorizer.get_feature_names()"
},
{
"code": null,
"e": 5813,
"s": 5742,
"text": "Create a dense matrix to convert into a list, and finally a dataframe."
},
{
"code": null,
"e": 5919,
"s": 5813,
"text": "dense = X.todense()denselist = dense.tolist()df = pd.DataFrame(denselist, columns=feature_names)df.head()"
},
{
"code": null,
"e": 5974,
"s": 5919,
"text": "My TF-IDF Document-Term Matrix output looks like this:"
},
{
"code": null,
"e": 6193,
"s": 5974,
"text": "There it is! Not very interesting, right? What about if we name the Documents, order the words by highest TF-IDF score per Document, and show the 15 most meaningful words by Presidential Inauguration Speech? Let’s see:"
},
{
"code": null,
"e": 6714,
"s": 6193,
"text": "data = df.transpose()data.columns = ['document_bush_2001', 'document_obama_2009', 'document_trump_2017', 'document_biden_2021']# Find the top 30 words said by each Presidenttop_dict = {}for c in range(4): top = data.iloc[:,c].sort_values(ascending=False).head(30) top_dict[data.columns[c]]= list(zip(top.index, top.values))# Print the top 15 words said by each Presidentfor president, top_words in top_dict.items(): print(president) print(', '.join([word for word, count in top_words[0:14]])) print('---')"
},
{
"code": null,
"e": 7487,
"s": 6714,
"text": "For NLP lovers and political buffs, these results are very revealing. Words are powerful, and we can clearly see what the focus of each candidate was following their election, as well as the state of the union. For instance, Trump is focussed on wealth, dreams, and left vs right. Biden is focussed on democracy, soul, the virus and loss, and doing better. One interesting theme is ‘story’ in both Bush and Biden’s speeches. I wonder what each of them were saying about ‘story’ in their speeches. This is just the tip of the iceberg but I hope that you can see how powerful TF-IDF is at extracting meaning from text. In fact, I used a TFIDF Vectorizer to build Storytimes, a Content-Based Illustrated Children’s Book Recommender for Parents, which you can read about here."
},
{
"code": null,
"e": 8465,
"s": 7487,
"text": "For data scientists in general, the methodology that went into generating TF-IDF can be used in non-textual applications. For instance, if you want to do some feature engineering on already numerical data to make already meaningful features more powerful, you can. For instance let’s say you find that the number of bathrooms and bedrooms in a house are important features in predicting the price of the house, you can engineer an even more predictive feature than the raw number of bathrooms or bedrooms. you can look at the density of bathrooms per bedrooms, let’s call it bathroom_frequency = (2 bathrooms / 3 bedrooms) and multiply that by the rarity of this feature for the neighborhood, let’s call it inverse_neighborhood_frequency = log(# of neighborhood houses / # of neighborhood houses with 2 bathrooms) to get a ‘BF-INF’ feature. In fact, I did something similar in my feature engineering to predict the rental price of airbnb’s in LA, which you can read about here."
}
]
|
Face Detection in 2 Minutes using OpenCV & Python | by Adarsh Menon | Towards Data Science | First of all make sure you have OpenCV installed. You can install it using pip:
pip install opencv-python
Face detection using Haar cascades is a machine learning based approach where a cascade function is trained with a set of input data. OpenCV already contains many pre-trained classifiers for face, eyes, smiles, etc.. Today we will be using the face classifier. You can experiment with other classifiers as well.
You need to download the trained classifier XML file (haarcascade_frontalface_default.xml), which is available in OpenCv’s GitHub repository. Save it to your working location.
To detect faces in images:
A few things to note:
The detection works only on grayscale images. So it is important to convert the color image to grayscale. (line 8)
detectMultiScale function (line 10) is used to detect the faces. It takes 3 arguments — the input image, scaleFactor and minNeighbours. scaleFactor specifies how much the image size is reduced with each scale. minNeighbours specifies how many neighbors each candidate rectangle should have to retain it. You can read about it in detail here. You may have to tweak these values to get the best results.
faces contains a list of coordinates for the rectangular regions where faces were found. We use these coordinates to draw the rectangles in our image.
Results:
Similarly, we can detect faces in videos. As you know videos are basically made up of frames, which are still images. So we perform the face detection for each frame in a video. Here is the code:
The only difference here is that we use an infinite loop to loop through each frame in the video. We use cap.read() to read each frame. The first value returned is a flag that indicates if the frame was read correctly or not. We don’t need it. The second value returned is the still frame on which we will be performing the detection.
Find the code here: https://github.com/adarsh1021/facedetection
Hope you found this useful. Do reach out to me if you have any trouble implementing this or if you need any help.
Email: [email protected]
Social Media: LinkedIn, Twitter, Instagram, YouTube | [
{
"code": null,
"e": 252,
"s": 172,
"text": "First of all make sure you have OpenCV installed. You can install it using pip:"
},
{
"code": null,
"e": 278,
"s": 252,
"text": "pip install opencv-python"
},
{
"code": null,
"e": 590,
"s": 278,
"text": "Face detection using Haar cascades is a machine learning based approach where a cascade function is trained with a set of input data. OpenCV already contains many pre-trained classifiers for face, eyes, smiles, etc.. Today we will be using the face classifier. You can experiment with other classifiers as well."
},
{
"code": null,
"e": 766,
"s": 590,
"text": "You need to download the trained classifier XML file (haarcascade_frontalface_default.xml), which is available in OpenCv’s GitHub repository. Save it to your working location."
},
{
"code": null,
"e": 793,
"s": 766,
"text": "To detect faces in images:"
},
{
"code": null,
"e": 815,
"s": 793,
"text": "A few things to note:"
},
{
"code": null,
"e": 930,
"s": 815,
"text": "The detection works only on grayscale images. So it is important to convert the color image to grayscale. (line 8)"
},
{
"code": null,
"e": 1332,
"s": 930,
"text": "detectMultiScale function (line 10) is used to detect the faces. It takes 3 arguments — the input image, scaleFactor and minNeighbours. scaleFactor specifies how much the image size is reduced with each scale. minNeighbours specifies how many neighbors each candidate rectangle should have to retain it. You can read about it in detail here. You may have to tweak these values to get the best results."
},
{
"code": null,
"e": 1483,
"s": 1332,
"text": "faces contains a list of coordinates for the rectangular regions where faces were found. We use these coordinates to draw the rectangles in our image."
},
{
"code": null,
"e": 1492,
"s": 1483,
"text": "Results:"
},
{
"code": null,
"e": 1688,
"s": 1492,
"text": "Similarly, we can detect faces in videos. As you know videos are basically made up of frames, which are still images. So we perform the face detection for each frame in a video. Here is the code:"
},
{
"code": null,
"e": 2023,
"s": 1688,
"text": "The only difference here is that we use an infinite loop to loop through each frame in the video. We use cap.read() to read each frame. The first value returned is a flag that indicates if the frame was read correctly or not. We don’t need it. The second value returned is the still frame on which we will be performing the detection."
},
{
"code": null,
"e": 2087,
"s": 2023,
"text": "Find the code here: https://github.com/adarsh1021/facedetection"
},
{
"code": null,
"e": 2201,
"s": 2087,
"text": "Hope you found this useful. Do reach out to me if you have any trouble implementing this or if you need any help."
},
{
"code": null,
"e": 2229,
"s": 2201,
"text": "Email: [email protected]"
}
]
|
Market Basket Analysis with Pandas | by Soner Yıldırım | Towards Data Science | Market basket analysis is a common data science practice implemented by retailers. The goal is to discover the associations among items. It is very important to have an idea of what people tend to buy together.
Having a decent market basket analysis provides useful insight for aisle organizations, sales, marketing campaigns, and more.
In this post, we will analyze the grocery dataset available on Kaggle. Let’s start with reading the dataset.
import numpy as npimport pandas as pdgroceries = pd.read_csv("/content/Groceries_dataset.csv")groceries.shape(38765, 3)groceries.head()
The dataset is organized in a way that each row represents an item purchased on a given day by a particular customer.
Before starting on the analysis, we should check the data types, and if there are any missing values.
groceries.isna().sum().sum()0groceries.dtypesMember_number int64 Date object itemDescription object
There is no missing value but the data type of “Date” column should be converted to datetime which can be done with the to_datetime function of pandas.
groceries.Date = pd.to_datetime(groceries.Date)
Let’s first check the average number of items sold per day. One way to do this is group items by date and count the items. We can then plot the result.
import matplotlib.pyplot as pltgroceries[['Date','itemDescription']].groupby('Date').count()\.plot(figsize=(12,6), legend=False, fontsize=14)plt.title('Number of Items Sold per Day', fontsize=18)plt.xlabel('Date',fontsize=14)plt.ylabel('Qty', fontsize=14)
It’d look better if we downsample it. We can use the resample function to decrease the frequency.
groceries[['Date','itemDescription']].groupby('Date').count()\.resample('M').mean()\.plot(figsize=(12,6), legend=False, fontsize=14)plt.title('Number of Items Sold per Day', fontsize=18)plt.xlabel('Date',fontsize=14)plt.ylabel('Qty', fontsize=14)
It seems like business is getting better because item quantities follow a general increasing trend.
Each row in the dataset represents an item purchased by a customer on a given day. If a customer buys three items at one shopping, there will be three rows with same customer number and date but with different item description.
Another measure is the average number of items per shopping which can be calculated by grouping the items by customer number and date.
item_qty = groceries[['Member_number', 'Date','itemDescription']]\.groupby(['Member_number','Date']).count().reset_index()item_qty.head()
Item_qty dataframe shows the number of items in each shopping. For instance, customer 1000 purchased 3 items on 2014–06–24.
The average number of items per shopping is around 2.5 .
item_qty.itemDescription.mean()2.5907
Let’s also check the distribution of the number of items per shopping.
item_qty.itemDescription.plot(figsize=(10,6), kind='hist', legend=False, fontsize=14)plt.title('Histogram of Item Quantities per Shopping', fontsize=18)
Customers are most likely to buy 2–3 items together.
The main focus of market basket analysis is what items are purchased together. One common technique is association rule learning which is a machine learning method to discover relationships among variables. Apriori algorithm is a frequently used algorithm for association rule learning.
We will not go in detail about apriori algorithm or association rule learning in this post. Instead, I will show you a simple way to check which items are frequent purchased together.
Let’s first create a dataframe that contains the items list per shopping.
items = groceries.groupby(['Member_number', 'Date'])\.agg({'itemDescription': lambda x: x.ravel().tolist()}).reset_index()items.head()
Three items purchased by customer 1000 on 2014–06–24 are whole milk, pastry, and salty snack.
We need to determine which items frequently exist in the same rows in “itemDescription” column.
One way is to create combinations of items in each row and count the occurrences of each combination. The itertools of python can be used to accomplish this task.
Here is an example for the first row.
import itertoolslist(itertools.combinations(items.itemDescription[0], 2))
There are 3 items in the first row so we have 3 combinations of pairs. Itertools.combinations do not return repeated combinations (e.g. (‘pastry’, ‘pastry’)) which is what we need.
The following code will to this operation on each row and add the combinations to a list.
combinations_list = []for row in items.itemDescription: combinations = list(itertools.combinations(row, 2)) combinations_list.append(combinations)
We have created a list of lists:
We can create a list from this list of lists by using the explode function of pandas but we need to first convert it to a pandas series.
combination_counts = pd.Series(combinations_list).explode().reset_index(drop=True)
We can now count the number of occurrences of each combination using the value_counts function. Here are the ten most frequent combinations:
The first one is a surprise because it is repeating one. We have made the combinations with no repeated elements. The dataset might contain repating elements. For instance, if a customer buys 2 whole milks at one shopping, there must be two rows of whole milk for that shopping.
We can confirm it by counting the number of whole milks at each shopping.
whole_milk = groceries[groceries.itemDescription == 'whole milk']\.groupby(['Member_number','Date']).count()\.sort_values(by='itemDescription', ascending=False).reset_index()whole_milk.head()
It seems like what we suspect is correct. For instance, customer 1994 purchased 4 whole milks on 2015–11–03. Thus, it totally makes sense to see the most frequent combination is whole milk and whole milk.
We should focus on non-repeating combinations. For instance, the second most frequent combination is whole milk and rolls/buns. The whole milk seems to be dominating the shopping lists.
We have done a simple and basic market basket analysis. The big retailers are doing much more complicated ones and they may approach the analysis from many different perspectives.
However, the overall goal is usually the same which is to be able to predict customers purchasing behaviour.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 382,
"s": 171,
"text": "Market basket analysis is a common data science practice implemented by retailers. The goal is to discover the associations among items. It is very important to have an idea of what people tend to buy together."
},
{
"code": null,
"e": 508,
"s": 382,
"text": "Having a decent market basket analysis provides useful insight for aisle organizations, sales, marketing campaigns, and more."
},
{
"code": null,
"e": 617,
"s": 508,
"text": "In this post, we will analyze the grocery dataset available on Kaggle. Let’s start with reading the dataset."
},
{
"code": null,
"e": 753,
"s": 617,
"text": "import numpy as npimport pandas as pdgroceries = pd.read_csv(\"/content/Groceries_dataset.csv\")groceries.shape(38765, 3)groceries.head()"
},
{
"code": null,
"e": 871,
"s": 753,
"text": "The dataset is organized in a way that each row represents an item purchased on a given day by a particular customer."
},
{
"code": null,
"e": 973,
"s": 871,
"text": "Before starting on the analysis, we should check the data types, and if there are any missing values."
},
{
"code": null,
"e": 1096,
"s": 973,
"text": "groceries.isna().sum().sum()0groceries.dtypesMember_number int64 Date object itemDescription object"
},
{
"code": null,
"e": 1248,
"s": 1096,
"text": "There is no missing value but the data type of “Date” column should be converted to datetime which can be done with the to_datetime function of pandas."
},
{
"code": null,
"e": 1296,
"s": 1248,
"text": "groceries.Date = pd.to_datetime(groceries.Date)"
},
{
"code": null,
"e": 1448,
"s": 1296,
"text": "Let’s first check the average number of items sold per day. One way to do this is group items by date and count the items. We can then plot the result."
},
{
"code": null,
"e": 1704,
"s": 1448,
"text": "import matplotlib.pyplot as pltgroceries[['Date','itemDescription']].groupby('Date').count()\\.plot(figsize=(12,6), legend=False, fontsize=14)plt.title('Number of Items Sold per Day', fontsize=18)plt.xlabel('Date',fontsize=14)plt.ylabel('Qty', fontsize=14)"
},
{
"code": null,
"e": 1802,
"s": 1704,
"text": "It’d look better if we downsample it. We can use the resample function to decrease the frequency."
},
{
"code": null,
"e": 2049,
"s": 1802,
"text": "groceries[['Date','itemDescription']].groupby('Date').count()\\.resample('M').mean()\\.plot(figsize=(12,6), legend=False, fontsize=14)plt.title('Number of Items Sold per Day', fontsize=18)plt.xlabel('Date',fontsize=14)plt.ylabel('Qty', fontsize=14)"
},
{
"code": null,
"e": 2149,
"s": 2049,
"text": "It seems like business is getting better because item quantities follow a general increasing trend."
},
{
"code": null,
"e": 2377,
"s": 2149,
"text": "Each row in the dataset represents an item purchased by a customer on a given day. If a customer buys three items at one shopping, there will be three rows with same customer number and date but with different item description."
},
{
"code": null,
"e": 2512,
"s": 2377,
"text": "Another measure is the average number of items per shopping which can be calculated by grouping the items by customer number and date."
},
{
"code": null,
"e": 2650,
"s": 2512,
"text": "item_qty = groceries[['Member_number', 'Date','itemDescription']]\\.groupby(['Member_number','Date']).count().reset_index()item_qty.head()"
},
{
"code": null,
"e": 2774,
"s": 2650,
"text": "Item_qty dataframe shows the number of items in each shopping. For instance, customer 1000 purchased 3 items on 2014–06–24."
},
{
"code": null,
"e": 2831,
"s": 2774,
"text": "The average number of items per shopping is around 2.5 ."
},
{
"code": null,
"e": 2869,
"s": 2831,
"text": "item_qty.itemDescription.mean()2.5907"
},
{
"code": null,
"e": 2940,
"s": 2869,
"text": "Let’s also check the distribution of the number of items per shopping."
},
{
"code": null,
"e": 3122,
"s": 2940,
"text": "item_qty.itemDescription.plot(figsize=(10,6), kind='hist', legend=False, fontsize=14)plt.title('Histogram of Item Quantities per Shopping', fontsize=18)"
},
{
"code": null,
"e": 3175,
"s": 3122,
"text": "Customers are most likely to buy 2–3 items together."
},
{
"code": null,
"e": 3462,
"s": 3175,
"text": "The main focus of market basket analysis is what items are purchased together. One common technique is association rule learning which is a machine learning method to discover relationships among variables. Apriori algorithm is a frequently used algorithm for association rule learning."
},
{
"code": null,
"e": 3646,
"s": 3462,
"text": "We will not go in detail about apriori algorithm or association rule learning in this post. Instead, I will show you a simple way to check which items are frequent purchased together."
},
{
"code": null,
"e": 3720,
"s": 3646,
"text": "Let’s first create a dataframe that contains the items list per shopping."
},
{
"code": null,
"e": 3855,
"s": 3720,
"text": "items = groceries.groupby(['Member_number', 'Date'])\\.agg({'itemDescription': lambda x: x.ravel().tolist()}).reset_index()items.head()"
},
{
"code": null,
"e": 3949,
"s": 3855,
"text": "Three items purchased by customer 1000 on 2014–06–24 are whole milk, pastry, and salty snack."
},
{
"code": null,
"e": 4045,
"s": 3949,
"text": "We need to determine which items frequently exist in the same rows in “itemDescription” column."
},
{
"code": null,
"e": 4208,
"s": 4045,
"text": "One way is to create combinations of items in each row and count the occurrences of each combination. The itertools of python can be used to accomplish this task."
},
{
"code": null,
"e": 4246,
"s": 4208,
"text": "Here is an example for the first row."
},
{
"code": null,
"e": 4320,
"s": 4246,
"text": "import itertoolslist(itertools.combinations(items.itemDescription[0], 2))"
},
{
"code": null,
"e": 4501,
"s": 4320,
"text": "There are 3 items in the first row so we have 3 combinations of pairs. Itertools.combinations do not return repeated combinations (e.g. (‘pastry’, ‘pastry’)) which is what we need."
},
{
"code": null,
"e": 4591,
"s": 4501,
"text": "The following code will to this operation on each row and add the combinations to a list."
},
{
"code": null,
"e": 4744,
"s": 4591,
"text": "combinations_list = []for row in items.itemDescription: combinations = list(itertools.combinations(row, 2)) combinations_list.append(combinations)"
},
{
"code": null,
"e": 4777,
"s": 4744,
"text": "We have created a list of lists:"
},
{
"code": null,
"e": 4914,
"s": 4777,
"text": "We can create a list from this list of lists by using the explode function of pandas but we need to first convert it to a pandas series."
},
{
"code": null,
"e": 4997,
"s": 4914,
"text": "combination_counts = pd.Series(combinations_list).explode().reset_index(drop=True)"
},
{
"code": null,
"e": 5138,
"s": 4997,
"text": "We can now count the number of occurrences of each combination using the value_counts function. Here are the ten most frequent combinations:"
},
{
"code": null,
"e": 5417,
"s": 5138,
"text": "The first one is a surprise because it is repeating one. We have made the combinations with no repeated elements. The dataset might contain repating elements. For instance, if a customer buys 2 whole milks at one shopping, there must be two rows of whole milk for that shopping."
},
{
"code": null,
"e": 5491,
"s": 5417,
"text": "We can confirm it by counting the number of whole milks at each shopping."
},
{
"code": null,
"e": 5683,
"s": 5491,
"text": "whole_milk = groceries[groceries.itemDescription == 'whole milk']\\.groupby(['Member_number','Date']).count()\\.sort_values(by='itemDescription', ascending=False).reset_index()whole_milk.head()"
},
{
"code": null,
"e": 5888,
"s": 5683,
"text": "It seems like what we suspect is correct. For instance, customer 1994 purchased 4 whole milks on 2015–11–03. Thus, it totally makes sense to see the most frequent combination is whole milk and whole milk."
},
{
"code": null,
"e": 6074,
"s": 5888,
"text": "We should focus on non-repeating combinations. For instance, the second most frequent combination is whole milk and rolls/buns. The whole milk seems to be dominating the shopping lists."
},
{
"code": null,
"e": 6254,
"s": 6074,
"text": "We have done a simple and basic market basket analysis. The big retailers are doing much more complicated ones and they may approach the analysis from many different perspectives."
},
{
"code": null,
"e": 6363,
"s": 6254,
"text": "However, the overall goal is usually the same which is to be able to predict customers purchasing behaviour."
}
]
|
p5.js shader() Method - GeeksforGeeks | 24 Mar, 2021
The shader() function in p5.js makes it possible to use a custom shader to fill in shapes in the WEBGL mode. A custom shader could be loaded using the loadShader() method, and it could even be programmed to have moving graphics on them.
Syntax:
shader( [s] )
Parameter: This function has a single parameter as mentioned above and discussed below:
s: It is a p5.Shader object that contains the desired shader to be used for filling shapes.
The below example demonstrates the shader() function in p5.js:
Example: This example shows how to draw a circle with a shader.
Javascript
// Variable to hold the shader objectlet circleShader; function preload() { // Load the shader files with loadShader() circleShader = loadShader('basic.vert', 'basic.frag');} function setup() { // Shaders require WEBGL mode to work createCanvas(400, 400, WEBGL); noStroke();} function draw() { // The shader() function sets the active // shader with our shader shader(circleShader); // Setting the time and resolution of our shader circleShader.setUniform( 'resolution', [width, height] ); circleShader.setUniform( 'time', frameCount * 0.05 ); // Using rect() to give some // geometry on the screen rect(0, 0, width, height);} function windowResized() { resizeCanvas(windowWidth, windowHeight);}
basic.vert
attribute vec3 aPosition;
attribute vec2 aTexCoord;
void main() {
// Copy the position data into a vec4,
// using 1.0 as the w component
vec4 positionVec4 = vec4(aPosition, 1.0);
// Scale the rect by two, and move it to
// the center of the screen
positionVec4.xy = positionVec4.xy * 2.0 - 1.0;
// Send the vertex information on to
// the fragment shader
gl_Position = positionVec4;
}
basic.frag
precision mediump float;
varying vec2 vTexCoord;
// We need the sketch resolution to
// perform some calculations
uniform vec2 resolution;
uniform float time;
// Function that turns an rgb value that
// goes from 0 - 255 into 0.0 - 1.0
vec3 rgb(float r, float g, float b){
return vec3(r / 255.0, g / 255.0, b / 255.0);
}
vec4 circle(float x, float y, float diam, vec3 col){
vec2 coord = gl_FragCoord.xy;
// Flip the y coordinates for p5
coord.y = resolution.y - coord.y;
// Store the x and y in a vec2
vec2 p = vec2(x, y);
// Calculate the circle
// First get the difference of the circles
// location and the screen coordinates
// compute the length of that result and
// subtract the radius
// this creates a black and white mask that
// we can use to multiply against our colors
float c = length( p - coord) - diam*0.5;
// Restrict the results to be between
// 0.0 and 1.0
c = clamp(c, 0.0,1.0);
// Send out the color, with the circle
// as the alpha channel
return vec4(rgb(col.r, col.g, col.b), 1.0 - c);
}
void main() {
// The width and height of our rectangle
float width = 100.0;
float height = 200.0;
// the center of the screen is just the
// resolution divided in half
vec2 center = resolution * 0.5;
// Lets make our rect in the center of the
// screen. We have to subtract half of it's
// width and height just like in p5
float x = center.x ;
float y = center.y ;
// add an oscillation to x
x += sin(time) * 200.0;
// A color for the rect
vec3 grn = vec3(200.0, 240.0, 200.0);
// A color for the bg
vec3 magenta = rgb(240.0,150.0,240.0);
// Call our circle function
vec4 circ = circle(x, y, 200.0, grn);
// out put the final image
// Mix the circle with the background color
// using the circles alpha
circ.rgb = mix(magenta, circ.rgb, circ.a);
gl_FragColor = vec4( circ.rgb ,1.0);
}
Output:
Reference: https://p5js.org/reference/#/p5/shader
JavaScript-p5.js
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25017,
"s": 24989,
"text": "\n24 Mar, 2021"
},
{
"code": null,
"e": 25254,
"s": 25017,
"text": "The shader() function in p5.js makes it possible to use a custom shader to fill in shapes in the WEBGL mode. A custom shader could be loaded using the loadShader() method, and it could even be programmed to have moving graphics on them."
},
{
"code": null,
"e": 25262,
"s": 25254,
"text": "Syntax:"
},
{
"code": null,
"e": 25276,
"s": 25262,
"text": "shader( [s] )"
},
{
"code": null,
"e": 25364,
"s": 25276,
"text": "Parameter: This function has a single parameter as mentioned above and discussed below:"
},
{
"code": null,
"e": 25456,
"s": 25364,
"text": "s: It is a p5.Shader object that contains the desired shader to be used for filling shapes."
},
{
"code": null,
"e": 25519,
"s": 25456,
"text": "The below example demonstrates the shader() function in p5.js:"
},
{
"code": null,
"e": 25583,
"s": 25519,
"text": "Example: This example shows how to draw a circle with a shader."
},
{
"code": null,
"e": 25594,
"s": 25583,
"text": "Javascript"
},
{
"code": "// Variable to hold the shader objectlet circleShader; function preload() { // Load the shader files with loadShader() circleShader = loadShader('basic.vert', 'basic.frag');} function setup() { // Shaders require WEBGL mode to work createCanvas(400, 400, WEBGL); noStroke();} function draw() { // The shader() function sets the active // shader with our shader shader(circleShader); // Setting the time and resolution of our shader circleShader.setUniform( 'resolution', [width, height] ); circleShader.setUniform( 'time', frameCount * 0.05 ); // Using rect() to give some // geometry on the screen rect(0, 0, width, height);} function windowResized() { resizeCanvas(windowWidth, windowHeight);}",
"e": 26328,
"s": 25594,
"text": null
},
{
"code": null,
"e": 26339,
"s": 26328,
"text": "basic.vert"
},
{
"code": null,
"e": 26737,
"s": 26339,
"text": "attribute vec3 aPosition;\nattribute vec2 aTexCoord;\n\nvoid main() {\n\n // Copy the position data into a vec4,\n // using 1.0 as the w component\n vec4 positionVec4 = vec4(aPosition, 1.0);\n\n // Scale the rect by two, and move it to\n // the center of the screen\n positionVec4.xy = positionVec4.xy * 2.0 - 1.0;\n\n // Send the vertex information on to\n // the fragment shader\n gl_Position = positionVec4;\n}"
},
{
"code": null,
"e": 26748,
"s": 26737,
"text": "basic.frag"
},
{
"code": null,
"e": 28703,
"s": 26748,
"text": "precision mediump float;\n\nvarying vec2 vTexCoord;\n\n// We need the sketch resolution to\n// perform some calculations\nuniform vec2 resolution;\nuniform float time;\n\n// Function that turns an rgb value that\n// goes from 0 - 255 into 0.0 - 1.0\nvec3 rgb(float r, float g, float b){\n return vec3(r / 255.0, g / 255.0, b / 255.0);\n}\n\nvec4 circle(float x, float y, float diam, vec3 col){\n vec2 coord = gl_FragCoord.xy;\n // Flip the y coordinates for p5\n coord.y = resolution.y - coord.y;\n\n // Store the x and y in a vec2 \n vec2 p = vec2(x, y);\n\n // Calculate the circle\n // First get the difference of the circles \n // location and the screen coordinates\n // compute the length of that result and \n // subtract the radius\n // this creates a black and white mask that \n // we can use to multiply against our colors\n float c = length( p - coord) - diam*0.5;\n\n // Restrict the results to be between \n // 0.0 and 1.0\n c = clamp(c, 0.0,1.0);\n \n // Send out the color, with the circle\n // as the alpha channel \n return vec4(rgb(col.r, col.g, col.b), 1.0 - c); \n}\n\n\nvoid main() {\n\n // The width and height of our rectangle\n float width = 100.0;\n float height = 200.0;\n\n // the center of the screen is just the\n // resolution divided in half\n vec2 center = resolution * 0.5;\n\n // Lets make our rect in the center of the\n // screen. We have to subtract half of it's\n // width and height just like in p5\n float x = center.x ;\n float y = center.y ;\n\n // add an oscillation to x\n\n x += sin(time) * 200.0;\n\n // A color for the rect \n vec3 grn = vec3(200.0, 240.0, 200.0);\n\n // A color for the bg\n vec3 magenta = rgb(240.0,150.0,240.0);\n\n // Call our circle function\n vec4 circ = circle(x, y, 200.0, grn);\n // out put the final image\n\n // Mix the circle with the background color\n // using the circles alpha\n circ.rgb = mix(magenta, circ.rgb, circ.a);\n\n gl_FragColor = vec4( circ.rgb ,1.0);\n}"
},
{
"code": null,
"e": 28711,
"s": 28703,
"text": "Output:"
},
{
"code": null,
"e": 28761,
"s": 28711,
"text": "Reference: https://p5js.org/reference/#/p5/shader"
},
{
"code": null,
"e": 28778,
"s": 28761,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 28785,
"s": 28778,
"text": "Picked"
},
{
"code": null,
"e": 28796,
"s": 28785,
"text": "JavaScript"
},
{
"code": null,
"e": 28813,
"s": 28796,
"text": "Web Technologies"
},
{
"code": null,
"e": 28911,
"s": 28813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28920,
"s": 28911,
"text": "Comments"
},
{
"code": null,
"e": 28933,
"s": 28920,
"text": "Old Comments"
},
{
"code": null,
"e": 28994,
"s": 28933,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29035,
"s": 28994,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29075,
"s": 29035,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29129,
"s": 29075,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29191,
"s": 29129,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 29247,
"s": 29191,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29280,
"s": 29247,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29342,
"s": 29280,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29385,
"s": 29342,
"text": "How to fetch data from an API in ReactJS ?"
}
]
|
Set a container that spans the full width of the screen with Bootstrap | Use the .container-fluid class in Bootstrap to set a container that spans the full width of the screen.
You can try to run the following code to implement the container-fluid class
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/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.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container-fluid">
<h3>Container fluid</h3>
<div class = "w-100 bg-danger">Normal width</div>
<div class = "w-75 bg-warning">Width is 75%</div>
<div class = "w-50 bg-success">Width is 50%</div>
<div class = "w-25 bg-warning">Width is 25%</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Use the .container-fluid class in Bootstrap to set a container that spans the full width of the screen."
},
{
"code": null,
"e": 1243,
"s": 1166,
"text": "You can try to run the following code to implement the container-fluid class"
},
{
"code": null,
"e": 1253,
"s": 1243,
"text": "Live Demo"
},
{
"code": null,
"e": 1994,
"s": 1253,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/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.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container-fluid\">\n <h3>Container fluid</h3>\n <div class = \"w-100 bg-danger\">Normal width</div>\n <div class = \"w-75 bg-warning\">Width is 75%</div>\n <div class = \"w-50 bg-success\">Width is 50%</div>\n <div class = \"w-25 bg-warning\">Width is 25%</div>\n </div>\n </body>\n</html>"
}
]
|
atomic.AddInt32() Function in Golang With Examples - GeeksforGeeks | 30 Dec, 2020
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt32() function in Golang is used to atomically add delta to the *addr. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions.
Syntax:
func AddInt32(addr *int32, delta int32) (new int32)
Here, addr indicates address and delta indicates a small number of bits greater than zero.
Note: (*int32) is the pointer to a int32 value. Moreover, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.Return value: It adds addr and delta atomically and returns a new value.
Example 1:
Go
// Golang Program to illustrate the usage of// AddInt32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Main functionfunc main() { // Assigning values to the int32 var ( i int32 = 97 j int32 = 48 k int32 = 34754567 l int32 = -355363 ) // Assigning constant // values to int32 const ( x int32 = 4 y int32 = 2 ) // Calling AddInt32 method // with its parameters res_1 := atomic.AddInt32(&i, y) res_2 := atomic.AddInt32(&j, y-1) res_3 := atomic.AddInt32(&k, x-1) res_4 := atomic.AddInt32(&l, x) // Displays the output after adding // addr and delta atomically fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4)}
Output:
99
49
34754570
-355359
Example 2:
Go
// Golang Program to illustrate the usage of// AddInt32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( "fmt" "sync/atomic") // Defining addr of type int32type addr int32 // function that adds addr and deltafunc (x *addr) add() int32 { // Calling AddInt32() function // with its parameter return atomic.AddInt32((*int32)(x), 2)} // Main functionfunc main() { // Defining x var x addr // For loop to increment // the value of x for i := 1; i < 7; i++ { // Displays the new value // after adding delta and addr fmt.Println(x.add()) }}
Output:
2
4
6
8
10
12
In the above example, we have defined a function add that returns the output returned from calling AddInt32 method. In the main function, we have defined a “for” loop that will increment the value of ‘x’ in each call. Here, the second parameter of the AddInt32() method is constant and only the value of the first parameter is variable. However, the output of the previous call will be the value of the first parameter of the AddInt32() method in the next call until the loop stops.
Lets see how above example works:
1st parameter = 0, 2nd parameter = 2 // returns ( 0 + 2 = 2)
// Now, the above output is 1st parameter in next call to AddInt32() method
1st parameter = 2, 2nd parameter = 2 // returns ( 2 + 2 = 4)
1st parameter = 4, 2nd parameter = 2 // returns ( 4 + 2 = 6) and so on.
jpmnina
GoLang-atomic
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Time Durations in Golang
Strings in Golang
Loops in Go Language
How to convert a string in uppercase in Golang?
Structures in Golang
Class and Object in Golang | [
{
"code": null,
"e": 24380,
"s": 24352,
"text": "\n30 Dec, 2020"
},
{
"code": null,
"e": 24716,
"s": 24380,
"text": "In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt32() function in Golang is used to atomically add delta to the *addr. This function is defined under the atomic package. Here, you need to import “sync/atomic” package in order to use these functions."
},
{
"code": null,
"e": 24725,
"s": 24716,
"text": "Syntax: "
},
{
"code": null,
"e": 24777,
"s": 24725,
"text": "func AddInt32(addr *int32, delta int32) (new int32)"
},
{
"code": null,
"e": 24868,
"s": 24777,
"text": "Here, addr indicates address and delta indicates a small number of bits greater than zero."
},
{
"code": null,
"e": 25083,
"s": 24868,
"text": "Note: (*int32) is the pointer to a int32 value. Moreover, int32 contains the set of all signed 32-bit integers from -2147483648 to 2147483647.Return value: It adds addr and delta atomically and returns a new value."
},
{
"code": null,
"e": 25094,
"s": 25083,
"text": "Example 1:"
},
{
"code": null,
"e": 25097,
"s": 25094,
"text": "Go"
},
{
"code": "// Golang Program to illustrate the usage of// AddInt32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Main functionfunc main() { // Assigning values to the int32 var ( i int32 = 97 j int32 = 48 k int32 = 34754567 l int32 = -355363 ) // Assigning constant // values to int32 const ( x int32 = 4 y int32 = 2 ) // Calling AddInt32 method // with its parameters res_1 := atomic.AddInt32(&i, y) res_2 := atomic.AddInt32(&j, y-1) res_3 := atomic.AddInt32(&k, x-1) res_4 := atomic.AddInt32(&l, x) // Displays the output after adding // addr and delta atomically fmt.Println(res_1) fmt.Println(res_2) fmt.Println(res_3) fmt.Println(res_4)}",
"e": 25904,
"s": 25097,
"text": null
},
{
"code": null,
"e": 25913,
"s": 25904,
"text": "Output: "
},
{
"code": null,
"e": 25936,
"s": 25913,
"text": "99\n49\n34754570\n-355359"
},
{
"code": null,
"e": 25947,
"s": 25936,
"text": "Example 2:"
},
{
"code": null,
"e": 25950,
"s": 25947,
"text": "Go"
},
{
"code": "// Golang Program to illustrate the usage of// AddInt32 function // Including main packagepackage main // importing fmt and sync/atomicimport ( \"fmt\" \"sync/atomic\") // Defining addr of type int32type addr int32 // function that adds addr and deltafunc (x *addr) add() int32 { // Calling AddInt32() function // with its parameter return atomic.AddInt32((*int32)(x), 2)} // Main functionfunc main() { // Defining x var x addr // For loop to increment // the value of x for i := 1; i < 7; i++ { // Displays the new value // after adding delta and addr fmt.Println(x.add()) }}",
"e": 26581,
"s": 25950,
"text": null
},
{
"code": null,
"e": 26590,
"s": 26581,
"text": "Output: "
},
{
"code": null,
"e": 26604,
"s": 26590,
"text": "2\n4\n6\n8\n10\n12"
},
{
"code": null,
"e": 27087,
"s": 26604,
"text": "In the above example, we have defined a function add that returns the output returned from calling AddInt32 method. In the main function, we have defined a “for” loop that will increment the value of ‘x’ in each call. Here, the second parameter of the AddInt32() method is constant and only the value of the first parameter is variable. However, the output of the previous call will be the value of the first parameter of the AddInt32() method in the next call until the loop stops."
},
{
"code": null,
"e": 27122,
"s": 27087,
"text": "Lets see how above example works: "
},
{
"code": null,
"e": 27399,
"s": 27122,
"text": "1st parameter = 0, 2nd parameter = 2 // returns ( 0 + 2 = 2)\n\n// Now, the above output is 1st parameter in next call to AddInt32() method\n1st parameter = 2, 2nd parameter = 2 // returns ( 2 + 2 = 4)\n1st parameter = 4, 2nd parameter = 2 // returns ( 4 + 2 = 6) and so on."
},
{
"code": null,
"e": 27409,
"s": 27401,
"text": "jpmnina"
},
{
"code": null,
"e": 27423,
"s": 27409,
"text": "GoLang-atomic"
},
{
"code": null,
"e": 27435,
"s": 27423,
"text": "Go Language"
},
{
"code": null,
"e": 27533,
"s": 27435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27542,
"s": 27533,
"text": "Comments"
},
{
"code": null,
"e": 27555,
"s": 27542,
"text": "Old Comments"
},
{
"code": null,
"e": 27584,
"s": 27555,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 27608,
"s": 27584,
"text": "Defer Keyword in Golang"
},
{
"code": null,
"e": 27654,
"s": 27608,
"text": "time.Parse() Function in Golang With Examples"
},
{
"code": null,
"e": 27688,
"s": 27654,
"text": "Anonymous function in Go Language"
},
{
"code": null,
"e": 27713,
"s": 27688,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 27731,
"s": 27713,
"text": "Strings in Golang"
},
{
"code": null,
"e": 27752,
"s": 27731,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 27800,
"s": 27752,
"text": "How to convert a string in uppercase in Golang?"
},
{
"code": null,
"e": 27821,
"s": 27800,
"text": "Structures in Golang"
}
]
|
PySpark - Environment Setup | In this chapter, we will understand the environment setup of PySpark.
Note − This is considering that you have Java and Scala installed on your computer.
Let us now download and set up PySpark with the following steps.
Step 1 − Go to the official Apache Spark download page and download the latest version of Apache Spark available there. In this tutorial, we are using spark-2.1.0-bin-hadoop2.7.
Step 2 − Now, extract the downloaded Spark tar file. By default, it will get downloaded in Downloads directory.
# tar -xvf Downloads/spark-2.1.0-bin-hadoop2.7.tgz
It will create a directory spark-2.1.0-bin-hadoop2.7. Before starting PySpark, you need to set the following environments to set the Spark path and the Py4j path.
export SPARK_HOME = /home/hadoop/spark-2.1.0-bin-hadoop2.7
export PATH = $PATH:/home/hadoop/spark-2.1.0-bin-hadoop2.7/bin
export PYTHONPATH = $SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip:$PYTHONPATH
export PATH = $SPARK_HOME/python:$PATH
Or, to set the above environments globally, put them in the .bashrc file. Then run the following command for the environments to work.
# source .bashrc
Now that we have all the environments set, let us go to Spark directory and invoke PySpark shell by running the following command −
# ./bin/pyspark
This will start your PySpark shell.
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Welcome to
____ __
/ __/__ ___ _____/ /__
_\ \/ _ \/ _ `/ __/ '_/
/__ / .__/\_,_/_/ /_/\_\ version 2.1.0
/_/
Using Python version 2.7.12 (default, Nov 19 2016 06:48:10)
SparkSession available as 'spark'.
<<<
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1875,
"s": 1805,
"text": "In this chapter, we will understand the environment setup of PySpark."
},
{
"code": null,
"e": 1959,
"s": 1875,
"text": "Note − This is considering that you have Java and Scala installed on your computer."
},
{
"code": null,
"e": 2024,
"s": 1959,
"text": "Let us now download and set up PySpark with the following steps."
},
{
"code": null,
"e": 2202,
"s": 2024,
"text": "Step 1 − Go to the official Apache Spark download page and download the latest version of Apache Spark available there. In this tutorial, we are using spark-2.1.0-bin-hadoop2.7."
},
{
"code": null,
"e": 2314,
"s": 2202,
"text": "Step 2 − Now, extract the downloaded Spark tar file. By default, it will get downloaded in Downloads directory."
},
{
"code": null,
"e": 2366,
"s": 2314,
"text": "# tar -xvf Downloads/spark-2.1.0-bin-hadoop2.7.tgz\n"
},
{
"code": null,
"e": 2529,
"s": 2366,
"text": "It will create a directory spark-2.1.0-bin-hadoop2.7. Before starting PySpark, you need to set the following environments to set the Spark path and the Py4j path."
},
{
"code": null,
"e": 2785,
"s": 2529,
"text": "export SPARK_HOME = /home/hadoop/spark-2.1.0-bin-hadoop2.7\nexport PATH = $PATH:/home/hadoop/spark-2.1.0-bin-hadoop2.7/bin\nexport PYTHONPATH = $SPARK_HOME/python:$SPARK_HOME/python/lib/py4j-0.10.4-src.zip:$PYTHONPATH\nexport PATH = $SPARK_HOME/python:$PATH\n"
},
{
"code": null,
"e": 2920,
"s": 2785,
"text": "Or, to set the above environments globally, put them in the .bashrc file. Then run the following command for the environments to work."
},
{
"code": null,
"e": 2938,
"s": 2920,
"text": "# source .bashrc\n"
},
{
"code": null,
"e": 3070,
"s": 2938,
"text": "Now that we have all the environments set, let us go to Spark directory and invoke PySpark shell by running the following command −"
},
{
"code": null,
"e": 3087,
"s": 3070,
"text": "# ./bin/pyspark\n"
},
{
"code": null,
"e": 3123,
"s": 3087,
"text": "This will start your PySpark shell."
},
{
"code": null,
"e": 3523,
"s": 3123,
"text": "Python 2.7.12 (default, Nov 19 2016, 06:48:10) \n[GCC 5.4.0 20160609] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\nWelcome to\n ____ __\n / __/__ ___ _____/ /__\n _\\ \\/ _ \\/ _ `/ __/ '_/\n /__ / .__/\\_,_/_/ /_/\\_\\ version 2.1.0\n /_/\nUsing Python version 2.7.12 (default, Nov 19 2016 06:48:10)\nSparkSession available as 'spark'.\n<<<\n"
},
{
"code": null,
"e": 3530,
"s": 3523,
"text": " Print"
},
{
"code": null,
"e": 3541,
"s": 3530,
"text": " Add Notes"
}
]
|
How to multiply two matrices using pointers in C? | Pointer is a variable that stores the address of another variable.
Pointer saves the memory space.
The execution time of a pointer is faster because of the direct access to a memory location.
With the help of pointers, the memory is accessed efficiently i.e. memory is allocated and deallocated dynamically.
Pointers are used with data structures.
Pointer declaration, initialization and accessing
Consider the following statement −
int qty = 179;
In the memory, the variable can be represented as shown below −
Declaring a pointer can be done as shown below −
Int *p;
It means ‘p’ is a pointer variable which holds the address of another integer variable.
The address operator (&) is used to initialize a pointer variable.
For example,
int qty = 175;
int *p;
p= &qty;
To access the value of the variable, indirection operator (*) is used.
Following is the C program to multiply the two matrices by using pointers −
Live Demo
#include <stdio.h>
#define ROW 3
#define COL 3
/* Function declarations */
void matrixInput(int mat[][COL]);
void matrixPrint(int mat[][COL]);
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);
int main() {
int mat1[ROW][COL];
int mat2[ROW][COL];
int product[ROW][COL];
printf("Enter elements in first matrix of size %dx%d\n", ROW, COL);
matrixInput(mat1);
printf("Enter elements in second matrix of size %dx%d\n", ROW, COL);
matrixInput(mat2);
matrixMultiply(mat1, mat2, product);
printf("Product of both matrices is : \n");
matrixPrint(product);
return 0;
}
void matrixInput(int mat[][COL]) {
int row, col;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
scanf("%d", (*(mat + row) + col));
}
}
}
void matrixPrint(int mat[][COL]) {
int row, col;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
printf("%d ", *(*(mat + row) + col));
}
printf("\n");
}
}
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]) {
int row, col, i;
int sum;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
sum = 0;
for (i = 0; i < COL; i++) {
sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));
}
*(*(res + row) + col) = sum;
}
}
}
When the above program is executed, it produces the following output −
Enter elements in first matrix of size 3x3
2 3 1
2 5 6
2 6 8
Enter elements in second matrix of size 3x3
1 2 1
2 3 4
5 6 7
Product of both matrices is :
13 19 21
42 55 64
54 70 82 | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Pointer is a variable that stores the address of another variable."
},
{
"code": null,
"e": 1161,
"s": 1129,
"text": "Pointer saves the memory space."
},
{
"code": null,
"e": 1254,
"s": 1161,
"text": "The execution time of a pointer is faster because of the direct access to a memory location."
},
{
"code": null,
"e": 1370,
"s": 1254,
"text": "With the help of pointers, the memory is accessed efficiently i.e. memory is allocated and deallocated dynamically."
},
{
"code": null,
"e": 1410,
"s": 1370,
"text": "Pointers are used with data structures."
},
{
"code": null,
"e": 1460,
"s": 1410,
"text": "Pointer declaration, initialization and accessing"
},
{
"code": null,
"e": 1495,
"s": 1460,
"text": "Consider the following statement −"
},
{
"code": null,
"e": 1510,
"s": 1495,
"text": "int qty = 179;"
},
{
"code": null,
"e": 1574,
"s": 1510,
"text": "In the memory, the variable can be represented as shown below −"
},
{
"code": null,
"e": 1623,
"s": 1574,
"text": "Declaring a pointer can be done as shown below −"
},
{
"code": null,
"e": 1631,
"s": 1623,
"text": "Int *p;"
},
{
"code": null,
"e": 1719,
"s": 1631,
"text": "It means ‘p’ is a pointer variable which holds the address of another integer variable."
},
{
"code": null,
"e": 1786,
"s": 1719,
"text": "The address operator (&) is used to initialize a pointer variable."
},
{
"code": null,
"e": 1799,
"s": 1786,
"text": "For example,"
},
{
"code": null,
"e": 1831,
"s": 1799,
"text": "int qty = 175;\nint *p;\np= &qty;"
},
{
"code": null,
"e": 1902,
"s": 1831,
"text": "To access the value of the variable, indirection operator (*) is used."
},
{
"code": null,
"e": 1978,
"s": 1902,
"text": "Following is the C program to multiply the two matrices by using pointers −"
},
{
"code": null,
"e": 1989,
"s": 1978,
"text": " Live Demo"
},
{
"code": null,
"e": 3369,
"s": 1989,
"text": "#include <stdio.h>\n#define ROW 3\n#define COL 3\n/* Function declarations */\nvoid matrixInput(int mat[][COL]);\nvoid matrixPrint(int mat[][COL]);\nvoid matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);\nint main() {\n int mat1[ROW][COL];\n int mat2[ROW][COL];\n int product[ROW][COL];\n printf(\"Enter elements in first matrix of size %dx%d\\n\", ROW, COL);\n matrixInput(mat1);\n printf(\"Enter elements in second matrix of size %dx%d\\n\", ROW, COL);\n matrixInput(mat2);\n matrixMultiply(mat1, mat2, product);\n printf(\"Product of both matrices is : \\n\");\n matrixPrint(product);\n return 0;\n}\nvoid matrixInput(int mat[][COL]) {\n int row, col;\n for (row = 0; row < ROW; row++) {\n for (col = 0; col < COL; col++) {\n scanf(\"%d\", (*(mat + row) + col));\n }\n }\n}\nvoid matrixPrint(int mat[][COL]) {\n int row, col;\n for (row = 0; row < ROW; row++) {\n for (col = 0; col < COL; col++) {\n printf(\"%d \", *(*(mat + row) + col));\n }\n printf(\"\\n\");\n }\n}\nvoid matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]) {\n int row, col, i;\n int sum;\n for (row = 0; row < ROW; row++) {\n for (col = 0; col < COL; col++) {\n sum = 0;\n for (i = 0; i < COL; i++) {\n sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));\n }\n *(*(res + row) + col) = sum;\n }\n }\n}"
},
{
"code": null,
"e": 3440,
"s": 3369,
"text": "When the above program is executed, it produces the following output −"
},
{
"code": null,
"e": 3620,
"s": 3440,
"text": "Enter elements in first matrix of size 3x3\n2 3 1\n2 5 6\n2 6 8\nEnter elements in second matrix of size 3x3\n1 2 1\n2 3 4\n5 6 7\nProduct of both matrices is :\n13 19 21\n42 55 64\n54 70 82"
}
]
|
How to Visualize Data on top of a Map in Python using the Geoviews library | by Christos Zeglis | Towards Data Science | So let’s start with the problem we are about to tackle. Say you have some data that represent a specific figure (e.g. population) which differs from place to place (e.g. different cities) and you want to make a plot to visualize that data. How do you proceed with that?
One way to do that (and the most common one) is to create a bar plot. The y-axis represents the figure(e.g. population) and the x-axis represents the place (e.g. cities). I bet the vast majority of plots on that kind of data is of that type. As a result, there is a countless number of such examples on the web and therefore there is no need for me to add another one on the stack.
Fortunately, there is a better way to visualize that kind of data. Remember, plots have to be intuitive for the viewers to get a better grasp of what’s in front of them. So, in this case, a more intuitive way to visualize that data would be to plot them on a map. What’s more intuitive than an interactive map where you can zoom in, out, and over the place or figure you look for?
For the purposes of this tutorial, we are going to make a plot to visualize the passengers volume for the busiest airports in my country, Greece, and the neighbor country, Turkey, for comparison reasons.
First, we need to import the libraries and the methods we are about to use.
import pandas as pdimport numpy as npimport geoviews as gvimport geoviews.tile_sources as gvtsfrom geoviews import dim, optsgv.extension('bokeh')
Our two dataframes, greek_aiports and turkish_airports, consist of the top 10 greek airports and the top 5 turkish airports in passengers volume respectively.
To these dataframes we will add an extra column country .
greek_airports['country']= 'GR'turkish_airports['country']= 'TR'
We will also add the column color . You will see later on why we did that.
greek_airports['color']= '#30a2da'turkish_airports['color']= '#fc4f30'
Now if we merge these two dataframes into airports
airports = pd.merge(greek_airports, turkish_airports, how='outer')
The airports dataframe will look like this.
I don’t need the citizens(k) column for that example so I will drop it.
airports.drop('citizens(k)', axis=1, inplace=True)
So the final airports dataframe will look like this.
(For those who want to follow along in their notebook the airports dataframe can be found here)
Now let’s start using the geoviews module. In specific, let’s use the geoviews.Points function to create a plot with our points.
airports_gv_points = gv.Points(airports, ['longitude', 'latitude'], ['IATA', 'city', 'passengers', 'country', 'color'])
In order to plot these points on a map we need a... map. The geoviews module offers a lot of tilemaps we can use. We can see what’s available if we type in
gvts.tile_sources
For that example let’s use the CartoLight tilemap. Let’s see what we get for
gvts.CartoLight
Now, we can plot the points on top of CartoLight with
gvts.CartoLight * airports_gv_points
There are a few issues here:
The plot dimensions are really small.
I don’t like axis labels for latitude and longitude.
I don’t like grids on maps.
I can fix these by adding a few options on the gvts.CartoLight like
gvts.CartoLight.options(width=1300, height=800, xaxis=None, yaxis=None, show_grid=False) * airports_gv_points
Now, because the points are still just dots, and therefore they cannot illustrate the volume of passengers, I will use the opts method we imported before. The parameter we need is size . Moreover, in order to get the numbers somewhat closer, I will use the np.sqrt function to get their square roots.
airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, xaxis=None, yaxis=None, size=np.sqrt(dim('passengers'))*10))
As you can see, we now have our interactive map that illustrates how busy the airports in Greece and in Turkey are. Obviously, Athens has the busiest airport in Greece whereas the busiest airport in Turkey is located in Istanbul.
To make the plot better, we can use different colors for each country while we can also add a hover tool to get some information about the airports once we move the cursor above them. To add color we add the parameter color=dim('color') which uses the color we specified on the color column, and for the hover tool we add the parameter tools=['hover'] .
airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=['hover'],size=np.sqrt(dim('passengers'))*10))
We can even create our own hover tool to get 100% control of what the hover tool shows. For example, I don’t want it to show the color code used for each country. Lastly, I want the color of each point to darken a little bit when I pass the cursor over them so I add the parameter hover_fill_alpha=0.5 .
from bokeh.models import HoverTooltooltips = [('IATA', '@IATA'), ('Passengers', '@passengers{0.00 a}m'), ('City', '@city'), ('Country', '@country'), ('Longitude', '$x'), ('Latitude', '$y'), ]hover = HoverTool(tooltips=tooltips)airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=[hover],size=np.sqrt(dim('passengers'))*10, hover_fill_color=None, hover_fill_alpha=0.5))
If you are a fan of dark color themes, as I am, you can always use the gvts.CartoDark tilemap.
airports_plot = (gvts.CartoDark.options(alpha=0.8) * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=[hover],size=np.sqrt(dim('passengers'))*10, hover_fill_color=None, hover_fill_alpha=0.5))
That’s it for today. Hope you found it useful. Till next time!
You can always find me on LinkedIn by clicking here. | [
{
"code": null,
"e": 441,
"s": 171,
"text": "So let’s start with the problem we are about to tackle. Say you have some data that represent a specific figure (e.g. population) which differs from place to place (e.g. different cities) and you want to make a plot to visualize that data. How do you proceed with that?"
},
{
"code": null,
"e": 823,
"s": 441,
"text": "One way to do that (and the most common one) is to create a bar plot. The y-axis represents the figure(e.g. population) and the x-axis represents the place (e.g. cities). I bet the vast majority of plots on that kind of data is of that type. As a result, there is a countless number of such examples on the web and therefore there is no need for me to add another one on the stack."
},
{
"code": null,
"e": 1204,
"s": 823,
"text": "Fortunately, there is a better way to visualize that kind of data. Remember, plots have to be intuitive for the viewers to get a better grasp of what’s in front of them. So, in this case, a more intuitive way to visualize that data would be to plot them on a map. What’s more intuitive than an interactive map where you can zoom in, out, and over the place or figure you look for?"
},
{
"code": null,
"e": 1408,
"s": 1204,
"text": "For the purposes of this tutorial, we are going to make a plot to visualize the passengers volume for the busiest airports in my country, Greece, and the neighbor country, Turkey, for comparison reasons."
},
{
"code": null,
"e": 1484,
"s": 1408,
"text": "First, we need to import the libraries and the methods we are about to use."
},
{
"code": null,
"e": 1630,
"s": 1484,
"text": "import pandas as pdimport numpy as npimport geoviews as gvimport geoviews.tile_sources as gvtsfrom geoviews import dim, optsgv.extension('bokeh')"
},
{
"code": null,
"e": 1789,
"s": 1630,
"text": "Our two dataframes, greek_aiports and turkish_airports, consist of the top 10 greek airports and the top 5 turkish airports in passengers volume respectively."
},
{
"code": null,
"e": 1847,
"s": 1789,
"text": "To these dataframes we will add an extra column country ."
},
{
"code": null,
"e": 1912,
"s": 1847,
"text": "greek_airports['country']= 'GR'turkish_airports['country']= 'TR'"
},
{
"code": null,
"e": 1987,
"s": 1912,
"text": "We will also add the column color . You will see later on why we did that."
},
{
"code": null,
"e": 2058,
"s": 1987,
"text": "greek_airports['color']= '#30a2da'turkish_airports['color']= '#fc4f30'"
},
{
"code": null,
"e": 2109,
"s": 2058,
"text": "Now if we merge these two dataframes into airports"
},
{
"code": null,
"e": 2176,
"s": 2109,
"text": "airports = pd.merge(greek_airports, turkish_airports, how='outer')"
},
{
"code": null,
"e": 2220,
"s": 2176,
"text": "The airports dataframe will look like this."
},
{
"code": null,
"e": 2292,
"s": 2220,
"text": "I don’t need the citizens(k) column for that example so I will drop it."
},
{
"code": null,
"e": 2343,
"s": 2292,
"text": "airports.drop('citizens(k)', axis=1, inplace=True)"
},
{
"code": null,
"e": 2396,
"s": 2343,
"text": "So the final airports dataframe will look like this."
},
{
"code": null,
"e": 2492,
"s": 2396,
"text": "(For those who want to follow along in their notebook the airports dataframe can be found here)"
},
{
"code": null,
"e": 2621,
"s": 2492,
"text": "Now let’s start using the geoviews module. In specific, let’s use the geoviews.Points function to create a plot with our points."
},
{
"code": null,
"e": 2801,
"s": 2621,
"text": "airports_gv_points = gv.Points(airports, ['longitude', 'latitude'], ['IATA', 'city', 'passengers', 'country', 'color'])"
},
{
"code": null,
"e": 2957,
"s": 2801,
"text": "In order to plot these points on a map we need a... map. The geoviews module offers a lot of tilemaps we can use. We can see what’s available if we type in"
},
{
"code": null,
"e": 2975,
"s": 2957,
"text": "gvts.tile_sources"
},
{
"code": null,
"e": 3052,
"s": 2975,
"text": "For that example let’s use the CartoLight tilemap. Let’s see what we get for"
},
{
"code": null,
"e": 3068,
"s": 3052,
"text": "gvts.CartoLight"
},
{
"code": null,
"e": 3122,
"s": 3068,
"text": "Now, we can plot the points on top of CartoLight with"
},
{
"code": null,
"e": 3159,
"s": 3122,
"text": "gvts.CartoLight * airports_gv_points"
},
{
"code": null,
"e": 3188,
"s": 3159,
"text": "There are a few issues here:"
},
{
"code": null,
"e": 3226,
"s": 3188,
"text": "The plot dimensions are really small."
},
{
"code": null,
"e": 3279,
"s": 3226,
"text": "I don’t like axis labels for latitude and longitude."
},
{
"code": null,
"e": 3307,
"s": 3279,
"text": "I don’t like grids on maps."
},
{
"code": null,
"e": 3375,
"s": 3307,
"text": "I can fix these by adding a few options on the gvts.CartoLight like"
},
{
"code": null,
"e": 3486,
"s": 3375,
"text": "gvts.CartoLight.options(width=1300, height=800, xaxis=None, yaxis=None, show_grid=False) * airports_gv_points"
},
{
"code": null,
"e": 3787,
"s": 3486,
"text": "Now, because the points are still just dots, and therefore they cannot illustrate the volume of passengers, I will use the opts method we imported before. The parameter we need is size . Moreover, in order to get the numbers somewhat closer, I will use the np.sqrt function to get their square roots."
},
{
"code": null,
"e": 3989,
"s": 3787,
"text": "airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, xaxis=None, yaxis=None, size=np.sqrt(dim('passengers'))*10))"
},
{
"code": null,
"e": 4219,
"s": 3989,
"text": "As you can see, we now have our interactive map that illustrates how busy the airports in Greece and in Turkey are. Obviously, Athens has the busiest airport in Greece whereas the busiest airport in Turkey is located in Istanbul."
},
{
"code": null,
"e": 4573,
"s": 4219,
"text": "To make the plot better, we can use different colors for each country while we can also add a hover tool to get some information about the airports once we move the cursor above them. To add color we add the parameter color=dim('color') which uses the color we specified on the color column, and for the hover tool we add the parameter tools=['hover'] ."
},
{
"code": null,
"e": 4874,
"s": 4573,
"text": "airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=['hover'],size=np.sqrt(dim('passengers'))*10))"
},
{
"code": null,
"e": 5178,
"s": 4874,
"text": "We can even create our own hover tool to get 100% control of what the hover tool shows. For example, I don’t want it to show the color code used for each country. Lastly, I want the color of each point to darken a little bit when I pass the cursor over them so I add the parameter hover_fill_alpha=0.5 ."
},
{
"code": null,
"e": 5830,
"s": 5178,
"text": "from bokeh.models import HoverTooltooltips = [('IATA', '@IATA'), ('Passengers', '@passengers{0.00 a}m'), ('City', '@city'), ('Country', '@country'), ('Longitude', '$x'), ('Latitude', '$y'), ]hover = HoverTool(tooltips=tooltips)airports_plot = (gvts.CartoLight * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=[hover],size=np.sqrt(dim('passengers'))*10, hover_fill_color=None, hover_fill_alpha=0.5))"
},
{
"code": null,
"e": 5925,
"s": 5830,
"text": "If you are a fan of dark color themes, as I am, you can always use the gvts.CartoDark tilemap."
},
{
"code": null,
"e": 6302,
"s": 5925,
"text": "airports_plot = (gvts.CartoDark.options(alpha=0.8) * airports_gv_points).opts( opts.Points(width=1200, height=700, alpha=0.3, color=dim('color'), hover_line_color='black', line_color='black', xaxis=None, yaxis=None, tools=[hover],size=np.sqrt(dim('passengers'))*10, hover_fill_color=None, hover_fill_alpha=0.5))"
},
{
"code": null,
"e": 6365,
"s": 6302,
"text": "That’s it for today. Hope you found it useful. Till next time!"
}
]
|
Tkinter Application to Switch Between Different Page Frames | 15 Feb, 2021
Prerequisites: Python GUI – tkinter
Sometimes it happens that we need to create an application with several pops up dialog boxes, i.e Page Frames. Here is a step by step process to create multiple Tkinter Page Frames and link them! This can be used as a boilerplate for more complex python GUI applications like creating interfaces for Virtual Laboratories for experiments, classrooms, etc.
Here are the steps:
Create three different pages. Here we have three different pages, The start page as the home page, page one, and page two.
Create a container for each page frame.
We have four classes. First is the tkinterApp class, where we have initialized the three frames and defined a function show_frame which is called every time the user clicks on a button.
The StartPage is simple with two buttons to go to Page 1 and Page 2.
Page 1 has two buttons, One for Page 2 and another to return to Start Page.
Page 2 also has two buttons, one for Page 1 and others to return to StartPage.
This is a simplistic application of navigating between Tkinter frames.
This can be used as a boilerplate for more complex applications and several features can be added.
The App starts with the StartPage as the first page, as shown in class tkinterApp. Here in StartApp, there are two buttons. Clicking on a button takes you to the respective Page. You can add images and graphs to these pages and add complex functionality. The pages have two buttons as well. Every time a button is pressed show_frame is called, which displays the respective Page.Below is the implementation.
Python3
import tkinter as tkfrom tkinter import ttk LARGEFONT =("Verdana", 35) class tkinterApp(tk.Tk): # __init__ function for class tkinterApp def __init__(self, *args, **kwargs): # __init__ function for class Tk tk.Tk.__init__(self, *args, **kwargs) # creating a container container = tk.Frame(self) container.pack(side = "top", fill = "both", expand = True) container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) # initializing frames to an empty array self.frames = {} # iterating through a tuple consisting # of the different page layouts for F in (StartPage, Page1, Page2): frame = F(container, self) # initializing frame of that object from # startpage, page1, page2 respectively with # for loop self.frames[F] = frame frame.grid(row = 0, column = 0, sticky ="nsew") self.show_frame(StartPage) # to display the current frame passed as # parameter def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() # first window frame startpage class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # label of frame Layout 2 label = ttk.Label(self, text ="Startpage", font = LARGEFONT) # putting the grid in its place by using # grid label.grid(row = 0, column = 4, padx = 10, pady = 10) button1 = ttk.Button(self, text ="Page 1", command = lambda : controller.show_frame(Page1)) # putting the button in its place by # using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) ## button to show frame 2 with text layout2 button2 = ttk.Button(self, text ="Page 2", command = lambda : controller.show_frame(Page2)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # second window frame page1class Page1(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text ="Page 1", font = LARGEFONT) label.grid(row = 0, column = 4, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button1 = ttk.Button(self, text ="StartPage", command = lambda : controller.show_frame(StartPage)) # putting the button in its place # by using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button2 = ttk.Button(self, text ="Page 2", command = lambda : controller.show_frame(Page2)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # third window frame page2class Page2(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text ="Page 2", font = LARGEFONT) label.grid(row = 0, column = 4, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button1 = ttk.Button(self, text ="Page 1", command = lambda : controller.show_frame(Page1)) # putting the button in its place by # using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) # button to show frame 3 with text # layout3 button2 = ttk.Button(self, text ="Startpage", command = lambda : controller.show_frame(StartPage)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # Driver Codeapp = tkinterApp()app.mainloop()
Output:
abhigoya
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Read a file line by line in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Feb, 2021"
},
{
"code": null,
"e": 91,
"s": 54,
"text": "Prerequisites: Python GUI – tkinter "
},
{
"code": null,
"e": 447,
"s": 91,
"text": "Sometimes it happens that we need to create an application with several pops up dialog boxes, i.e Page Frames. Here is a step by step process to create multiple Tkinter Page Frames and link them! This can be used as a boilerplate for more complex python GUI applications like creating interfaces for Virtual Laboratories for experiments, classrooms, etc. "
},
{
"code": null,
"e": 468,
"s": 447,
"text": "Here are the steps: "
},
{
"code": null,
"e": 592,
"s": 468,
"text": "Create three different pages. Here we have three different pages, The start page as the home page, page one, and page two. "
},
{
"code": null,
"e": 633,
"s": 592,
"text": "Create a container for each page frame. "
},
{
"code": null,
"e": 820,
"s": 633,
"text": "We have four classes. First is the tkinterApp class, where we have initialized the three frames and defined a function show_frame which is called every time the user clicks on a button. "
},
{
"code": null,
"e": 890,
"s": 820,
"text": "The StartPage is simple with two buttons to go to Page 1 and Page 2. "
},
{
"code": null,
"e": 967,
"s": 890,
"text": "Page 1 has two buttons, One for Page 2 and another to return to Start Page. "
},
{
"code": null,
"e": 1047,
"s": 967,
"text": "Page 2 also has two buttons, one for Page 1 and others to return to StartPage. "
},
{
"code": null,
"e": 1119,
"s": 1047,
"text": "This is a simplistic application of navigating between Tkinter frames. "
},
{
"code": null,
"e": 1220,
"s": 1119,
"text": "This can be used as a boilerplate for more complex applications and several features can be added. "
},
{
"code": null,
"e": 1629,
"s": 1220,
"text": "The App starts with the StartPage as the first page, as shown in class tkinterApp. Here in StartApp, there are two buttons. Clicking on a button takes you to the respective Page. You can add images and graphs to these pages and add complex functionality. The pages have two buttons as well. Every time a button is pressed show_frame is called, which displays the respective Page.Below is the implementation. "
},
{
"code": null,
"e": 1637,
"s": 1629,
"text": "Python3"
},
{
"code": "import tkinter as tkfrom tkinter import ttk LARGEFONT =(\"Verdana\", 35) class tkinterApp(tk.Tk): # __init__ function for class tkinterApp def __init__(self, *args, **kwargs): # __init__ function for class Tk tk.Tk.__init__(self, *args, **kwargs) # creating a container container = tk.Frame(self) container.pack(side = \"top\", fill = \"both\", expand = True) container.grid_rowconfigure(0, weight = 1) container.grid_columnconfigure(0, weight = 1) # initializing frames to an empty array self.frames = {} # iterating through a tuple consisting # of the different page layouts for F in (StartPage, Page1, Page2): frame = F(container, self) # initializing frame of that object from # startpage, page1, page2 respectively with # for loop self.frames[F] = frame frame.grid(row = 0, column = 0, sticky =\"nsew\") self.show_frame(StartPage) # to display the current frame passed as # parameter def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() # first window frame startpage class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # label of frame Layout 2 label = ttk.Label(self, text =\"Startpage\", font = LARGEFONT) # putting the grid in its place by using # grid label.grid(row = 0, column = 4, padx = 10, pady = 10) button1 = ttk.Button(self, text =\"Page 1\", command = lambda : controller.show_frame(Page1)) # putting the button in its place by # using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) ## button to show frame 2 with text layout2 button2 = ttk.Button(self, text =\"Page 2\", command = lambda : controller.show_frame(Page2)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # second window frame page1class Page1(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text =\"Page 1\", font = LARGEFONT) label.grid(row = 0, column = 4, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button1 = ttk.Button(self, text =\"StartPage\", command = lambda : controller.show_frame(StartPage)) # putting the button in its place # by using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button2 = ttk.Button(self, text =\"Page 2\", command = lambda : controller.show_frame(Page2)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # third window frame page2class Page2(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text =\"Page 2\", font = LARGEFONT) label.grid(row = 0, column = 4, padx = 10, pady = 10) # button to show frame 2 with text # layout2 button1 = ttk.Button(self, text =\"Page 1\", command = lambda : controller.show_frame(Page1)) # putting the button in its place by # using grid button1.grid(row = 1, column = 1, padx = 10, pady = 10) # button to show frame 3 with text # layout3 button2 = ttk.Button(self, text =\"Startpage\", command = lambda : controller.show_frame(StartPage)) # putting the button in its place by # using grid button2.grid(row = 2, column = 1, padx = 10, pady = 10) # Driver Codeapp = tkinterApp()app.mainloop()",
"e": 5623,
"s": 1637,
"text": null
},
{
"code": null,
"e": 5631,
"s": 5623,
"text": "Output:"
},
{
"code": null,
"e": 5646,
"s": 5637,
"text": "abhigoya"
},
{
"code": null,
"e": 5671,
"s": 5646,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 5686,
"s": 5671,
"text": "Python-tkinter"
},
{
"code": null,
"e": 5693,
"s": 5686,
"text": "Python"
},
{
"code": null,
"e": 5791,
"s": 5693,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5821,
"s": 5791,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5871,
"s": 5821,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 5887,
"s": 5871,
"text": "Deque in Python"
},
{
"code": null,
"e": 5903,
"s": 5887,
"text": "Stack in Python"
},
{
"code": null,
"e": 5921,
"s": 5903,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5946,
"s": 5921,
"text": "sum() function in Python"
},
{
"code": null,
"e": 5987,
"s": 5946,
"text": "Print lists in Python (5 Different Ways)"
},
{
"code": null,
"e": 6029,
"s": 5987,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6045,
"s": 6029,
"text": "Queue in Python"
}
]
|
Java Program to Print Reverse Pyramid Star Pattern | 17 Mar, 2021
Approach:
1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object.
2. Now run two loops
Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,Run an inner loop from 1 to ‘i-1’Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)
Run an inner loop from 1 to ‘i-1’
Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)
Illustration:
Input: number = 7
Output:
*************
***********
*********
*******
*****
***
*
Methods: We can print a reverse pyramid star pattern using the following methods:
Using while loopUsing for loopUsing do-while loop
Using while loop
Using for loop
Using do-while loop
Example 1: Using While Loop
Java
// Java program to Print Reverse Pyramid Star Pattern// Using While loop // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variable to // Size of the pyramid int number = 7; int i = number, j; // Nested while loops // Outer loop // Till condition holds true while (i > 0) { j = 0; // Inner loop // Condition check while (j++ < number - i) { // Print whitespaces System.out.print(" "); } j = 0; // Inner loop // Condition check while (j++ < (i * 2) - 1) { // Print star System.out.print("*"); } // By now, we reach end of execution for one row // so next line System.out.println(); // Decrementing counter because we want to print // reverse of pyramid i--; } }}
*************
***********
*********
*******
*****
***
*
Example 2: Using for Loop
Java
// Java program to print reverse pyramid star pattern// Using for loopimport java.io.*; class GFG{ public static void main (String[] args) { // Size of the pyramid int number = 7; int i, j; // Outer loop handle the number of rows for(i = number; i >= 1; i--) { // Inner loop print space for(j = i; j < number; j++) { System.out.print(" "); } // Inner loop print star for(j = 1; j <= (2 * i - 1); j++) { System.out.print("*"); } // Ending line after each row System.out.println(""); } }}
*************
***********
*********
*******
*****
***
*
Example 3: Using do-while Loop
Java
// Java program to Print Reverse Pyramid Star Pattern// Using do-while loop // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Declare and initialize variable to // Size of the pyramid int number = 7; int i = number, j; // Outer loop iterate until i > 0 is false do { j = 0; // First inner do-while loop do { // Prints space until j++ < number - i is // false System.out.print(" "); } while (j++ < number - i); j = 0; // Second inner do-while loop // Inner loop prints star // until j++ < i * 2 - 2 is false do { // print star System.out.print("*"); } while (j++ < i * 2 - 2); // Print whitespace System.out.println(""); } // while of outer 'do-while' loop while (--i > 0); }}
*************
***********
*********
*******
*****
***
*
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 63,
"s": 53,
"text": "Approach:"
},
{
"code": null,
"e": 161,
"s": 63,
"text": "1. Get the number of input rows from the user using Scanner Class or BufferedReader Class object."
},
{
"code": null,
"e": 182,
"s": 161,
"text": "2. Now run two loops"
},
{
"code": null,
"e": 388,
"s": 182,
"text": "Outer loop to iterate through a number of rows as initialized or input is taken from reader class object in java. Now,Run an inner loop from 1 to ‘i-1’Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)"
},
{
"code": null,
"e": 422,
"s": 388,
"text": "Run an inner loop from 1 to ‘i-1’"
},
{
"code": null,
"e": 477,
"s": 422,
"text": "Ru another inner loop from 1 to rows * 2 – (i × 2 – 1)"
},
{
"code": null,
"e": 491,
"s": 477,
"text": "Illustration:"
},
{
"code": null,
"e": 597,
"s": 491,
"text": "Input: number = 7\n \nOutput:\n\n*************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 679,
"s": 597,
"text": "Methods: We can print a reverse pyramid star pattern using the following methods:"
},
{
"code": null,
"e": 729,
"s": 679,
"text": "Using while loopUsing for loopUsing do-while loop"
},
{
"code": null,
"e": 746,
"s": 729,
"text": "Using while loop"
},
{
"code": null,
"e": 761,
"s": 746,
"text": "Using for loop"
},
{
"code": null,
"e": 781,
"s": 761,
"text": "Using do-while loop"
},
{
"code": null,
"e": 809,
"s": 781,
"text": "Example 1: Using While Loop"
},
{
"code": null,
"e": 814,
"s": 809,
"text": "Java"
},
{
"code": "// Java program to Print Reverse Pyramid Star Pattern// Using While loop // Importing input output classesimport java.io.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing variable to // Size of the pyramid int number = 7; int i = number, j; // Nested while loops // Outer loop // Till condition holds true while (i > 0) { j = 0; // Inner loop // Condition check while (j++ < number - i) { // Print whitespaces System.out.print(\" \"); } j = 0; // Inner loop // Condition check while (j++ < (i * 2) - 1) { // Print star System.out.print(\"*\"); } // By now, we reach end of execution for one row // so next line System.out.println(); // Decrementing counter because we want to print // reverse of pyramid i--; } }}",
"e": 1926,
"s": 814,
"text": null
},
{
"code": null,
"e": 2003,
"s": 1926,
"text": "*************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 2029,
"s": 2003,
"text": "Example 2: Using for Loop"
},
{
"code": null,
"e": 2034,
"s": 2029,
"text": "Java"
},
{
"code": "// Java program to print reverse pyramid star pattern// Using for loopimport java.io.*; class GFG{ public static void main (String[] args) { // Size of the pyramid int number = 7; int i, j; // Outer loop handle the number of rows for(i = number; i >= 1; i--) { // Inner loop print space for(j = i; j < number; j++) { System.out.print(\" \"); } // Inner loop print star for(j = 1; j <= (2 * i - 1); j++) { System.out.print(\"*\"); } // Ending line after each row System.out.println(\"\"); } }}",
"e": 2682,
"s": 2034,
"text": null
},
{
"code": null,
"e": 2759,
"s": 2682,
"text": "*************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 2790,
"s": 2759,
"text": "Example 3: Using do-while Loop"
},
{
"code": null,
"e": 2795,
"s": 2790,
"text": "Java"
},
{
"code": "// Java program to Print Reverse Pyramid Star Pattern// Using do-while loop // Importing input output classesimport java.io.*; // Main Classpublic class GFG { // Main driver method public static void main(String[] args) { // Declare and initialize variable to // Size of the pyramid int number = 7; int i = number, j; // Outer loop iterate until i > 0 is false do { j = 0; // First inner do-while loop do { // Prints space until j++ < number - i is // false System.out.print(\" \"); } while (j++ < number - i); j = 0; // Second inner do-while loop // Inner loop prints star // until j++ < i * 2 - 2 is false do { // print star System.out.print(\"*\"); } while (j++ < i * 2 - 2); // Print whitespace System.out.println(\"\"); } // while of outer 'do-while' loop while (--i > 0); }}",
"e": 3887,
"s": 2795,
"text": null
},
{
"code": null,
"e": 3971,
"s": 3887,
"text": " *************\n ***********\n *********\n *******\n *****\n ***\n *"
},
{
"code": null,
"e": 3978,
"s": 3971,
"text": "Picked"
},
{
"code": null,
"e": 3983,
"s": 3978,
"text": "Java"
},
{
"code": null,
"e": 3997,
"s": 3983,
"text": "Java Programs"
},
{
"code": null,
"e": 4002,
"s": 3997,
"text": "Java"
}
]
|
Huffman Encoding | Practice | GeeksforGeeks | Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.
Note: While merging if two nodes have the same value, then the node which occurs at first will be taken on the left of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the subtree and other one to the right.
Example 1:
S = "abcdef"
f[] = {5, 9, 12, 13, 16, 45}
Output:
0 100 101 1100 1101 111
Explanation:
HuffmanCodes will be:
f : 0
c : 100
d : 101
a : 1100
b : 1101
e : 111
Hence printing them in the PreOrder of Binary
Tree.
Your Task:
You don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree.
Expected Time complexity: O(N * LogN)
Expected Space complexity: O(N)
Constraints:
1 ≤ N ≤ 26
0
msandhiya82483 days ago
C++ CLEAN SOLUTION:
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
struct Node{
char dat;
int freq;
Node *left,*right;
};
Node * newNode(char j,int f){
Node *n=new Node();
n->dat=j;
n->freq=f;
n->left=NULL;
n->right=NULL;
}
struct cmpare{
bool operator()(Node *l,Node *r){
return l->freq>r->freq;
}
};
void preorder(Node *r,string t,vector<string>&a ){
if(r->left==NULL and r->right==NULL)
{
a.push_back(t);
return;
}
preorder(r->left,t+'0',a);
preorder(r->right,t+'1',a);
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
Node *root=NULL;
priority_queue<Node *,vector<Node *>,cmpare>p;
for(int i=0;i<N;i++){
Node *t=newNode(S[i],f[i]);
p.push(t);
}
vector<string>v;
while(p.size()>1){
Node *n;
Node *l=p.top();
p.pop();
Node *r=p.top();
p.pop();
// cout<<l->freq<<" "<<r->freq<<endl;
n=newNode('*',l->freq+r->freq);
if(l->freq<=r->freq){
n->left=l;
n->right=r;
}
else{
n->left=r;
n->right=l;
}
//cout<<n->freq<<" ";
p.push(n);
}
root=p.top();
// cout<<root->freq;
string s;
preorder(root,s,v);
return v;
}
};
// { Driver Code Starts.
int main(){
int T;
cin >> T;
while(T--)
{
string S;
cin >> S;
int N = S.length();
vector<int> f(N);
for(int i=0;i<N;i++){
cin>>f[i];
}
Solution ob;
vector<string> ans = ob.huffmanCodes(S,f,N);
for(auto i: ans)
cout << i << " ";
cout << "\n";
}
return 0;
} // } Driver Code Ends
+1
arkoghoshdastidar3920005 days ago
C++ solution:
Time Complexity : O(nlogn)
Space Complexity : O(n)
Concepts used : Tree traversal & min_priority_queue.
Solution :
class Node{
public:
char data;
int frequency;
Node* left;
Node* right;
Node(){
this->left = NULL;
this->right = NULL;
this->data = '*';
}
Node(int frequency){
this->frequency = frequency;
this->data = '*';
this->left = NULL;
this->right = NULL;
}
Node(char data, int frequency){
this->data = data;
this->frequency = frequency;
this->left = NULL;
this->right = NULL;
}
};
class cmp{
public:
bool operator()(Node* n1, Node* n2){
return n1->frequency > n2->frequency;
}
};
vector<Node*> pairCharWithFrequency(string S, vector<int> f, int N){
vector<Node*> characterAndFrequencyPair;
for(int i=0; i<N; i++){
Node* currentNode = new Node(S[i], f[i]);
characterAndFrequencyPair.push_back(currentNode);
}
return characterAndFrequencyPair;
}
void insertNodesInPQ(vector<Node*> characterAndFrequencyPair, priority_queue<Node*, vector<Node*>, cmp> &pq, int N){
for(int i=0; i<N; i++){
pq.push(characterAndFrequencyPair[i]);
}
}
Node* setHuffmanTree(priority_queue<Node*, vector<Node*>, cmp> &pq){
Node* rootNode = NULL;
while(pq.size() > 1){
Node* n1 = pq.top();
pq.pop();
Node* n2 = pq.top();
pq.pop();
Node* newNode = new Node(n1->frequency+n2->frequency);
if(n1->frequency <= n2->frequency){
newNode->left = n1;
newNode->right = n2;
}else{
newNode->right = n1;
newNode->left = n2;
}
pq.push(newNode);
}
rootNode = pq.top();
return rootNode;
}
void getCodes(Node* node, string code, vector<string> &codes){
if(!node->left && !node->right){
codes.push_back(code);
return;
}
getCodes(node->left, code+'0', codes);
getCodes(node->right, code+'1', codes);
}
class Solution{
public:
vector<string> huffmanCodes(string S,vector<int> f,int N){
vector<string> codes;
string s;
if(N == 1){
//Only one character present in the string S.
return codes;
}
vector<Node*> characterAndFrequencyPair = pairCharWithFrequency(S, f, N); //O(n)
priority_queue<Node*, vector<Node*>, cmp> pq;
insertNodesInPQ(characterAndFrequencyPair, pq, N); //O(nlogn)
Node* rootNode = setHuffmanTree(pq); //O(nlogn)
getCodes(rootNode, s, codes); //O(n)
return codes;
}
};
0
avinashdhn19042 weeks ago
// C++ code using priority_queue
class Node{
public:
int data;
Node *left,*right;
Node(int x){
this->data=x;
this->left=NULL;
this->right=NULL;
}
};
struct cmp{
bool operator()(Node *l,Node *r){
return (l->data>r->data);
}
};
class Solution
{
public:
void preorder(Node *root,string s,vector<string>&ans){
if(root==NULL)return;
if(root->left==NULL&&root->right==NULL){
ans.push_back(s);
}
preorder(root->left,s+'0',ans);
preorder(root->right,s+'1',ans);
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
vector<string>ans;
priority_queue<Node*,vector<Node*>,cmp>mh;
for(int i=0;i<N;i++){
Node *root=new Node(f[i]);
mh.push(root);
}
while(mh.size()!=1){
Node *left=mh.top();
mh.pop();
Node *right=mh.top();
mh.pop();
Node *parent= new Node(left->data+right->data);
parent->left=left;
parent->right=right;
mh.push(parent);
}
Node *root=mh.top();
mh.pop();
preorder(root,"",ans);
return ans;
}
};
0
dheerukd20022 weeks ago
class Node{
public:
char data;
int val;
Node* left;
Node* right;
Node(int i,char c='#'){
val=i;
data=c;
left=NULL;
right=NULL;
}
};
void decodeHuff(Node* root,string s,vector<string> &v){
if(!root)return;
if(root->left==NULL&&root->right==NULL){
v.push_back(s);
return ;
}
decodeHuff(root->left,s+"0",v);
decodeHuff(root->right,s+"1",v);
}
bool comp(Node*n1,Node*n2){
return n1->val>n2->val;
}
class Solution
{
public:
vector<string> huffmanCodes(string S,vector<int> f,int N){
if(N==1)return {0};
priority_queue<Node*,vector<Node*>,function<bool(Node*,Node*)>>pq(comp);
for(int i=0;i<N;i++){
Node* n=new Node(f[i],S[i]);
pq.push(n);
}
while(pq.size()!=1){
Node* t1=pq.top();
pq.pop();
Node* t2=pq.top();
pq.pop();
Node* n=new Node(t1->val+t2->val);
n->left=(t1->val<=t2->val)?t1:t2;
n->right=(t1->val<=t2->val)?t2:t1;
pq.push(n);
}
vector<string> ans;
decodeHuff(pq.top(),"",ans);
return ans;
}
};
+2
billagreeshman3 weeks ago
struct data{
int val;
vector<string> s;
};
class cmp
{
public:
int operator()(const data a,const data b){
return a.val>b.val;
}
};
class Solution
{
public:
vector<string> huffmanCodes(string s,vector<int> f,int n)
{
// Code here
priority_queue<data,vector<data>,cmp> heap;
for(int i=0;i<n;i++){
data temp;
temp.val=f[i];
temp.s=vector<string>(1,"");
heap.push(temp);
}
while(heap.size()>1){
int f1=heap.top().val;
vector<string> f2=heap.top().s;
heap.pop();
int s1=heap.top().val;
vector<string> s2=heap.top().s;
heap.pop();
for(int i=0;i<f2.size();i++){
f2[i]="0"+f2[i];
}
for(int i=0;i<s2.size();i++){
s2[i]="1"+s2[i];
}
f1+=s1;
data temp;
temp.val=f1;
temp.s=f2;
temp.s.insert(temp.s.end(),s2.begin(),s2.end());
heap.push(temp);
}
vector<string> ans=heap.top().s;
return heap.top().s;
}
};
0
xxxcoder_fnc4 weeks ago
please anybody check why it's not working
class Node{ public: char data; int freq; Node* left; Node*right; Node(char data,int freq){ this->data=data; this->freq=freq; left=right=NULL; }};
//for priority queue
class compare{ bool operator()(Node*a,Node*b){ return (a->freq > b->freq); } };
void print_code(Node *root,string a,vector<string>&ans){ if(root==NULL){return;} //we have already initiallize the sum data with '&' //now any node we encounter having '&' we do'nt accept //node not containing '&' will be our input node only if(root->data!='&'){ ans.push_back(a); } print_code(root->left,a+"0",ans);//go left add 0 print_code(root->right,a+"1",ans);//go right add 1 } vector<string> huffmanCodes(string S,vector<int> f,int N) { // Node *l,*r,*top; //we are creating a min heap //so that only top minimum two will be always get added priority_queue<Node*,vector<Node*>,compare>pq; for(int i=0;i<f.size();i++){ pq.push(new Node(S[i],f[i])); } //now we have to compute sum till we get last node while(pq.size()!=1){ //extract the two minimum and add it and make three internal nodes Node *left=pq.top(); pq.pop(); Node *right=pq.top(); pq.pop(); //create new internal node Node* top=new Node('&',left->data+right->data); top->left=left; top->right=right; //now insert the top in the queue pq.push(top); } //now we have to print/insert the hoffman code //in the vector vector<string>ans; print_code(pq.top(),"",ans); return ans; }
+4
roboto7o32oo31 month ago
Clean C++ Solution✨✨
class Solution
{
public:
struct Node{
string symbol;
int frequency;
Node* left;
Node* right;
bool isLeaf;
Node(string symbol, int frequency){
this->symbol = symbol;
this->frequency = frequency;
this->left = NULL;
this->right = NULL;
this->isLeaf = false;
}
};
struct CompareNode{
bool operator()(Node* a, Node* b){
return a->frequency > b->frequency;
}
};
void preOrder(Node* node, string path, vector<string>&result){
if(node == NULL){
return;
}
if(node->isLeaf){
result.push_back(path);
}
preOrder(node->left, path+"0", result);
preOrder(node->right, path+"1", result);
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
priority_queue<Node*, vector<Node*>, CompareNode> pq;
Node *node,*node1,*node2,*newNode,*root;
vector<string> result;
for(int i=0; i<N; i++){
node = new Node(string(1,S[i]),f[i]);
node->isLeaf = true;
pq.push(node);
}
while(pq.size() != 1){
node1 = pq.top();
pq.pop();
node2 = pq.top();
pq.pop();
newNode = new Node((node1->symbol+node2->symbol), (node1->frequency+node2->frequency));
newNode->left = node1;
newNode->right = node2;
pq.push(newNode);
}
root = pq.top();
preOrder(root, "", result);
return result;
}
};
0
putyavka2 months ago
struct Node {
int f, i;
Node *l, *r;
Node(int f, char i=-1, Node*l=NULL, Node*r=NULL)
: f(f), i(i), l(l), r(r) {
}
};
struct NodeCmp {
bool operator()(const Node* a, const Node* b) {
return a->f > b->f;
}
};
void deleteNodeR(Node* node) {
if (!node) return;
deleteNodeR(node->l);
deleteNodeR(node->r);
delete node;
}
void printR(Node* n, string& s, vector<string>& R) {
if (n->i > -1) R.push_back(s);
else {
s.push_back('0');
printR(n->l, s, R);
s.pop_back();
s.push_back('1');
printR(n->r, s, R);
s.pop_back();
}
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
priority_queue<Node*, vector<Node*>, NodeCmp> Q;
for (int i = 0; i < N; i++)
Q.push(new Node(f[i], i));
while (Q.size() > 1) {
auto l = Q.top(); Q.pop();
auto r = Q.top(); Q.pop();
Q.push(new Node(l->f + r->f, -1, l, r));
}
vector<string> R;
string s;
printR(Q.top(), s, R);
deleteNodeR(Q.top());
return R;
}
0
utsavj5023 months ago
#User function Template for python3
from heapq import heapify, heappush, heappop
class Node :
def __init__(self,freq,symbol,left=None,right=None) :
self.freq=freq
self.symbol=symbol
self.left=left
self.right=right
def __lt__(self, other):
return self.freq < other.freq
class Solution:
def traverse(self,root,ans,curr) :
if(root==None) : return;
if(root.symbol!="$" and root.left==None and root.right==None) :
ans.append(curr)
return;
self.traverse(root.left,ans,curr+'0')
self.traverse(root.right,ans,curr+'1')
def huffmanCodes(self,S,f,N):
heap=[]
heapify(heap)
for i in range(N) :
heappush(heap,Node(f[i],S[i]))
while len(heap)>1 :
left=heappop(heap)
right=heappop(heap)
node=Node(left.freq+right.freq,"$",left,right)
heappush(heap,node)
ans=[]
self.traverse(heappop(heap),ans,"")
return ans
# Code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t=int(input())
for i in range(t):
S= input()
N= len(S);
f= [int(x) for x in input().split()]
ob = Solution()
ans = ob.huffmanCodes(S,f,N)
for i in ans:
print(i, end = " ")
print()
# } Driver Code Ends
+1
revolverocelot3 months ago
For C++. Athough using greater<int> gurantees the constraint mentioned in the ‘note’ of this question. However after running a test case I saw it actually violates it, which results in the testcase getting failed.
So instead of greater<>, while intialising prioirty_queue, define your own comparator block as under
struct comp { bool operator()( yourDataType a, yourDataType b) { return a→data > b→data; } };
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 731,
"s": 238,
"text": "Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.\nNote: While merging if two nodes have the same value, then the node which occurs at first will be taken on the left of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the subtree and other one to the right."
},
{
"code": null,
"e": 742,
"s": 731,
"text": "Example 1:"
},
{
"code": null,
"e": 954,
"s": 742,
"text": "S = \"abcdef\"\nf[] = {5, 9, 12, 13, 16, 45}\nOutput: \n0 100 101 1100 1101 111\nExplanation:\n\nHuffmanCodes will be:\nf : 0\nc : 100\nd : 101\na : 1100\nb : 1101\ne : 111\nHence printing them in the PreOrder of Binary \nTree."
},
{
"code": null,
"e": 1265,
"s": 954,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree."
},
{
"code": null,
"e": 1337,
"s": 1265,
"text": "Expected Time complexity: O(N * LogN) \nExpected Space complexity: O(N) "
},
{
"code": null,
"e": 1361,
"s": 1337,
"text": "Constraints:\n1 ≤ N ≤ 26"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "0"
},
{
"code": null,
"e": 1387,
"s": 1363,
"text": "msandhiya82483 days ago"
},
{
"code": null,
"e": 1407,
"s": 1387,
"text": "C++ CLEAN SOLUTION:"
},
{
"code": null,
"e": 3422,
"s": 1407,
"text": "// { Driver Code Starts\n#include<bits/stdc++.h>\nusing namespace std;\n\n // } Driver Code Ends\nclass Solution\n{\n public:\n\t\n\t struct Node{\n\t char dat;\n\t int freq;\n\t \n\t Node *left,*right;\n\t };\n\t Node * newNode(char j,int f){\n\t Node *n=new Node();\n\t n->dat=j;\n\t n->freq=f;\n\t n->left=NULL;\n\t n->right=NULL;\n\t }\n\t struct cmpare{\n\t bool operator()(Node *l,Node *r){\n\t return l->freq>r->freq;\n\t } \n\t };\n\t \n\t void preorder(Node *r,string t,vector<string>&a ){\n\t if(r->left==NULL and r->right==NULL)\n\t {\n\t a.push_back(t);\n\t return;\n\t }\n\t preorder(r->left,t+'0',a);\n\t preorder(r->right,t+'1',a);\n\t \n\t }\n\t \n\t \n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N)\n\t\t{\n\t\t Node *root=NULL;\n\t\t priority_queue<Node *,vector<Node *>,cmpare>p;\n\t\t for(int i=0;i<N;i++){\n\t\t Node *t=newNode(S[i],f[i]);\n\t\t p.push(t);\n\t\t }\n\t\t vector<string>v;\n\t\t while(p.size()>1){\n\t\t Node *n;\n\t\t Node *l=p.top();\n\t\t p.pop();\n\t\t Node *r=p.top();\n\t\t p.pop();\n\t\t \n\t\t // cout<<l->freq<<\" \"<<r->freq<<endl;\n\t\t n=newNode('*',l->freq+r->freq);\n\t\t if(l->freq<=r->freq){\n\t\t n->left=l;\n\t\t n->right=r;\n\t\t }\n\t\t else{\n\t\t n->left=r;\n\t\t n->right=l;\n\t\t }\n\t\t //cout<<n->freq<<\" \";\n\t\t p.push(n);\n\t\t \n\t\t \n\t\t }\n\t\t root=p.top();\n\t\t // cout<<root->freq;\n\t\t string s;\n\t\t preorder(root,s,v);\n\t\t \n\t\t return v;\n\t\t \n\t\t}\n};\n\n// { Driver Code Starts.\nint main(){\n int T;\n cin >> T;\n while(T--)\n {\n\t string S;\n\t cin >> S;\n\t int N = S.length();\n\t vector<int> f(N);\n\t for(int i=0;i<N;i++){\n\t cin>>f[i];\n\t }\n\t Solution ob;\n\t vector<string> ans = ob.huffmanCodes(S,f,N);\n\t for(auto i: ans)\n\t \tcout << i << \" \";\n\t cout << \"\\n\";\n }\n\treturn 0;\n} // } Driver Code Ends"
},
{
"code": null,
"e": 3425,
"s": 3422,
"text": "+1"
},
{
"code": null,
"e": 3459,
"s": 3425,
"text": "arkoghoshdastidar3920005 days ago"
},
{
"code": null,
"e": 3473,
"s": 3459,
"text": "C++ solution:"
},
{
"code": null,
"e": 3500,
"s": 3473,
"text": "Time Complexity : O(nlogn)"
},
{
"code": null,
"e": 3524,
"s": 3500,
"text": "Space Complexity : O(n)"
},
{
"code": null,
"e": 3580,
"s": 3526,
"text": "Concepts used : Tree traversal & min_priority_queue."
},
{
"code": null,
"e": 3594,
"s": 3582,
"text": "Solution : "
},
{
"code": null,
"e": 6063,
"s": 3594,
"text": "class Node{\n public:\n char data;\n int frequency;\n Node* left;\n Node* right;\n Node(){\n this->left = NULL;\n this->right = NULL;\n this->data = '*';\n }\n Node(int frequency){\n this->frequency = frequency;\n this->data = '*';\n this->left = NULL;\n this->right = NULL;\n }\n Node(char data, int frequency){\n this->data = data;\n this->frequency = frequency;\n this->left = NULL;\n this->right = NULL;\n }\n};\n\nclass cmp{\n public:\n bool operator()(Node* n1, Node* n2){\n return n1->frequency > n2->frequency;\n } \n};\n\nvector<Node*> pairCharWithFrequency(string S, vector<int> f, int N){\n vector<Node*> characterAndFrequencyPair;\n for(int i=0; i<N; i++){\n Node* currentNode = new Node(S[i], f[i]);\n characterAndFrequencyPair.push_back(currentNode);\n }\n return characterAndFrequencyPair;\n}\n\nvoid insertNodesInPQ(vector<Node*> characterAndFrequencyPair, priority_queue<Node*, vector<Node*>, cmp> &pq, int N){\n for(int i=0; i<N; i++){\n pq.push(characterAndFrequencyPair[i]);\n }\n}\n\nNode* setHuffmanTree(priority_queue<Node*, vector<Node*>, cmp> &pq){\n Node* rootNode = NULL;\n while(pq.size() > 1){\n Node* n1 = pq.top();\n pq.pop();\n Node* n2 = pq.top();\n pq.pop();\n Node* newNode = new Node(n1->frequency+n2->frequency);\n if(n1->frequency <= n2->frequency){\n newNode->left = n1;\n newNode->right = n2;\n }else{\n newNode->right = n1;\n newNode->left = n2;\n }\n pq.push(newNode);\n }\n rootNode = pq.top();\n return rootNode;\n}\n\nvoid getCodes(Node* node, string code, vector<string> &codes){\n if(!node->left && !node->right){\n codes.push_back(code);\n return;\n }\n getCodes(node->left, code+'0', codes);\n getCodes(node->right, code+'1', codes);\n}\n\nclass Solution{\n public:\n\tvector<string> huffmanCodes(string S,vector<int> f,int N){\n\t vector<string> codes;\n\t string s;\n\t if(N == 1){\n\t //Only one character present in the string S.\n\t return codes;\n\t }\n\t vector<Node*> characterAndFrequencyPair = pairCharWithFrequency(S, f, N); //O(n)\n\t priority_queue<Node*, vector<Node*>, cmp> pq; \n\t insertNodesInPQ(characterAndFrequencyPair, pq, N); //O(nlogn)\n\t Node* rootNode = setHuffmanTree(pq); //O(nlogn)\n\t getCodes(rootNode, s, codes); //O(n)\n\t return codes;\n\t}\n};"
},
{
"code": null,
"e": 6065,
"s": 6063,
"text": "0"
},
{
"code": null,
"e": 6091,
"s": 6065,
"text": "avinashdhn19042 weeks ago"
},
{
"code": null,
"e": 7219,
"s": 6091,
"text": "// C++ code using priority_queue\n\nclass Node{\n public:\n int data;\n Node *left,*right;\n Node(int x){\n this->data=x;\n this->left=NULL;\n this->right=NULL;\n }\n};\nstruct cmp{\n bool operator()(Node *l,Node *r){\n return (l->data>r->data);\n }\n};\nclass Solution\n{\n\tpublic:\n\nvoid preorder(Node *root,string s,vector<string>&ans){\n if(root==NULL)return;\n if(root->left==NULL&&root->right==NULL){\n ans.push_back(s);\n }\n preorder(root->left,s+'0',ans);\n preorder(root->right,s+'1',ans);\n}\n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N)\n\t\t{\n\t\t vector<string>ans;\n\t\t priority_queue<Node*,vector<Node*>,cmp>mh;\n\t\t for(int i=0;i<N;i++){\n\t\t Node *root=new Node(f[i]);\n\t\t mh.push(root);\n\t\t }\n\t\t while(mh.size()!=1){\n\t\t Node *left=mh.top();\n\t\t mh.pop();\n\t\t Node *right=mh.top();\n\t\t mh.pop();\n\t\t Node *parent= new Node(left->data+right->data);\n\t\t parent->left=left;\n\t\t parent->right=right;\n\t\t mh.push(parent);\n\t\t }\n\t\t Node *root=mh.top();\n\t\t mh.pop();\n\t\t preorder(root,\"\",ans);\n\t\t return ans;\n\t\t}\n};\n"
},
{
"code": null,
"e": 7221,
"s": 7219,
"text": "0"
},
{
"code": null,
"e": 7245,
"s": 7221,
"text": "dheerukd20022 weeks ago"
},
{
"code": null,
"e": 8509,
"s": 7245,
"text": "class Node{\n public:\n char data;\n int val;\n Node* left;\n Node* right;\n \n Node(int i,char c='#'){\n val=i;\n data=c;\n left=NULL;\n right=NULL;\n }\n};\n\nvoid decodeHuff(Node* root,string s,vector<string> &v){\n if(!root)return;\n \n if(root->left==NULL&&root->right==NULL){\n v.push_back(s);\n return ;\n }\n \n decodeHuff(root->left,s+\"0\",v);\n decodeHuff(root->right,s+\"1\",v);\n \n}\n\nbool comp(Node*n1,Node*n2){\n return n1->val>n2->val;\n}\n\nclass Solution\n{\n\tpublic:\n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N){\n\t\t \n\t\t if(N==1)return {0};\n\t\t \n\t\t priority_queue<Node*,vector<Node*>,function<bool(Node*,Node*)>>pq(comp);\n\t\t \n\t\t for(int i=0;i<N;i++){\n\t\t Node* n=new Node(f[i],S[i]);\n\t\t pq.push(n);\n\t\t }\n\t\t \n\t\t while(pq.size()!=1){\n\t\t Node* t1=pq.top();\n\t\t pq.pop();\n\t\t Node* t2=pq.top();\n\t\t pq.pop();\n\t\t \n\t\t Node* n=new Node(t1->val+t2->val);\n\t\t \n\t\t n->left=(t1->val<=t2->val)?t1:t2;\n\t\t n->right=(t1->val<=t2->val)?t2:t1;\n\t\t \n\t\t pq.push(n);\n\t\t }\n\t\t \n\t\t vector<string> ans;\n\t\t \n\t\t decodeHuff(pq.top(),\"\",ans);\n\n\t\t return ans;\n\t\t \n\t\t}\n};"
},
{
"code": null,
"e": 8512,
"s": 8509,
"text": "+2"
},
{
"code": null,
"e": 8538,
"s": 8512,
"text": "billagreeshman3 weeks ago"
},
{
"code": null,
"e": 9736,
"s": 8540,
"text": "struct data{\n int val;\n vector<string> s;\n };\n\n\nclass cmp\n{\n public:\n int operator()(const data a,const data b){\n return a.val>b.val;\n }\n};\nclass Solution\n{\n\n \n\tpublic:\n\t\tvector<string> huffmanCodes(string s,vector<int> f,int n)\n\t\t{\n\t\t // Code here\n\t\t priority_queue<data,vector<data>,cmp> heap;\n\t\t \n\t\t for(int i=0;i<n;i++){\n\t\t \n\t\t data temp;\n\t\t temp.val=f[i];\n\t\t temp.s=vector<string>(1,\"\");\n\t\t \n\t\t heap.push(temp);\n\t\t }\n\t\t \n\t\t while(heap.size()>1){\n\t\t int f1=heap.top().val;\n\t\t vector<string> f2=heap.top().s;\n\t\t heap.pop();\n\t\t \n\t\t int s1=heap.top().val;\n\t\t vector<string> s2=heap.top().s;\n\t\t heap.pop();\n\t\t \n\t\t for(int i=0;i<f2.size();i++){\n\t\t f2[i]=\"0\"+f2[i];\n\t\t }\n\t\t for(int i=0;i<s2.size();i++){\n\t\t s2[i]=\"1\"+s2[i];\n\t\t }\n\t\t f1+=s1;\n\t\t data temp;\n\t\t temp.val=f1;\n\t\t temp.s=f2;\n\t\t temp.s.insert(temp.s.end(),s2.begin(),s2.end());\n\t\t heap.push(temp);\n\t\t }\n\t\t vector<string> ans=heap.top().s;\n\t\t \n\t\t \n\t\t return heap.top().s;\n\t\t}\n};"
},
{
"code": null,
"e": 9738,
"s": 9736,
"text": "0"
},
{
"code": null,
"e": 9762,
"s": 9738,
"text": "xxxcoder_fnc4 weeks ago"
},
{
"code": null,
"e": 9804,
"s": 9762,
"text": "please anybody check why it's not working"
},
{
"code": null,
"e": 9978,
"s": 9808,
"text": "class Node{ public: char data; int freq; Node* left; Node*right; Node(char data,int freq){ this->data=data; this->freq=freq; left=right=NULL; }};"
},
{
"code": null,
"e": 9999,
"s": 9978,
"text": "//for priority queue"
},
{
"code": null,
"e": 10091,
"s": 9999,
"text": "class compare{ bool operator()(Node*a,Node*b){ return (a->freq > b->freq); } };"
},
{
"code": null,
"e": 11387,
"s": 10091,
"text": "void print_code(Node *root,string a,vector<string>&ans){ if(root==NULL){return;} //we have already initiallize the sum data with '&' //now any node we encounter having '&' we do'nt accept //node not containing '&' will be our input node only if(root->data!='&'){ ans.push_back(a); } print_code(root->left,a+\"0\",ans);//go left add 0 print_code(root->right,a+\"1\",ans);//go right add 1 } vector<string> huffmanCodes(string S,vector<int> f,int N) { // Node *l,*r,*top; //we are creating a min heap //so that only top minimum two will be always get added priority_queue<Node*,vector<Node*>,compare>pq; for(int i=0;i<f.size();i++){ pq.push(new Node(S[i],f[i])); } //now we have to compute sum till we get last node while(pq.size()!=1){ //extract the two minimum and add it and make three internal nodes Node *left=pq.top(); pq.pop(); Node *right=pq.top(); pq.pop(); //create new internal node Node* top=new Node('&',left->data+right->data); top->left=left; top->right=right; //now insert the top in the queue pq.push(top); } //now we have to print/insert the hoffman code //in the vector vector<string>ans; print_code(pq.top(),\"\",ans); return ans; }"
},
{
"code": null,
"e": 11392,
"s": 11389,
"text": "+4"
},
{
"code": null,
"e": 11417,
"s": 11392,
"text": "roboto7o32oo31 month ago"
},
{
"code": null,
"e": 11438,
"s": 11417,
"text": "Clean C++ Solution✨✨"
},
{
"code": null,
"e": 13140,
"s": 11440,
"text": "class Solution\n{\n\tpublic:\n\t\n\t struct Node{\n\t string symbol;\n\t int frequency;\n\t Node* left;\n\t Node* right;\n\t bool isLeaf;\n\t \n\t Node(string symbol, int frequency){\n\t this->symbol = symbol;\n\t this->frequency = frequency;\n\t this->left = NULL;\n\t this->right = NULL;\n\t this->isLeaf = false;\n\t }\n\t };\n\t \n\t struct CompareNode{\n\t bool operator()(Node* a, Node* b){\n\t return a->frequency > b->frequency;\n\t }\n\t };\n\t \n\t void preOrder(Node* node, string path, vector<string>&result){\n\t if(node == NULL){\n\t return;\n\t }\n\t \n\t if(node->isLeaf){\n\t result.push_back(path);\n\t }\n\t \n\t preOrder(node->left, path+\"0\", result);\n\t preOrder(node->right, path+\"1\", result);\n\t }\n\t\n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N)\n\t\t{\n\t\t priority_queue<Node*, vector<Node*>, CompareNode> pq;\n\t\t Node *node,*node1,*node2,*newNode,*root;\n\t\t vector<string> result;\n\t\t \n\t\t for(int i=0; i<N; i++){\n\t\t node = new Node(string(1,S[i]),f[i]);\n\t\t node->isLeaf = true;\n\t\t pq.push(node);\n\t\t }\n\t\t \n\t\t while(pq.size() != 1){\n\t\t node1 = pq.top();\n\t\t pq.pop();\n\t\t \n\t\t node2 = pq.top();\n\t\t pq.pop();\n\t\t \n\t\t newNode = new Node((node1->symbol+node2->symbol), (node1->frequency+node2->frequency));\n\t\t newNode->left = node1;\n\t\t newNode->right = node2;\n\t\t pq.push(newNode);\n\t\t }\n\t\t \n\t\t root = pq.top();\n\t\t \n\t\t preOrder(root, \"\", result);\n\t\t \n\t\t return result;\n\t\t}\n};"
},
{
"code": null,
"e": 13142,
"s": 13140,
"text": "0"
},
{
"code": null,
"e": 13163,
"s": 13142,
"text": "putyavka2 months ago"
},
{
"code": null,
"e": 14232,
"s": 13163,
"text": "struct Node {\n int f, i;\n Node *l, *r;\n Node(int f, char i=-1, Node*l=NULL, Node*r=NULL)\n : f(f), i(i), l(l), r(r) {\n }\n};\nstruct NodeCmp {\n bool operator()(const Node* a, const Node* b) {\n return a->f > b->f;\n }\n};\nvoid deleteNodeR(Node* node) {\n if (!node) return;\n deleteNodeR(node->l);\n deleteNodeR(node->r);\n delete node;\n}\nvoid printR(Node* n, string& s, vector<string>& R) {\n if (n->i > -1) R.push_back(s);\n else {\n s.push_back('0');\n printR(n->l, s, R);\n s.pop_back();\n s.push_back('1');\n printR(n->r, s, R);\n s.pop_back();\n }\n}\nvector<string> huffmanCodes(string S,vector<int> f,int N)\n{\n priority_queue<Node*, vector<Node*>, NodeCmp> Q;\n for (int i = 0; i < N; i++)\n Q.push(new Node(f[i], i));\n while (Q.size() > 1) {\n auto l = Q.top(); Q.pop();\n auto r = Q.top(); Q.pop();\n Q.push(new Node(l->f + r->f, -1, l, r));\n }\n vector<string> R;\n string s;\n printR(Q.top(), s, R);\n deleteNodeR(Q.top());\n return R;\n}"
},
{
"code": null,
"e": 14234,
"s": 14232,
"text": "0"
},
{
"code": null,
"e": 14256,
"s": 14234,
"text": "utsavj5023 months ago"
},
{
"code": null,
"e": 15624,
"s": 14256,
"text": "#User function Template for python3\nfrom heapq import heapify, heappush, heappop\nclass Node : \n def __init__(self,freq,symbol,left=None,right=None) : \n self.freq=freq\n self.symbol=symbol\n self.left=left\n self.right=right\n def __lt__(self, other):\n return self.freq < other.freq\n\nclass Solution:\n def traverse(self,root,ans,curr) : \n if(root==None) : return;\n if(root.symbol!=\"$\" and root.left==None and root.right==None) : \n ans.append(curr)\n return;\n self.traverse(root.left,ans,curr+'0')\n self.traverse(root.right,ans,curr+'1')\n \n def huffmanCodes(self,S,f,N):\n heap=[]\n heapify(heap)\n for i in range(N) : \n heappush(heap,Node(f[i],S[i]))\n while len(heap)>1 : \n left=heappop(heap)\n right=heappop(heap)\n node=Node(left.freq+right.freq,\"$\",left,right)\n heappush(heap,node)\n ans=[]\n self.traverse(heappop(heap),ans,\"\")\n return ans\n # Code here\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\n\nif __name__ == '__main__':\n\tt=int(input())\n\tfor i in range(t):\n\t\tS= input()\n\t\tN= len(S);\n\t\tf= [int(x) for x in input().split()]\n\t\tob = Solution()\n\t\tans = ob.huffmanCodes(S,f,N)\n\t\tfor i in ans:\n\t\t print(i, end = \" \")\n\t\tprint()\n# } Driver Code Ends"
},
{
"code": null,
"e": 15627,
"s": 15624,
"text": "+1"
},
{
"code": null,
"e": 15654,
"s": 15627,
"text": "revolverocelot3 months ago"
},
{
"code": null,
"e": 15868,
"s": 15654,
"text": "For C++. Athough using greater<int> gurantees the constraint mentioned in the ‘note’ of this question. However after running a test case I saw it actually violates it, which results in the testcase getting failed."
},
{
"code": null,
"e": 15969,
"s": 15868,
"text": "So instead of greater<>, while intialising prioirty_queue, define your own comparator block as under"
},
{
"code": null,
"e": 16119,
"s": 15969,
"text": "struct comp { bool operator()( yourDataType a, yourDataType b) { return a→data > b→data; } };"
},
{
"code": null,
"e": 16265,
"s": 16119,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 16301,
"s": 16265,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 16311,
"s": 16301,
"text": "\nProblem\n"
},
{
"code": null,
"e": 16321,
"s": 16311,
"text": "\nContest\n"
},
{
"code": null,
"e": 16384,
"s": 16321,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 16569,
"s": 16384,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 16853,
"s": 16569,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 16999,
"s": 16853,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 17076,
"s": 16999,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 17117,
"s": 17076,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 17145,
"s": 17117,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 17216,
"s": 17145,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 17403,
"s": 17216,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
]
|
Program for Area And Perimeter Of Rectangle | 21 Jun, 2022
A rectangle is a flat figure in a plane. It has four sides and four equal angles of 90 degree each. In rectangle all four sides are not of equal length like square, sides opposite to each other have equal length. Both diagonals of the rectangle have equal length.
Examples:
Input : 4 5
Output : Area = 20
Perimeter = 18
Input : 2 3
Output : Area = 6
Perimeter = 10
Formulae :
Area of rectangle : a*b
Perimeter of rectangle: 2*(a + b)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find area// and perimeter of rectangle#include<bits/stdc++.h>using namespace std; // Utility functionint areaRectangle(int a, int b){ int area = a * b; return area;} int perimeterRectangle(int a, int b){ int perimeter = 2*(a + b); return perimeter;} // Driver programint main(){ int a = 5; int b = 6; cout << "Area = " << areaRectangle(a, b) << endl; cout << "Perimeter = " << perimeterRectangle(a, b); return 0;}
// Java program to find area// and perimeter of rectangleimport java.io.*; class Geometry { // Utility function static int areaRectangle(int a, int b) { int area = a * b; return area; } static int perimeterRectangle(int a, int b) { int perimeter = 2*(a + b); return perimeter; } // Driver Function public static void main (String[] args) { int a = 5; int b = 6; System.out.println("Area = "+ areaRectangle(a, b)); System.out.println("Perimeter = "+ perimeterRectangle(a, b)); }} // This code is contributed by Chinmoy Lenka
# Python3 code to find area# and perimeter of rectangle # Utility functiondef areaRectangle(a, b): return (a * b) def perimeterRectangle(a, b): return (2 * (a + b)) # Driver functiona = 5;b = 6;print ("Area = ", areaRectangle(a, b))print ("Perimeter = ", perimeterRectangle(a, b)) # This code is contributed by 'saloni1297'.
// C# program to find area// and perimeter of rectangleusing System; class GFG { // Utility function static int areaRectangle(int a, int b) { int area = a * b; return area; } static int perimeterRectangle(int a, int b) { int perimeter = 2 * (a + b); return perimeter; } // Driver Function public static void Main() { int a = 5; int b = 6; Console.WriteLine("Area = " + areaRectangle(a, b)); Console.WriteLine("Perimeter = " + perimeterRectangle(a, b)); }} // This code is contributed by vt_m.
<?php// PHP program to find area// and perimeter of rectangle // Utility functionfunction areaRectangle( $a, $b){ $area = $a * $b; return $area;} function perimeterRectangle( $a, $b){ $perimeter = 2 * ($a + $b); return $perimeter;} // Driver program$a = 5;$b = 6;echo("Area = " );echo(areaRectangle($a, $b));echo("\n");echo( "Perimeter = ");echo(perimeterRectangle($a, $b)); // This code is contributed by vt_m.?>
<script> // Javascript program to find area// and perimeter of rectangle // Utility functionfunction areaRectangle(a, b){ let area = a * b; return area;} function perimeterRectangle(a, b){ let perimeter = 2*(a + b); return perimeter;} // Driver program let a = 5;let b = 6;document.write("Area = " + areaRectangle(a, b) + "<br>");document.write("Perimeter = " + perimeterRectangle(a, b)); // This code is contributed by Manoj </script>
Output :
Area = 30
Perimeter = 22
Time complexity : O(1) Auxiliary Space : O(1)
This article is contributed by Saloni Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vt_m
mank1083
kk773572498
krishnav4
area-volume-programs
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 316,
"s": 52,
"text": "A rectangle is a flat figure in a plane. It has four sides and four equal angles of 90 degree each. In rectangle all four sides are not of equal length like square, sides opposite to each other have equal length. Both diagonals of the rectangle have equal length."
},
{
"code": null,
"e": 328,
"s": 316,
"text": "Examples: "
},
{
"code": null,
"e": 438,
"s": 328,
"text": "Input : 4 5\nOutput : Area = 20\n Perimeter = 18\n\nInput : 2 3\nOutput : Area = 6\n Perimeter = 10"
},
{
"code": null,
"e": 451,
"s": 438,
"text": "Formulae : "
},
{
"code": null,
"e": 511,
"s": 451,
"text": "Area of rectangle : a*b \nPerimeter of rectangle: 2*(a + b) "
},
{
"code": null,
"e": 515,
"s": 511,
"text": "C++"
},
{
"code": null,
"e": 520,
"s": 515,
"text": "Java"
},
{
"code": null,
"e": 528,
"s": 520,
"text": "Python3"
},
{
"code": null,
"e": 531,
"s": 528,
"text": "C#"
},
{
"code": null,
"e": 535,
"s": 531,
"text": "PHP"
},
{
"code": null,
"e": 546,
"s": 535,
"text": "Javascript"
},
{
"code": "// CPP program to find area// and perimeter of rectangle#include<bits/stdc++.h>using namespace std; // Utility functionint areaRectangle(int a, int b){ int area = a * b; return area;} int perimeterRectangle(int a, int b){ int perimeter = 2*(a + b); return perimeter;} // Driver programint main(){ int a = 5; int b = 6; cout << \"Area = \" << areaRectangle(a, b) << endl; cout << \"Perimeter = \" << perimeterRectangle(a, b); return 0;}",
"e": 991,
"s": 546,
"text": null
},
{
"code": "// Java program to find area// and perimeter of rectangleimport java.io.*; class Geometry { // Utility function static int areaRectangle(int a, int b) { int area = a * b; return area; } static int perimeterRectangle(int a, int b) { int perimeter = 2*(a + b); return perimeter; } // Driver Function public static void main (String[] args) { int a = 5; int b = 6; System.out.println(\"Area = \"+ areaRectangle(a, b)); System.out.println(\"Perimeter = \"+ perimeterRectangle(a, b)); }} // This code is contributed by Chinmoy Lenka",
"e": 1606,
"s": 991,
"text": null
},
{
"code": "# Python3 code to find area# and perimeter of rectangle # Utility functiondef areaRectangle(a, b): return (a * b) def perimeterRectangle(a, b): return (2 * (a + b)) # Driver functiona = 5;b = 6;print (\"Area = \", areaRectangle(a, b))print (\"Perimeter = \", perimeterRectangle(a, b)) # This code is contributed by 'saloni1297'.",
"e": 1937,
"s": 1606,
"text": null
},
{
"code": "// C# program to find area// and perimeter of rectangleusing System; class GFG { // Utility function static int areaRectangle(int a, int b) { int area = a * b; return area; } static int perimeterRectangle(int a, int b) { int perimeter = 2 * (a + b); return perimeter; } // Driver Function public static void Main() { int a = 5; int b = 6; Console.WriteLine(\"Area = \" + areaRectangle(a, b)); Console.WriteLine(\"Perimeter = \" + perimeterRectangle(a, b)); }} // This code is contributed by vt_m.",
"e": 2569,
"s": 1937,
"text": null
},
{
"code": "<?php// PHP program to find area// and perimeter of rectangle // Utility functionfunction areaRectangle( $a, $b){ $area = $a * $b; return $area;} function perimeterRectangle( $a, $b){ $perimeter = 2 * ($a + $b); return $perimeter;} // Driver program$a = 5;$b = 6;echo(\"Area = \" );echo(areaRectangle($a, $b));echo(\"\\n\");echo( \"Perimeter = \");echo(perimeterRectangle($a, $b)); // This code is contributed by vt_m.?>",
"e": 2995,
"s": 2569,
"text": null
},
{
"code": "<script> // Javascript program to find area// and perimeter of rectangle // Utility functionfunction areaRectangle(a, b){ let area = a * b; return area;} function perimeterRectangle(a, b){ let perimeter = 2*(a + b); return perimeter;} // Driver program let a = 5;let b = 6;document.write(\"Area = \" + areaRectangle(a, b) + \"<br>\");document.write(\"Perimeter = \" + perimeterRectangle(a, b)); // This code is contributed by Manoj </script>",
"e": 3445,
"s": 2995,
"text": null
},
{
"code": null,
"e": 3455,
"s": 3445,
"text": "Output : "
},
{
"code": null,
"e": 3480,
"s": 3455,
"text": "Area = 30\nPerimeter = 22"
},
{
"code": null,
"e": 3526,
"s": 3480,
"text": "Time complexity : O(1) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 3947,
"s": 3526,
"text": "This article is contributed by Saloni Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3952,
"s": 3947,
"text": "vt_m"
},
{
"code": null,
"e": 3961,
"s": 3952,
"text": "mank1083"
},
{
"code": null,
"e": 3973,
"s": 3961,
"text": "kk773572498"
},
{
"code": null,
"e": 3983,
"s": 3973,
"text": "krishnav4"
},
{
"code": null,
"e": 4004,
"s": 3983,
"text": "area-volume-programs"
},
{
"code": null,
"e": 4014,
"s": 4004,
"text": "Geometric"
},
{
"code": null,
"e": 4033,
"s": 4014,
"text": "School Programming"
},
{
"code": null,
"e": 4043,
"s": 4033,
"text": "Geometric"
}
]
|
GATE | GATE CS 1996 | Question 38 | 03 Jul, 2020
The average number of key comparisons done in a successful sequential search in a list of length it is(A) log n(B) (n-1)/2(C) n/2(D) (n+1)/2Answer: (D)Explanation: If element is at 1 position then it requires 1 comparison.If element is at 2 position then it requires 2 comparison.If element is at 3 position then it requires 3 comparison.Similarly , If element is at n position then it requires n comparison.
Total comparison
= n(n+1)/2
For average comparison
= (n(n+1)/2) / n
= (n+1)/2
Option (D) is correct.Quiz of this Question
vivekkumarmth0077
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 461,
"s": 52,
"text": "The average number of key comparisons done in a successful sequential search in a list of length it is(A) log n(B) (n-1)/2(C) n/2(D) (n+1)/2Answer: (D)Explanation: If element is at 1 position then it requires 1 comparison.If element is at 2 position then it requires 2 comparison.If element is at 3 position then it requires 3 comparison.Similarly , If element is at n position then it requires n comparison."
},
{
"code": null,
"e": 544,
"s": 461,
"text": "Total comparison \n= n(n+1)/2\n\nFor average comparison \n= (n(n+1)/2) / n \n= (n+1)/2 "
},
{
"code": null,
"e": 588,
"s": 544,
"text": "Option (D) is correct.Quiz of this Question"
},
{
"code": null,
"e": 606,
"s": 588,
"text": "vivekkumarmth0077"
},
{
"code": null,
"e": 619,
"s": 606,
"text": "GATE CS 1996"
},
{
"code": null,
"e": 637,
"s": 619,
"text": "GATE-GATE CS 1996"
},
{
"code": null,
"e": 642,
"s": 637,
"text": "GATE"
}
]
|
Platform Module in Python | 23 Jan, 2020
Python defines an in-built module platform that provides system information.
The Platform module is used to retrieve as much possible information about the platform on which the program is being currently executed. Now by platform info, it means information about the device, it’s OS, node, OS version, Python version, etc. This module plays a crucial role when you want to check whether your program is compatible with the python version installed on a particular system or whether the hardware specifications meet the requirements of your program.This module already exists in the python library and does not require any installation using pip.
It can be imported using the following syntax:
import platform
Example 1: Displaying the platform processor
# Python program to display platform processor # import moduleimport platform # displaying platform processorprint('Platform processor:', platform.processor())
Output:
This function returns a tuple that stores information about the bit architecture(number of bits in the platform processor) and linkage format( defines how names can or can not refer to the same entity throughout the whole program or one single translation unit).
Example 2: Displaying the platform architecture
# Python program to display platform architecture # import moduleimport platform # displaying platform architectureprint('Platform architecture:', platform.architecture())
Output:
This function returns a string that displays the machine type, by machine type here it means the information that tells the width or size of registers available in the core.
Example 3: Displaying the machine type
# Python program to display machine type # import moduleimport platform # displaying machine typeprint('Machine type:', platform.machine())
Output:
This function returns a string that displays the information about the node basically the system’s network name.
Example 4: Displaying the system’s network name
# Python program to display the # system's network name # import moduleimport platform # displaying system network nameprint('System's network name:', platform.node())
Output:
This function returns a single string containing as much useful information that is to retrievable about the system.The output may differ on different systems.
Example 5: Displaying the platform information
# Python program to display platform information # import moduleimport platform # displaying platform informationprint('Platform information:', platform.platform())
Output:
This function returns a string that displays the information about the platform processor basically the real name of the system’s processor
Note: Many platforms do not provide this information. eg-NetBSD
Example 6: Displaying the platform processor
# Python program to display platform # processor name # import moduleimport platform # displaying platform processor nameprint('Platform processor:', platform.platform())
Output:
This function returns a string that displays the name of the operation system on the current device being used to run the program.
Example 7: Displaying the OS name
# Python program to display OS name # import moduleimport platform # displaying OS nameprint('Operating system:', platform.system())
Output:
This function returns a tuple that stores information regarding the system. Basically this function can be used to replace the individual functions to retrieve information about the system, node, release, version, machine, version and processor. Thus, a single function serving many purposes.
Example 8: Displaying the System info
# Python program to display System info # import moduleimport platform # displaying system infoprint('System info:', platform.system())
Output:
Note: Platform module not only retrieves system information, but it can also be used to retrieve information about the Python software running on the system.
This function returns a tuple that stores information about the python build date and build no. This information is stored in the tuple as a string datatype.
Example 9: Displaying the python build date and no.
# Python program to display python# build date and no. # import moduleimport platform # displaying python build date and no.print('Python build no. and date:', platform.python_build())
Output:
This function returns a string that displays the compiler used for compiling the Python programs.
Example 10: Displaying the python compiler info
# Python program to display python compiler info # import moduleimport platform # displaying python compilerprint('Python compiler:', platform.python_compiler())
Output:
This function returns a string displaying information about the python SCM branch, SCM here stands for Source Code Manager , it is a tool used by programmers to manage source code. SCM is used to track revisions in software.
Example 11: Displaying the python SCM info
# Python program to display python SCM info # import moduleimport platform # displaying python SCM infoprint('Python SCM:', platform.python_compiler())
This function returns a string that displays information about the python implementation. The possible outputs of this function are CPython, JPython, PyPy, IronPython.
To know more about these implementations visit:Various Implementations of Python
Example 12: Displaying the python implementation
# Python program to display python implementation # import moduleimport platform # displaying python implementationprint('Python implementation:', platform.python_implementation())
Output:
This function returns a string that displays the version of Python running currently on the system. The python version is returned in the following manner:
'major.minor.patchlevel'
Example 13: Displaying the python version
# Python program to display python version # import moduleimport platform # displaying python versionprint('Python version:', platform.python_version())
Output:
Note: Since python is a platform-independent language, it’s modules also have functionalities that are specific to operating systems. Some of them from platform module are mentioned below:
This function returns a tuple containing information such as release, version, machine about the Mac OS. The output is in the following manner:
(release, versioninfo, machine)
In this versioninfo itself is a tuple storing information in the following manner:
(version, dev_stage, non_release_version)
This function returns a tuple storing information such as library and version of the Unix OS. The output is in the following manner:
(lib, version)
This function returns a tuple containing additional information about Windows OS such as OS release, version number, service pack, OS type(single/ multi processor). The output is in the following format:
(release, version, csd, ptype)
where csd is service pack and ptype is OS type.
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 130,
"s": 53,
"text": "Python defines an in-built module platform that provides system information."
},
{
"code": null,
"e": 700,
"s": 130,
"text": "The Platform module is used to retrieve as much possible information about the platform on which the program is being currently executed. Now by platform info, it means information about the device, it’s OS, node, OS version, Python version, etc. This module plays a crucial role when you want to check whether your program is compatible with the python version installed on a particular system or whether the hardware specifications meet the requirements of your program.This module already exists in the python library and does not require any installation using pip."
},
{
"code": null,
"e": 747,
"s": 700,
"text": "It can be imported using the following syntax:"
},
{
"code": null,
"e": 763,
"s": 747,
"text": "import platform"
},
{
"code": null,
"e": 808,
"s": 763,
"text": "Example 1: Displaying the platform processor"
},
{
"code": "# Python program to display platform processor # import moduleimport platform # displaying platform processorprint('Platform processor:', platform.processor())",
"e": 970,
"s": 808,
"text": null
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Output:"
},
{
"code": null,
"e": 1241,
"s": 978,
"text": "This function returns a tuple that stores information about the bit architecture(number of bits in the platform processor) and linkage format( defines how names can or can not refer to the same entity throughout the whole program or one single translation unit)."
},
{
"code": null,
"e": 1289,
"s": 1241,
"text": "Example 2: Displaying the platform architecture"
},
{
"code": "# Python program to display platform architecture # import moduleimport platform # displaying platform architectureprint('Platform architecture:', platform.architecture())",
"e": 1463,
"s": 1289,
"text": null
},
{
"code": null,
"e": 1471,
"s": 1463,
"text": "Output:"
},
{
"code": null,
"e": 1645,
"s": 1471,
"text": "This function returns a string that displays the machine type, by machine type here it means the information that tells the width or size of registers available in the core."
},
{
"code": null,
"e": 1684,
"s": 1645,
"text": "Example 3: Displaying the machine type"
},
{
"code": "# Python program to display machine type # import moduleimport platform # displaying machine typeprint('Machine type:', platform.machine())",
"e": 1826,
"s": 1684,
"text": null
},
{
"code": null,
"e": 1834,
"s": 1826,
"text": "Output:"
},
{
"code": null,
"e": 1947,
"s": 1834,
"text": "This function returns a string that displays the information about the node basically the system’s network name."
},
{
"code": null,
"e": 1995,
"s": 1947,
"text": "Example 4: Displaying the system’s network name"
},
{
"code": "# Python program to display the # system's network name # import moduleimport platform # displaying system network nameprint('System's network name:', platform.node())",
"e": 2165,
"s": 1995,
"text": null
},
{
"code": null,
"e": 2173,
"s": 2165,
"text": "Output:"
},
{
"code": null,
"e": 2333,
"s": 2173,
"text": "This function returns a single string containing as much useful information that is to retrievable about the system.The output may differ on different systems."
},
{
"code": null,
"e": 2380,
"s": 2333,
"text": "Example 5: Displaying the platform information"
},
{
"code": "# Python program to display platform information # import moduleimport platform # displaying platform informationprint('Platform information:', platform.platform())",
"e": 2547,
"s": 2380,
"text": null
},
{
"code": null,
"e": 2555,
"s": 2547,
"text": "Output:"
},
{
"code": null,
"e": 2695,
"s": 2555,
"text": "This function returns a string that displays the information about the platform processor basically the real name of the system’s processor"
},
{
"code": null,
"e": 2759,
"s": 2695,
"text": "Note: Many platforms do not provide this information. eg-NetBSD"
},
{
"code": null,
"e": 2804,
"s": 2759,
"text": "Example 6: Displaying the platform processor"
},
{
"code": "# Python program to display platform # processor name # import moduleimport platform # displaying platform processor nameprint('Platform processor:', platform.platform())",
"e": 2977,
"s": 2804,
"text": null
},
{
"code": null,
"e": 2985,
"s": 2977,
"text": "Output:"
},
{
"code": null,
"e": 3116,
"s": 2985,
"text": "This function returns a string that displays the name of the operation system on the current device being used to run the program."
},
{
"code": null,
"e": 3150,
"s": 3116,
"text": "Example 7: Displaying the OS name"
},
{
"code": "# Python program to display OS name # import moduleimport platform # displaying OS nameprint('Operating system:', platform.system())",
"e": 3285,
"s": 3150,
"text": null
},
{
"code": null,
"e": 3293,
"s": 3285,
"text": "Output:"
},
{
"code": null,
"e": 3586,
"s": 3293,
"text": "This function returns a tuple that stores information regarding the system. Basically this function can be used to replace the individual functions to retrieve information about the system, node, release, version, machine, version and processor. Thus, a single function serving many purposes."
},
{
"code": null,
"e": 3624,
"s": 3586,
"text": "Example 8: Displaying the System info"
},
{
"code": "# Python program to display System info # import moduleimport platform # displaying system infoprint('System info:', platform.system())",
"e": 3762,
"s": 3624,
"text": null
},
{
"code": null,
"e": 3770,
"s": 3762,
"text": "Output:"
},
{
"code": null,
"e": 3928,
"s": 3770,
"text": "Note: Platform module not only retrieves system information, but it can also be used to retrieve information about the Python software running on the system."
},
{
"code": null,
"e": 4086,
"s": 3928,
"text": "This function returns a tuple that stores information about the python build date and build no. This information is stored in the tuple as a string datatype."
},
{
"code": null,
"e": 4138,
"s": 4086,
"text": "Example 9: Displaying the python build date and no."
},
{
"code": "# Python program to display python# build date and no. # import moduleimport platform # displaying python build date and no.print('Python build no. and date:', platform.python_build())",
"e": 4325,
"s": 4138,
"text": null
},
{
"code": null,
"e": 4333,
"s": 4325,
"text": "Output:"
},
{
"code": null,
"e": 4431,
"s": 4333,
"text": "This function returns a string that displays the compiler used for compiling the Python programs."
},
{
"code": null,
"e": 4479,
"s": 4431,
"text": "Example 10: Displaying the python compiler info"
},
{
"code": "# Python program to display python compiler info # import moduleimport platform # displaying python compilerprint('Python compiler:', platform.python_compiler())",
"e": 4643,
"s": 4479,
"text": null
},
{
"code": null,
"e": 4651,
"s": 4643,
"text": "Output:"
},
{
"code": null,
"e": 4876,
"s": 4651,
"text": "This function returns a string displaying information about the python SCM branch, SCM here stands for Source Code Manager , it is a tool used by programmers to manage source code. SCM is used to track revisions in software."
},
{
"code": null,
"e": 4919,
"s": 4876,
"text": "Example 11: Displaying the python SCM info"
},
{
"code": "# Python program to display python SCM info # import moduleimport platform # displaying python SCM infoprint('Python SCM:', platform.python_compiler())",
"e": 5073,
"s": 4919,
"text": null
},
{
"code": null,
"e": 5241,
"s": 5073,
"text": "This function returns a string that displays information about the python implementation. The possible outputs of this function are CPython, JPython, PyPy, IronPython."
},
{
"code": null,
"e": 5322,
"s": 5241,
"text": "To know more about these implementations visit:Various Implementations of Python"
},
{
"code": null,
"e": 5371,
"s": 5322,
"text": "Example 12: Displaying the python implementation"
},
{
"code": "# Python program to display python implementation # import moduleimport platform # displaying python implementationprint('Python implementation:', platform.python_implementation())",
"e": 5554,
"s": 5371,
"text": null
},
{
"code": null,
"e": 5562,
"s": 5554,
"text": "Output:"
},
{
"code": null,
"e": 5718,
"s": 5562,
"text": "This function returns a string that displays the version of Python running currently on the system. The python version is returned in the following manner:"
},
{
"code": null,
"e": 5743,
"s": 5718,
"text": "'major.minor.patchlevel'"
},
{
"code": null,
"e": 5785,
"s": 5743,
"text": "Example 13: Displaying the python version"
},
{
"code": "# Python program to display python version # import moduleimport platform # displaying python versionprint('Python version:', platform.python_version())",
"e": 5940,
"s": 5785,
"text": null
},
{
"code": null,
"e": 5948,
"s": 5940,
"text": "Output:"
},
{
"code": null,
"e": 6137,
"s": 5948,
"text": "Note: Since python is a platform-independent language, it’s modules also have functionalities that are specific to operating systems. Some of them from platform module are mentioned below:"
},
{
"code": null,
"e": 6281,
"s": 6137,
"text": "This function returns a tuple containing information such as release, version, machine about the Mac OS. The output is in the following manner:"
},
{
"code": null,
"e": 6313,
"s": 6281,
"text": "(release, versioninfo, machine)"
},
{
"code": null,
"e": 6396,
"s": 6313,
"text": "In this versioninfo itself is a tuple storing information in the following manner:"
},
{
"code": null,
"e": 6438,
"s": 6396,
"text": "(version, dev_stage, non_release_version)"
},
{
"code": null,
"e": 6571,
"s": 6438,
"text": "This function returns a tuple storing information such as library and version of the Unix OS. The output is in the following manner:"
},
{
"code": null,
"e": 6586,
"s": 6571,
"text": "(lib, version)"
},
{
"code": null,
"e": 6790,
"s": 6586,
"text": "This function returns a tuple containing additional information about Windows OS such as OS release, version number, service pack, OS type(single/ multi processor). The output is in the following format:"
},
{
"code": null,
"e": 6821,
"s": 6790,
"text": "(release, version, csd, ptype)"
},
{
"code": null,
"e": 6869,
"s": 6821,
"text": "where csd is service pack and ptype is OS type."
},
{
"code": null,
"e": 6884,
"s": 6869,
"text": "python-modules"
},
{
"code": null,
"e": 6891,
"s": 6884,
"text": "Python"
}
]
|
Optional isPresent() method in Java with examples | 30 Jul, 2019
The isPresent() method of java.util.Optional class in Java is used to find out if there is a value present in this Optional instance. If there is no value present in this Optional instance, then this method returns false, else true.
Syntax:
public boolean isPresent()
Parameters: This method do not accept any parameter.
Return value: This method returns a boolean value stating whether if there is a value present in this Optional instance.
Below programs illustrate isPresent() method:Program 1:
// Java program to demonstrate// Optional.isPresent() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println("Optional: " + op); // check for the value System.out.println("Is any value present: " + op.isPresent()); }}
Optional: Optional[9455]
Is any value present: true
Program 2:
// Java program to demonstrate// Optional.isPresent() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // check for the value System.out.println("Is any value present: " + op.isPresent()); } catch (Exception e) { System.out.println(e); } }}
Optional: Optional.empty
Is any value present: false
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#isPresent–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jul, 2019"
},
{
"code": null,
"e": 261,
"s": 28,
"text": "The isPresent() method of java.util.Optional class in Java is used to find out if there is a value present in this Optional instance. If there is no value present in this Optional instance, then this method returns false, else true."
},
{
"code": null,
"e": 269,
"s": 261,
"text": "Syntax:"
},
{
"code": null,
"e": 297,
"s": 269,
"text": "public boolean isPresent()\n"
},
{
"code": null,
"e": 350,
"s": 297,
"text": "Parameters: This method do not accept any parameter."
},
{
"code": null,
"e": 471,
"s": 350,
"text": "Return value: This method returns a boolean value stating whether if there is a value present in this Optional instance."
},
{
"code": null,
"e": 527,
"s": 471,
"text": "Below programs illustrate isPresent() method:Program 1:"
},
{
"code": "// Java program to demonstrate// Optional.isPresent() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.of(9455); // print value System.out.println(\"Optional: \" + op); // check for the value System.out.println(\"Is any value present: \" + op.isPresent()); }}",
"e": 998,
"s": 527,
"text": null
},
{
"code": null,
"e": 1051,
"s": 998,
"text": "Optional: Optional[9455]\nIs any value present: true\n"
},
{
"code": null,
"e": 1062,
"s": 1051,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// Optional.isPresent() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println(\"Optional: \" + op); try { // check for the value System.out.println(\"Is any value present: \" + op.isPresent()); } catch (Exception e) { System.out.println(e); } }}",
"e": 1640,
"s": 1062,
"text": null
},
{
"code": null,
"e": 1694,
"s": 1640,
"text": "Optional: Optional.empty\nIs any value present: false\n"
},
{
"code": null,
"e": 1782,
"s": 1694,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#isPresent–"
},
{
"code": null,
"e": 1802,
"s": 1782,
"text": "Java - util package"
},
{
"code": null,
"e": 1817,
"s": 1802,
"text": "Java-Functions"
},
{
"code": null,
"e": 1831,
"s": 1817,
"text": "Java-Optional"
},
{
"code": null,
"e": 1836,
"s": 1831,
"text": "Java"
},
{
"code": null,
"e": 1841,
"s": 1836,
"text": "Java"
},
{
"code": null,
"e": 1939,
"s": 1841,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1990,
"s": 1939,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2021,
"s": 1990,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2040,
"s": 2021,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2070,
"s": 2040,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2088,
"s": 2070,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2108,
"s": 2088,
"text": "Collections in Java"
},
{
"code": null,
"e": 2132,
"s": 2108,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2164,
"s": 2132,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2176,
"s": 2164,
"text": "Set in Java"
}
]
|
How To Approach A Coding Problem ? | 08 Jul, 2022
Developers and students solve a lot of coding questions of data structures and algorithms but most of them don’t understand the importance of it. A lot of them also have this opinion that data structure and algorithms only help in interviews and after that, there is no use of all those complicated stuff in daily jobs.
You might be one of them who is happy with learning a new language or framework and building some applications with that but once you will enter the real world industry, you will realize that your job is not just writing the code and make things work. Your real job is to write the right amount of good code which means it should be efficient and robust and here comes the role of data structures and algorithms. Data Structures and Algorithms not only help in getting the logic for your program but also helps in writing the efficient code for your software. Whether we talk about the time complexity or memory management, code refactoring, or code reusability, you will understand its value in each part of your application.
In real-world projects, your brain should be able to write a quick efficient solution for complicated stuff and you can only do that when you practice a lot of coding questions. Understand that language and frameworks are just tools, they won’t teach you problem-solving skills. You develop problem-solving skills when you practice a lot of coding questions. Firstly understand the importance of DSA with these two articles...
Why Data Structures and Algorithms Are Important to Learn?
I Can’t Use Logic In Programming. What Should I Do?
Every developer has their own tricks and they follow their own pattern to solve coding problems but when it comes to new developers they are always uncertain about where to start. A lot of them understand the problems, the logic, and the basics of syntax, they also understand someone else codes and they can follow along with them but when it comes to solving the questions on their own, they get stuck. They don’t understand how to turn their thoughts into code even though they understand the syntax or logic. We are going to share some simple steps that will help you to approach a coding question.
It doesn’t matter if you have seen the question in the past or not, read the question several times and understand it completely. Now, think about the question and analyze it carefully. Sometimes we read a few lines and assume the rest of the things on our own but a slight change in your question can change a lot of things in your code so be careful about that. Now take a paper and write down everything. What is given (input) and what you need to find out (output)? While going through the problem you need to ask a few questions yourself...
Did you understand the problem fully?Would you be able to explain this question to someone else?What and how many inputs are required?What would be the output for those inputsDo you need to separate out some modules or parts from the problem?Do you have enough information to solve that question? If not then read the question again or clear it to the interviewer.
Did you understand the problem fully?
Would you be able to explain this question to someone else?
What and how many inputs are required?
What would be the output for those inputs
Do you need to separate out some modules or parts from the problem?
Do you have enough information to solve that question? If not then read the question again or clear it to the interviewer.
For Example: If you are given an array and you need to return the array that contains only even numbers then first of all analyze the problem carefully. While going through the problem a few questions you should ask yourself before jumping into the solution.
How to identify an even number? Divide that number by 2 and see if its remainder is 0.What should I pass into this function? An arrayWhat will that array contain? One or more numbersWhat are the data types of the elements in the array? NumbersWhat is the end goal? The goal is to return the array of even numbers. If there are no even numbers, return an empty array.
How to identify an even number? Divide that number by 2 and see if its remainder is 0.
What should I pass into this function? An array
What will that array contain? One or more numbers
What are the data types of the elements in the array? Numbers
What is the end goal? The goal is to return the array of even numbers. If there are no even numbers, return an empty array.
When you try to understand the problem take some sample inputs and try to analyze the output. Taking some sample inputs will help you to understand the problem in a better way. You will also get clarity that how many cases your code can handle and what all can be the possible output or output range. Read the points given below...
Consider some simple inputs or data and analyze the output.
Consider some complex and bigger input and identify what will be the output and how many cases you need to take for the problem.
Consider the edge cases as well. Analyze what would be the output if there is no input or if you give some invalid input.
For Example: If you need to return the array of even numbers from a given array then below are some variety of cases or sample inputs for which you can analyze the problem and its output.
[1]
[1, 2]
[1, 2, 3, 4, 5, 6]
[-300.35]
[-700.1, 1000, 5.1, -1000.25, 52, 900]
When you see a coding question that is complex or big, instead of being afraid and getting confused that how to solve that question, break down the problem into smaller chunks and then try to solve each part of the problem. Below are some steps you should follow in order to solve the complex coding questions...
Make a flow chart or a UML for the problem at hand.
Divide the problem into sub-problems or smaller chunks.
Solve the subproblems. Make independent functions for each subproblem.
Connect the solutions of each subproblem by calling them in the required order, or as necessary.
Wherever it’s required use classes and objects while handling questions (for real-world problems like management systems, etc.)
Before you jump into the solution it’s always good to write pseudocode for your problem. Basically, pseudocode defines the structure of your code and it will help you to write every line of code that you need in order to solve the problem. Reading pseudocode gives a clear idea that what your code is supposed to do. A lot of people or experienced programmers skip this step but when you write pseudocode the process of writing the final code becomes easier for you. In the end, you will have to only translate each line of pseudocode into actual code. So write down every step and logic in your pseudocode. Below is one of the examples of pseudocode that returns the array of even numbers...
function getEvenNumbers
evenNumbers = []
for i = 0 to i = length of evenNumbers
if (element % 2 === 0)
add to that to the array evenNumbers
return evenNumbers
Once you have written the pseudocode it’s time to translate this into actual code. Replace each line of your pseudocode into real code in the language you are working on. If you have divided your problem into subproblems then write down the code for each subproblem. While writing the code keep in mind three things...
The point where you started
Where are you right now?
What is your destination (end result)?
Don’t forget to test your code with sample sets of data (we have discussed in step 2) to check if the actual output is equal to the expected output. Once you are done with coding you can get rid of pseudocode. Below is the code for the example we have considered in the previous steps...
Javascript
function getEvenNumbers(arrayofNumbers) { let evenNumbers = []for (var i = 0; i < arrayofNumbers.length; i++) { if (arrayofNumbers[i] % 2 === 0) { evenNumbers.push(arrayofNumbers[i]) } }return evenNumbers}
When you are writing the code in your interviews keep telling the interviewer about how you are approaching the problem.
Tell the interviewer how you are trying to start
Tell the interviewer about your approach to solving the problem
Discuss with the interviewer the most difficult part you are facing in your problem.
Tell the interviewer about the approach to solving each sub-problem in order to get the final output.
Discuss the sample data or test cases with the interviewer.
Discuss the better solution with the interviewer.
Always try to improve your code. Look back, analyze it once again and try to find a better or alternate solution. We have mentioned earlier that you should always try to write the right amount of good code so always look for the alternate solution which is more efficient than the previous one. Writing the correct solution to your problem is not the final thing you should do. Explore the problem completely with all possible solutions and then write down the most efficient or optimized solution for your code. So once you are done with writing the solution for your code below are some questions you should ask yourself.
Does this code run for every possible input including the edge cases.
Is there an alternate solution for the same problem?
Is the code efficient? Can it be more efficient or can the performance be improved?
How else can you make the code more readable?
Are there any more extra steps or functions you can take out?
Is there any repetition in your code? Take it out.
Below is the alternate solution for the same problem of the array which returns even numbers...
function getEvenNumbers(arrayofNumbers) {
let evenNumbers = arrayofNumbers.filter(n => n % 2 === 0)
return evenNumbers
}
bunnyram19
Pushpender007
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 373,
"s": 52,
"text": "Developers and students solve a lot of coding questions of data structures and algorithms but most of them don’t understand the importance of it. A lot of them also have this opinion that data structure and algorithms only help in interviews and after that, there is no use of all those complicated stuff in daily jobs. "
},
{
"code": null,
"e": 1101,
"s": 373,
"text": "You might be one of them who is happy with learning a new language or framework and building some applications with that but once you will enter the real world industry, you will realize that your job is not just writing the code and make things work. Your real job is to write the right amount of good code which means it should be efficient and robust and here comes the role of data structures and algorithms. Data Structures and Algorithms not only help in getting the logic for your program but also helps in writing the efficient code for your software. Whether we talk about the time complexity or memory management, code refactoring, or code reusability, you will understand its value in each part of your application. "
},
{
"code": null,
"e": 1528,
"s": 1101,
"text": "In real-world projects, your brain should be able to write a quick efficient solution for complicated stuff and you can only do that when you practice a lot of coding questions. Understand that language and frameworks are just tools, they won’t teach you problem-solving skills. You develop problem-solving skills when you practice a lot of coding questions. Firstly understand the importance of DSA with these two articles..."
},
{
"code": null,
"e": 1587,
"s": 1528,
"text": "Why Data Structures and Algorithms Are Important to Learn?"
},
{
"code": null,
"e": 1639,
"s": 1587,
"text": "I Can’t Use Logic In Programming. What Should I Do?"
},
{
"code": null,
"e": 2244,
"s": 1639,
"text": "Every developer has their own tricks and they follow their own pattern to solve coding problems but when it comes to new developers they are always uncertain about where to start. A lot of them understand the problems, the logic, and the basics of syntax, they also understand someone else codes and they can follow along with them but when it comes to solving the questions on their own, they get stuck. They don’t understand how to turn their thoughts into code even though they understand the syntax or logic. We are going to share some simple steps that will help you to approach a coding question. "
},
{
"code": null,
"e": 2790,
"s": 2244,
"text": "It doesn’t matter if you have seen the question in the past or not, read the question several times and understand it completely. Now, think about the question and analyze it carefully. Sometimes we read a few lines and assume the rest of the things on our own but a slight change in your question can change a lot of things in your code so be careful about that. Now take a paper and write down everything. What is given (input) and what you need to find out (output)? While going through the problem you need to ask a few questions yourself..."
},
{
"code": null,
"e": 3155,
"s": 2790,
"text": "Did you understand the problem fully?Would you be able to explain this question to someone else?What and how many inputs are required?What would be the output for those inputsDo you need to separate out some modules or parts from the problem?Do you have enough information to solve that question? If not then read the question again or clear it to the interviewer."
},
{
"code": null,
"e": 3193,
"s": 3155,
"text": "Did you understand the problem fully?"
},
{
"code": null,
"e": 3253,
"s": 3193,
"text": "Would you be able to explain this question to someone else?"
},
{
"code": null,
"e": 3292,
"s": 3253,
"text": "What and how many inputs are required?"
},
{
"code": null,
"e": 3334,
"s": 3292,
"text": "What would be the output for those inputs"
},
{
"code": null,
"e": 3402,
"s": 3334,
"text": "Do you need to separate out some modules or parts from the problem?"
},
{
"code": null,
"e": 3525,
"s": 3402,
"text": "Do you have enough information to solve that question? If not then read the question again or clear it to the interviewer."
},
{
"code": null,
"e": 3784,
"s": 3525,
"text": "For Example: If you are given an array and you need to return the array that contains only even numbers then first of all analyze the problem carefully. While going through the problem a few questions you should ask yourself before jumping into the solution."
},
{
"code": null,
"e": 4151,
"s": 3784,
"text": "How to identify an even number? Divide that number by 2 and see if its remainder is 0.What should I pass into this function? An arrayWhat will that array contain? One or more numbersWhat are the data types of the elements in the array? NumbersWhat is the end goal? The goal is to return the array of even numbers. If there are no even numbers, return an empty array."
},
{
"code": null,
"e": 4238,
"s": 4151,
"text": "How to identify an even number? Divide that number by 2 and see if its remainder is 0."
},
{
"code": null,
"e": 4286,
"s": 4238,
"text": "What should I pass into this function? An array"
},
{
"code": null,
"e": 4336,
"s": 4286,
"text": "What will that array contain? One or more numbers"
},
{
"code": null,
"e": 4398,
"s": 4336,
"text": "What are the data types of the elements in the array? Numbers"
},
{
"code": null,
"e": 4522,
"s": 4398,
"text": "What is the end goal? The goal is to return the array of even numbers. If there are no even numbers, return an empty array."
},
{
"code": null,
"e": 4856,
"s": 4522,
"text": "When you try to understand the problem take some sample inputs and try to analyze the output. Taking some sample inputs will help you to understand the problem in a better way. You will also get clarity that how many cases your code can handle and what all can be the possible output or output range. Read the points given below... "
},
{
"code": null,
"e": 4916,
"s": 4856,
"text": "Consider some simple inputs or data and analyze the output."
},
{
"code": null,
"e": 5045,
"s": 4916,
"text": "Consider some complex and bigger input and identify what will be the output and how many cases you need to take for the problem."
},
{
"code": null,
"e": 5167,
"s": 5045,
"text": "Consider the edge cases as well. Analyze what would be the output if there is no input or if you give some invalid input."
},
{
"code": null,
"e": 5357,
"s": 5167,
"text": "For Example: If you need to return the array of even numbers from a given array then below are some variety of cases or sample inputs for which you can analyze the problem and its output. "
},
{
"code": null,
"e": 5436,
"s": 5357,
"text": "[1]\n[1, 2]\n[1, 2, 3, 4, 5, 6]\n[-300.35]\n[-700.1, 1000, 5.1, -1000.25, 52, 900]"
},
{
"code": null,
"e": 5750,
"s": 5436,
"text": "When you see a coding question that is complex or big, instead of being afraid and getting confused that how to solve that question, break down the problem into smaller chunks and then try to solve each part of the problem. Below are some steps you should follow in order to solve the complex coding questions... "
},
{
"code": null,
"e": 5802,
"s": 5750,
"text": "Make a flow chart or a UML for the problem at hand."
},
{
"code": null,
"e": 5858,
"s": 5802,
"text": "Divide the problem into sub-problems or smaller chunks."
},
{
"code": null,
"e": 5929,
"s": 5858,
"text": "Solve the subproblems. Make independent functions for each subproblem."
},
{
"code": null,
"e": 6026,
"s": 5929,
"text": "Connect the solutions of each subproblem by calling them in the required order, or as necessary."
},
{
"code": null,
"e": 6154,
"s": 6026,
"text": "Wherever it’s required use classes and objects while handling questions (for real-world problems like management systems, etc.)"
},
{
"code": null,
"e": 6847,
"s": 6154,
"text": "Before you jump into the solution it’s always good to write pseudocode for your problem. Basically, pseudocode defines the structure of your code and it will help you to write every line of code that you need in order to solve the problem. Reading pseudocode gives a clear idea that what your code is supposed to do. A lot of people or experienced programmers skip this step but when you write pseudocode the process of writing the final code becomes easier for you. In the end, you will have to only translate each line of pseudocode into actual code. So write down every step and logic in your pseudocode. Below is one of the examples of pseudocode that returns the array of even numbers..."
},
{
"code": null,
"e": 7013,
"s": 6847,
"text": "function getEvenNumbers\nevenNumbers = []\nfor i = 0 to i = length of evenNumbers\n if (element % 2 === 0) \n add to that to the array evenNumbers\nreturn evenNumbers"
},
{
"code": null,
"e": 7333,
"s": 7013,
"text": "Once you have written the pseudocode it’s time to translate this into actual code. Replace each line of your pseudocode into real code in the language you are working on. If you have divided your problem into subproblems then write down the code for each subproblem. While writing the code keep in mind three things... "
},
{
"code": null,
"e": 7361,
"s": 7333,
"text": "The point where you started"
},
{
"code": null,
"e": 7386,
"s": 7361,
"text": "Where are you right now?"
},
{
"code": null,
"e": 7425,
"s": 7386,
"text": "What is your destination (end result)?"
},
{
"code": null,
"e": 7714,
"s": 7425,
"text": "Don’t forget to test your code with sample sets of data (we have discussed in step 2) to check if the actual output is equal to the expected output. Once you are done with coding you can get rid of pseudocode. Below is the code for the example we have considered in the previous steps... "
},
{
"code": null,
"e": 7725,
"s": 7714,
"text": "Javascript"
},
{
"code": "function getEvenNumbers(arrayofNumbers) { let evenNumbers = []for (var i = 0; i < arrayofNumbers.length; i++) { if (arrayofNumbers[i] % 2 === 0) { evenNumbers.push(arrayofNumbers[i]) } }return evenNumbers}",
"e": 7944,
"s": 7725,
"text": null
},
{
"code": null,
"e": 8066,
"s": 7944,
"text": "When you are writing the code in your interviews keep telling the interviewer about how you are approaching the problem. "
},
{
"code": null,
"e": 8115,
"s": 8066,
"text": "Tell the interviewer how you are trying to start"
},
{
"code": null,
"e": 8179,
"s": 8115,
"text": "Tell the interviewer about your approach to solving the problem"
},
{
"code": null,
"e": 8264,
"s": 8179,
"text": "Discuss with the interviewer the most difficult part you are facing in your problem."
},
{
"code": null,
"e": 8366,
"s": 8264,
"text": "Tell the interviewer about the approach to solving each sub-problem in order to get the final output."
},
{
"code": null,
"e": 8426,
"s": 8366,
"text": "Discuss the sample data or test cases with the interviewer."
},
{
"code": null,
"e": 8476,
"s": 8426,
"text": "Discuss the better solution with the interviewer."
},
{
"code": null,
"e": 9100,
"s": 8476,
"text": "Always try to improve your code. Look back, analyze it once again and try to find a better or alternate solution. We have mentioned earlier that you should always try to write the right amount of good code so always look for the alternate solution which is more efficient than the previous one. Writing the correct solution to your problem is not the final thing you should do. Explore the problem completely with all possible solutions and then write down the most efficient or optimized solution for your code. So once you are done with writing the solution for your code below are some questions you should ask yourself."
},
{
"code": null,
"e": 9170,
"s": 9100,
"text": "Does this code run for every possible input including the edge cases."
},
{
"code": null,
"e": 9223,
"s": 9170,
"text": "Is there an alternate solution for the same problem?"
},
{
"code": null,
"e": 9307,
"s": 9223,
"text": "Is the code efficient? Can it be more efficient or can the performance be improved?"
},
{
"code": null,
"e": 9353,
"s": 9307,
"text": "How else can you make the code more readable?"
},
{
"code": null,
"e": 9415,
"s": 9353,
"text": "Are there any more extra steps or functions you can take out?"
},
{
"code": null,
"e": 9466,
"s": 9415,
"text": "Is there any repetition in your code? Take it out."
},
{
"code": null,
"e": 9563,
"s": 9466,
"text": "Below is the alternate solution for the same problem of the array which returns even numbers... "
},
{
"code": null,
"e": 9688,
"s": 9563,
"text": "function getEvenNumbers(arrayofNumbers) {\n let evenNumbers = arrayofNumbers.filter(n => n % 2 === 0)\n return evenNumbers\n}"
},
{
"code": null,
"e": 9701,
"s": 9690,
"text": "bunnyram19"
},
{
"code": null,
"e": 9715,
"s": 9701,
"text": "Pushpender007"
},
{
"code": null,
"e": 9739,
"s": 9715,
"text": "Competitive Programming"
}
]
|
Lottery Process Scheduling in Operating System | 16 Aug, 2019
Prerequisite – CPU Scheduling, Process ManagementLottery Scheduling is type of process scheduling, somewhat different from other Scheduling. Processes are scheduled in a random manner. Lottery scheduling can be preemptive or non-preemptive. It also solves the problem of starvation. Giving each process at least one lottery ticket guarantees that it has non-zero probability of being selected at each scheduling operation.
In this scheduling every process have some tickets and scheduler picks a random ticket and process having that ticket is the winner and it is executed for a time slice and then another ticket is picked by the scheduler. These tickets represent the share of processes. A process having a higher number of tickets give it more chance to get chosen for execution.
Example – If we have two processes A and B having 60 and 40 tickets respectively out of total 100 tickets. CPU share of A is 60% and that of B is 40%.These shares are calculated probabilistically and not deterministically.
Explanation –
We have two processes A and B. A has 60 tickets (ticket number 1 to 60) and B have 40 tickets (ticket no. 61 to 100).Scheduler picks a random number from 1 to 100. If the picked no. is from 1 to 60 then A is executed otherwise B is executed.An example of 10 tickets picked by Scheduler may look like this –Ticket number - 73 82 23 45 32 87 49 39 12 09.
Resulting Schedule - B B A A A B A A A A.
A is executed 7 times and B is executed 3 times. As you can see that A takes 70% of CPU and B takes 30% which is not the same as what we need as we need A to have 60% of CPU and B should have 40% of CPU.This happens because shares are calculated probabilistically but in a long run(i.e when no. of tickets picked is more than 100 or 1000) we can achieve a share percentage of approx. 60 and 40 for A and B respectively.
We have two processes A and B. A has 60 tickets (ticket number 1 to 60) and B have 40 tickets (ticket no. 61 to 100).
Scheduler picks a random number from 1 to 100. If the picked no. is from 1 to 60 then A is executed otherwise B is executed.
An example of 10 tickets picked by Scheduler may look like this –Ticket number - 73 82 23 45 32 87 49 39 12 09.
Resulting Schedule - B B A A A B A A A A.
Ticket number - 73 82 23 45 32 87 49 39 12 09.
Resulting Schedule - B B A A A B A A A A.
A is executed 7 times and B is executed 3 times. As you can see that A takes 70% of CPU and B takes 30% which is not the same as what we need as we need A to have 60% of CPU and B should have 40% of CPU.This happens because shares are calculated probabilistically but in a long run(i.e when no. of tickets picked is more than 100 or 1000) we can achieve a share percentage of approx. 60 and 40 for A and B respectively.
Ways to manipulate tickets –
Ticket Currency –Scheduler give a certain number of tickets to different users in a currency and users can give it to there processes in a different currency. E.g. Two users A and B are given 100 and 200 tickets respectively. User A is running two process and give 50 tickets to each in A’s own currency. B is running 1 process and gives it all 200 tickets in B’s currency. Now at the time of scheduling tickets of each process are converted into global currency i.e A’s process will have 50 tickets each and B’s process will have 200 tickets and scheduling is done on this basis.
Transfer Tickets –A process can pass its tickets to another process.
Ticket inflation –With this technique a process can temporarily raise or lower the number of tickets it own.
References –Lottery scheduling – Wikipediaeecs.berkeley.edu
This article is contributed by Ashish Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
dk619
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Aug, 2019"
},
{
"code": null,
"e": 475,
"s": 52,
"text": "Prerequisite – CPU Scheduling, Process ManagementLottery Scheduling is type of process scheduling, somewhat different from other Scheduling. Processes are scheduled in a random manner. Lottery scheduling can be preemptive or non-preemptive. It also solves the problem of starvation. Giving each process at least one lottery ticket guarantees that it has non-zero probability of being selected at each scheduling operation."
},
{
"code": null,
"e": 836,
"s": 475,
"text": "In this scheduling every process have some tickets and scheduler picks a random ticket and process having that ticket is the winner and it is executed for a time slice and then another ticket is picked by the scheduler. These tickets represent the share of processes. A process having a higher number of tickets give it more chance to get chosen for execution."
},
{
"code": null,
"e": 1059,
"s": 836,
"text": "Example – If we have two processes A and B having 60 and 40 tickets respectively out of total 100 tickets. CPU share of A is 60% and that of B is 40%.These shares are calculated probabilistically and not deterministically."
},
{
"code": null,
"e": 1073,
"s": 1059,
"text": "Explanation –"
},
{
"code": null,
"e": 1899,
"s": 1073,
"text": "We have two processes A and B. A has 60 tickets (ticket number 1 to 60) and B have 40 tickets (ticket no. 61 to 100).Scheduler picks a random number from 1 to 100. If the picked no. is from 1 to 60 then A is executed otherwise B is executed.An example of 10 tickets picked by Scheduler may look like this –Ticket number - 73 82 23 45 32 87 49 39 12 09.\nResulting Schedule - B B A A A B A A A A.\nA is executed 7 times and B is executed 3 times. As you can see that A takes 70% of CPU and B takes 30% which is not the same as what we need as we need A to have 60% of CPU and B should have 40% of CPU.This happens because shares are calculated probabilistically but in a long run(i.e when no. of tickets picked is more than 100 or 1000) we can achieve a share percentage of approx. 60 and 40 for A and B respectively."
},
{
"code": null,
"e": 2017,
"s": 1899,
"text": "We have two processes A and B. A has 60 tickets (ticket number 1 to 60) and B have 40 tickets (ticket no. 61 to 100)."
},
{
"code": null,
"e": 2142,
"s": 2017,
"text": "Scheduler picks a random number from 1 to 100. If the picked no. is from 1 to 60 then A is executed otherwise B is executed."
},
{
"code": null,
"e": 2308,
"s": 2142,
"text": "An example of 10 tickets picked by Scheduler may look like this –Ticket number - 73 82 23 45 32 87 49 39 12 09.\nResulting Schedule - B B A A A B A A A A.\n"
},
{
"code": null,
"e": 2409,
"s": 2308,
"text": "Ticket number - 73 82 23 45 32 87 49 39 12 09.\nResulting Schedule - B B A A A B A A A A.\n"
},
{
"code": null,
"e": 2829,
"s": 2409,
"text": "A is executed 7 times and B is executed 3 times. As you can see that A takes 70% of CPU and B takes 30% which is not the same as what we need as we need A to have 60% of CPU and B should have 40% of CPU.This happens because shares are calculated probabilistically but in a long run(i.e when no. of tickets picked is more than 100 or 1000) we can achieve a share percentage of approx. 60 and 40 for A and B respectively."
},
{
"code": null,
"e": 2858,
"s": 2829,
"text": "Ways to manipulate tickets –"
},
{
"code": null,
"e": 3439,
"s": 2858,
"text": "Ticket Currency –Scheduler give a certain number of tickets to different users in a currency and users can give it to there processes in a different currency. E.g. Two users A and B are given 100 and 200 tickets respectively. User A is running two process and give 50 tickets to each in A’s own currency. B is running 1 process and gives it all 200 tickets in B’s currency. Now at the time of scheduling tickets of each process are converted into global currency i.e A’s process will have 50 tickets each and B’s process will have 200 tickets and scheduling is done on this basis."
},
{
"code": null,
"e": 3508,
"s": 3439,
"text": "Transfer Tickets –A process can pass its tickets to another process."
},
{
"code": null,
"e": 3617,
"s": 3508,
"text": "Ticket inflation –With this technique a process can temporarily raise or lower the number of tickets it own."
},
{
"code": null,
"e": 3677,
"s": 3617,
"text": "References –Lottery scheduling – Wikipediaeecs.berkeley.edu"
},
{
"code": null,
"e": 3978,
"s": 3677,
"text": "This article is contributed by Ashish Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4103,
"s": 3978,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4109,
"s": 4103,
"text": "dk619"
},
{
"code": null,
"e": 4117,
"s": 4109,
"text": "GATE CS"
},
{
"code": null,
"e": 4135,
"s": 4117,
"text": "Operating Systems"
},
{
"code": null,
"e": 4153,
"s": 4135,
"text": "Operating Systems"
}
]
|
HTML Geolocation | 01 Jun, 2022
In this article, we will know HTML Geolocation, various properties, methods & their implementation through the examples.
Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to the backend server. Most of the browsers support Geolocation API. Geo-location API uses a global navigator object which can be created as follows:
Syntax:
var loc = navigator.geolocation
Location Properties: The following table determines properties used in getCurrentPosition() and their returning values.
coords.latitude: Always returns latitude as a decimal number.
coords.accuracy: Always returns the accuracy of position.
coords.longitude: Always returns longitude as a decimal number.
coords.altitude: Returns the altitude in meters above sea level if available.
coords.altitudeAccuracy: Returns altitude accuracy of position if available.
coords.heading: Returns heading in degree clockwise from North if available
coords.speed: Returns speed in mps, if available.
timestamp: Returns date or time of response if available
Geolocation Methods: The Geolocation has following methods which make it interesting and easier to work.
getCurrentPosition(): It fetches the current location of the user.
watchPosition(): It fetches periodic updates of the user’s current location.
clearWatch(): It cancels a watchPosition call currently in execution.
Example: This example explains returning the user’s current location using the getCurrentPosition() method.
HTML
var loc = navigator.geolocation;function getLoc() {loc.getCurrentPosition(showLoc, errHand);}
The above function can also be written without creating a navigator object as shown below:
HTML
function getlocation(){navigator.geolocation.getCurrentPosition(showLoc, errHand);}
Example: In this example, we simply display the current location with the help of latitude and longitude via HTML Geolocation.
HTML
<!DOCTYPE html><html> <body> <p>Displaying location using Latitude and Longitude</p> <button class="geeks" onclick="getlocation()"> Click Me </button> <p id="demo1"></p> <script> var variable1 = document.getElementById("demo1"); function getlocation() { navigator.geolocation.getCurrentPosition(showLoc); } function showLoc(pos) { variable1.innerHTML = "Latitude: " + pos.coords.latitude + "<br>Longitude: " + pos.coords.longitude; } </script></body> </html>
Output:
Getting the current location using latitude and longitude
Error and Rejection Handling: It is very important to handle the errors generated in Geolocation and show a required message when an error occurs. Functions like getCurrentPosition() make use of an error handler to handle the error generated (function errHand as used in the above example). The PositionError object used by the error handler has two properties that let the function handle error efficiently.
Code
Message
Generated errors in geolocation:
Example:
HTML
<!DOCTYPE html><html> <head> <title>Errors in geolocation</title> <style> .gfg { font-size: 40px; font-weight: bold; color: #009900; margin-left: 20px; } .geeks { margin-left: 150px; } p { font-size: 20px; margin-left: 20px; } </style></head> <body> <div class="gfg">GeeksforGeeks</div> <p>Error handling in geolocation</p> <button class="geeks" onclick="getlocation()"> Click </button> <p id="demo1"></p> <script> var variable1 = document.getElementById("demo1"); function getlocation() { navigator.geolocation.getCurrentPosition(showLoc, errHand); } function showLoc(pos) { variable1.innerHTML = "Latitude: " + pos.coords.latitude + "<br>Longitude: " + pos.coords.longitude; } function errHand(err) { switch (err.code) { case err.PERMISSION_DENIED: variable1.innerHTML = "The application doesn't have the" + "permission to make use of location services"; break; case err.POSITION_UNAVAILABLE: variable1.innerHTML = "The location of the device is uncertain"; break; case err.TIMEOUT: variable1.innerHTML = "The request to get user location timed out"; break; case err.UNKNOWN_ERROR: variable1.innerHTML = "Time to fetch location information exceeded" + "the maximum timeout interval"; break; } } </script></body> </html>
Output:
Error handling in Geolocation
Displaying result in MAP: Displaying location in a map is a very interesting task. These services are used to provide the exact location on the map.
Example: This example describes getting the current position in Google Map with the help of latitude and longitude via HTML Geolocation.
HTML
<!DOCTYPE html><html> <head> <title>Display location in map</title> <style> .gfg { font-size: 40px; font-weight: bold; color: #009900; margin-left: 20px; } .geeks { margin-left: 150px; } p { font-size: 20px; margin-left: 20px; } </style></head> <body> <div class="gfg">GeeksforGeeks</div> <p>Display location in map</p> <button class="geeks" type="button" onclick="getlocation();"> Current Position </button> <div id="demo2" style="width: 500px; height: 500px"></div> <script src="https://maps.google.com/maps/api/js?sensor=false"> </script> <script type="text/javascript"> function getlocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showLoc, errHand); } } function showLoc(pos) { latt = pos.coords.latitude; long = pos.coords.longitude; var lattlong = new google.maps.LatLng(latt, long); var OPTions = { center: lattlong, zoom: 10, mapTypeControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL, }, }; var mapg = new google.maps.Map( document.getElementById("demo2"), OPTions ); var markerg = new google.maps.Marker({ position: lattlong, map: mapg, title: "You are here!", }); } function errHand(err) { switch (err.code) { case err.PERMISSION_DENIED: result.innerHTML = "The application doesn't have the permission" + "to make use of location services"; break; case err.POSITION_UNAVAILABLE: result.innerHTML = "The location of the device is uncertain"; break; case err.TIMEOUT: result.innerHTML = "The request to get user location timed out"; break; case err.UNKNOWN_ERROR: result.innerHTML = "Time to fetch location information exceeded" + "the maximum timeout interval"; break; } } </script></body> </html>
Output:
Getting the current position in Google Map
Supported Browsers:
Google Chrome 5 and above
Microsoft Edge 12 and above
Firefox 3.5 and above
Internet Explorer 9 and above
Opera 10.6 and above
Safari 5 and above
arorakashish0911
ysachin2314
shubhamyadav4
bhaskargeeksforgeeks
kumargaurav97520
HTML-Basics
Picked
CSS
HTML
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 173,
"s": 52,
"text": "In this article, we will know HTML Geolocation, various properties, methods & their implementation through the examples."
},
{
"code": null,
"e": 566,
"s": 173,
"text": "Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to the backend server. Most of the browsers support Geolocation API. Geo-location API uses a global navigator object which can be created as follows:"
},
{
"code": null,
"e": 574,
"s": 566,
"text": "Syntax:"
},
{
"code": null,
"e": 606,
"s": 574,
"text": "var loc = navigator.geolocation"
},
{
"code": null,
"e": 726,
"s": 606,
"text": "Location Properties: The following table determines properties used in getCurrentPosition() and their returning values."
},
{
"code": null,
"e": 788,
"s": 726,
"text": "coords.latitude: Always returns latitude as a decimal number."
},
{
"code": null,
"e": 846,
"s": 788,
"text": "coords.accuracy: Always returns the accuracy of position."
},
{
"code": null,
"e": 910,
"s": 846,
"text": "coords.longitude: Always returns longitude as a decimal number."
},
{
"code": null,
"e": 988,
"s": 910,
"text": "coords.altitude: Returns the altitude in meters above sea level if available."
},
{
"code": null,
"e": 1065,
"s": 988,
"text": "coords.altitudeAccuracy: Returns altitude accuracy of position if available."
},
{
"code": null,
"e": 1141,
"s": 1065,
"text": "coords.heading: Returns heading in degree clockwise from North if available"
},
{
"code": null,
"e": 1191,
"s": 1141,
"text": "coords.speed: Returns speed in mps, if available."
},
{
"code": null,
"e": 1248,
"s": 1191,
"text": "timestamp: Returns date or time of response if available"
},
{
"code": null,
"e": 1353,
"s": 1248,
"text": "Geolocation Methods: The Geolocation has following methods which make it interesting and easier to work."
},
{
"code": null,
"e": 1420,
"s": 1353,
"text": "getCurrentPosition(): It fetches the current location of the user."
},
{
"code": null,
"e": 1497,
"s": 1420,
"text": "watchPosition(): It fetches periodic updates of the user’s current location."
},
{
"code": null,
"e": 1567,
"s": 1497,
"text": "clearWatch(): It cancels a watchPosition call currently in execution."
},
{
"code": null,
"e": 1675,
"s": 1567,
"text": "Example: This example explains returning the user’s current location using the getCurrentPosition() method."
},
{
"code": null,
"e": 1680,
"s": 1675,
"text": "HTML"
},
{
"code": "var loc = navigator.geolocation;function getLoc() {loc.getCurrentPosition(showLoc, errHand);}",
"e": 1774,
"s": 1680,
"text": null
},
{
"code": null,
"e": 1866,
"s": 1774,
"text": "The above function can also be written without creating a navigator object as shown below: "
},
{
"code": null,
"e": 1871,
"s": 1866,
"text": "HTML"
},
{
"code": "function getlocation(){navigator.geolocation.getCurrentPosition(showLoc, errHand);}",
"e": 1955,
"s": 1871,
"text": null
},
{
"code": null,
"e": 2082,
"s": 1955,
"text": "Example: In this example, we simply display the current location with the help of latitude and longitude via HTML Geolocation."
},
{
"code": null,
"e": 2087,
"s": 2082,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <p>Displaying location using Latitude and Longitude</p> <button class=\"geeks\" onclick=\"getlocation()\"> Click Me </button> <p id=\"demo1\"></p> <script> var variable1 = document.getElementById(\"demo1\"); function getlocation() { navigator.geolocation.getCurrentPosition(showLoc); } function showLoc(pos) { variable1.innerHTML = \"Latitude: \" + pos.coords.latitude + \"<br>Longitude: \" + pos.coords.longitude; } </script></body> </html>",
"e": 2619,
"s": 2087,
"text": null
},
{
"code": null,
"e": 2627,
"s": 2619,
"text": "Output:"
},
{
"code": null,
"e": 2685,
"s": 2627,
"text": "Getting the current location using latitude and longitude"
},
{
"code": null,
"e": 3094,
"s": 2685,
"text": "Error and Rejection Handling: It is very important to handle the errors generated in Geolocation and show a required message when an error occurs. Functions like getCurrentPosition() make use of an error handler to handle the error generated (function errHand as used in the above example). The PositionError object used by the error handler has two properties that let the function handle error efficiently."
},
{
"code": null,
"e": 3099,
"s": 3094,
"text": "Code"
},
{
"code": null,
"e": 3107,
"s": 3099,
"text": "Message"
},
{
"code": null,
"e": 3141,
"s": 3107,
"text": "Generated errors in geolocation: "
},
{
"code": null,
"e": 3151,
"s": 3141,
"text": "Example: "
},
{
"code": null,
"e": 3156,
"s": 3151,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Errors in geolocation</title> <style> .gfg { font-size: 40px; font-weight: bold; color: #009900; margin-left: 20px; } .geeks { margin-left: 150px; } p { font-size: 20px; margin-left: 20px; } </style></head> <body> <div class=\"gfg\">GeeksforGeeks</div> <p>Error handling in geolocation</p> <button class=\"geeks\" onclick=\"getlocation()\"> Click </button> <p id=\"demo1\"></p> <script> var variable1 = document.getElementById(\"demo1\"); function getlocation() { navigator.geolocation.getCurrentPosition(showLoc, errHand); } function showLoc(pos) { variable1.innerHTML = \"Latitude: \" + pos.coords.latitude + \"<br>Longitude: \" + pos.coords.longitude; } function errHand(err) { switch (err.code) { case err.PERMISSION_DENIED: variable1.innerHTML = \"The application doesn't have the\" + \"permission to make use of location services\"; break; case err.POSITION_UNAVAILABLE: variable1.innerHTML = \"The location of the device is uncertain\"; break; case err.TIMEOUT: variable1.innerHTML = \"The request to get user location timed out\"; break; case err.UNKNOWN_ERROR: variable1.innerHTML = \"Time to fetch location information exceeded\" + \"the maximum timeout interval\"; break; } } </script></body> </html>",
"e": 4672,
"s": 3156,
"text": null
},
{
"code": null,
"e": 4680,
"s": 4672,
"text": "Output:"
},
{
"code": null,
"e": 4711,
"s": 4680,
"text": "Error handling in Geolocation "
},
{
"code": null,
"e": 4860,
"s": 4711,
"text": "Displaying result in MAP: Displaying location in a map is a very interesting task. These services are used to provide the exact location on the map."
},
{
"code": null,
"e": 4997,
"s": 4860,
"text": "Example: This example describes getting the current position in Google Map with the help of latitude and longitude via HTML Geolocation."
},
{
"code": null,
"e": 5002,
"s": 4997,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Display location in map</title> <style> .gfg { font-size: 40px; font-weight: bold; color: #009900; margin-left: 20px; } .geeks { margin-left: 150px; } p { font-size: 20px; margin-left: 20px; } </style></head> <body> <div class=\"gfg\">GeeksforGeeks</div> <p>Display location in map</p> <button class=\"geeks\" type=\"button\" onclick=\"getlocation();\"> Current Position </button> <div id=\"demo2\" style=\"width: 500px; height: 500px\"></div> <script src=\"https://maps.google.com/maps/api/js?sensor=false\"> </script> <script type=\"text/javascript\"> function getlocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showLoc, errHand); } } function showLoc(pos) { latt = pos.coords.latitude; long = pos.coords.longitude; var lattlong = new google.maps.LatLng(latt, long); var OPTions = { center: lattlong, zoom: 10, mapTypeControl: true, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL, }, }; var mapg = new google.maps.Map( document.getElementById(\"demo2\"), OPTions ); var markerg = new google.maps.Marker({ position: lattlong, map: mapg, title: \"You are here!\", }); } function errHand(err) { switch (err.code) { case err.PERMISSION_DENIED: result.innerHTML = \"The application doesn't have the permission\" + \"to make use of location services\"; break; case err.POSITION_UNAVAILABLE: result.innerHTML = \"The location of the device is uncertain\"; break; case err.TIMEOUT: result.innerHTML = \"The request to get user location timed out\"; break; case err.UNKNOWN_ERROR: result.innerHTML = \"Time to fetch location information exceeded\" + \"the maximum timeout interval\"; break; } } </script></body> </html>",
"e": 7081,
"s": 5002,
"text": null
},
{
"code": null,
"e": 7089,
"s": 7081,
"text": "Output:"
},
{
"code": null,
"e": 7132,
"s": 7089,
"text": "Getting the current position in Google Map"
},
{
"code": null,
"e": 7152,
"s": 7132,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 7178,
"s": 7152,
"text": "Google Chrome 5 and above"
},
{
"code": null,
"e": 7206,
"s": 7178,
"text": "Microsoft Edge 12 and above"
},
{
"code": null,
"e": 7228,
"s": 7206,
"text": "Firefox 3.5 and above"
},
{
"code": null,
"e": 7258,
"s": 7228,
"text": "Internet Explorer 9 and above"
},
{
"code": null,
"e": 7279,
"s": 7258,
"text": "Opera 10.6 and above"
},
{
"code": null,
"e": 7298,
"s": 7279,
"text": "Safari 5 and above"
},
{
"code": null,
"e": 7315,
"s": 7298,
"text": "arorakashish0911"
},
{
"code": null,
"e": 7327,
"s": 7315,
"text": "ysachin2314"
},
{
"code": null,
"e": 7341,
"s": 7327,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 7362,
"s": 7341,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 7379,
"s": 7362,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 7391,
"s": 7379,
"text": "HTML-Basics"
},
{
"code": null,
"e": 7398,
"s": 7391,
"text": "Picked"
},
{
"code": null,
"e": 7402,
"s": 7398,
"text": "CSS"
},
{
"code": null,
"e": 7407,
"s": 7402,
"text": "HTML"
},
{
"code": null,
"e": 7434,
"s": 7407,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 7439,
"s": 7434,
"text": "HTML"
},
{
"code": null,
"e": 7537,
"s": 7439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7585,
"s": 7537,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 7647,
"s": 7585,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7697,
"s": 7647,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7755,
"s": 7697,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 7805,
"s": 7755,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 7853,
"s": 7805,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 7915,
"s": 7853,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7965,
"s": 7915,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7989,
"s": 7965,
"text": "REST API (Introduction)"
}
]
|
Minimum number of edges to be removed from given Graph such that no path exists between given pairs of vertices | 16 Feb, 2022
Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn’t exist any path for every pair (u, v) in the array arr[].
Examples:
Input: arr[] = {{1, 4}, {2, 5}Output: 1Explanation:For N = 5, the given graph can be represented as:
1 <-> 2 <-> 3 <-> 4 <-> 5
After removing the edge between vertices 2 and 3 or the edge between vertices 3 and 4, the graph modifies to:
1 <-> 2 3 <-> 4 <-> 5
Now, there doesn’t exist any path between every pair of nodes in the array. Therefore, the minimum number of edges that should be removed is 1.
Input: arr[] = {{1, 8}, {2, 7}, {3, 5}, {4, 6}, {7, 9}}Output: 2
Approach: The given problem can be solved using a Greedy Approach. The idea is to sort the given array of pairs arr[] in increasing order of ending pairs and for each pair, say (u, v) remove the nearest edges connected to the vertex v so that all the other vertices on the connected components containing vertex v is unreachable. Follow the steps below to solve the given problem:
Create a variable, say minEdges as 0, that stores the count of removed edges.
Create a variable reachable as 0, that keeps track of the smallest vertex that is reachable from the last vertex i.e., N.
Sort the given array of pairs arr[] in increasing order of the second value of the pairs.
Traverse the given array arr[] and for every pair (u, v) in arr[], if reachable > u, it implies that there exists no path between u and v, otherwise removing the last edge between (v – 1) and v is the most optimal choice. Therefore, increment the value of minEdges by 1 and the value of reachable will be equal to v.
After completing the above steps, print the value of minEdges as 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; // Comparator function to sort the// given array of pairs in increasing// order of second value of the pairsbool comp(pair<int, int> a, pair<int, int> b){ if (a.second < b.second) { return true; } return false;} // Function to find minimum number of edges// to be removed such that there exist no// path between each pair in the array arr[]int findMinEdges(vector<pair<int, int> > arr, int N){ // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair sort(arr.begin(), arr.end(), comp); // Loop to iterate through array arr[] for (int i = 0; i < arr.size(); i++) { // If reachable > arr[i].first, there // exist no path between arr[i].first // and arr[i].second, hence continue if (reachable > arr[i].first) continue; else { // Update the reachable vertex reachable = arr[i].second; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges;} // Driver Codeint main(){ vector<pair<int, int> > arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; int N = arr.size(); cout << findMinEdges(arr, N); return 0;}
// Java program for the above approachimport java.util.Arrays; class GFG{ // Comparator function to sort the // given array of pairs in increasing // order of second value of the pairs // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array arr[] public static int findMinEdges(int[][] arr, int N) { // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair Arrays.sort(arr, (a, b) -> (a[1] - b[1])); // Loop to iterate through array arr[] for (int i = 0; i < arr.length; i++) { // If reachable > arr[i][0], there // exist no path between arr[i][0] // and arr[i][1], hence continue if (reachable > arr[i][0]) continue; else { // Update the reachable vertex reachable = arr[i][1]; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code public static void main(String args[]) { int[][] arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; int N = arr.length; System.out.println(findMinEdges(arr, N)); }} // This code is contributed by _saurabh_jaiswal.
# Python 3 program for the above approach # Comparator function to sort the# given array of pairs in increasing# order of second value of the pairs # Function to find minimum number of edges# to be removed such that there exist no# path between each pair in the array arr[]def findMinEdges(arr, N): # Stores the count of edges to be deleted minEdges = 0 # Stores the smallest vertex reachable # from the current vertex reachable = 0 # Sort the array arr[] in increasing # order of the second value of the pair arr.sort() # Loop to iterate through array arr[] for i in range(len(arr)): # If reachable > arr[i].first, there # exist no path between arr[i].first # and arr[i].second, hence continue if (reachable > arr[i][0]): continue else: # Update the reachable vertex reachable = arr[i][1] # Increment minEdges by 1 minEdges += 1 # Return answer return minEdges+1 # Driver Codeif __name__ == '__main__': arr = [[1, 8],[2, 7],[3, 5],[4, 6],[7, 9]] N = len(arr) print(findMinEdges(arr, N)) # This code is contributed by SURENDRA_GANGWAR.
// C# program for the above approachusing System;using System.Linq;using System.Collections.Generic;public class GFG { // Comparator function to sort the // given array of pairs in increasing // order of second value of the pairs // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array []arr public static int findMinEdges(List<List<int>> arr, int N) { // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array []arr in increasing // order of the second value of the pair arr.Sort((a, b) => a[1] - b[1]); // Loop to iterate through array []arr for (int i = 0; i < arr.Count; i++) { // If reachable > arr[i,0], there // exist no path between arr[i,0] // and arr[i,1], hence continue if (reachable > arr[i][0]) continue; else { // Update the reachable vertex reachable = arr[i][1]; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code public static void Main(String []args) { int[,] arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; List<List<int>> arr1 = new List<List<int>>(); for(int i = 0;i<arr.GetLength(0);i++){ List<int> arr2 = new List<int>(); arr2.Add(arr[i,0]); arr2.Add(arr[i,1]); arr1.Add(arr2); } int N = arr.GetLength(0); Console.WriteLine(findMinEdges(arr1, N)); }} // This code is contributed by Rajput-Ji
<script> // JavaScript Program to implement // the above approach // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array arr[] function findMinEdges(arr, N) { // Stores the count of edges to be deleted let minEdges = 0; // Stores the smallest vertex reachable // from the current vertex let reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair arr.sort(function (a, b) { return a.second - b.second }) // Loop to iterate through array arr[] for (let i = 0; i < arr.length; i++) { // If reachable > arr[i].first, there // exist no path between arr[i].first // and arr[i].second, hence continue if (reachable > arr[i].first) continue; else { // Update the reachable vertex reachable = arr[i].second; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code let arr = [{first: 1, second: 8}, { first: 2, second: 7 }, { first: 3, second: 5 }, { first: 4, second: 6 }, { first: 7, second: 9 }]; let N = arr.length; document.write(findMinEdges(arr, N)); // This code is contributed by Potta Lokesh </script>
2
Time Complexity: O(M*log M)Auxiliary Space: O(1)
SURENDRA_GANGWAR
lokeshpotta20
_saurabh_jaiswal
Rajput-Ji
simmytarika5
Activity Selection Problem
Arrays
Graph
Greedy
Mathematical
Sorting
Arrays
Greedy
Mathematical
Sorting
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 389,
"s": 54,
"text": "Given an undirected graph consisting of N valued over the range [1, N] such that vertices (i, i + 1) are connected and an array arr[] consisting of M pair of integers, the task is to find the minimum number of edges that should be removed from the graph such that there doesn’t exist any path for every pair (u, v) in the array arr[]."
},
{
"code": null,
"e": 399,
"s": 389,
"text": "Examples:"
},
{
"code": null,
"e": 500,
"s": 399,
"text": "Input: arr[] = {{1, 4}, {2, 5}Output: 1Explanation:For N = 5, the given graph can be represented as:"
},
{
"code": null,
"e": 526,
"s": 500,
"text": "1 <-> 2 <-> 3 <-> 4 <-> 5"
},
{
"code": null,
"e": 636,
"s": 526,
"text": "After removing the edge between vertices 2 and 3 or the edge between vertices 3 and 4, the graph modifies to:"
},
{
"code": null,
"e": 664,
"s": 636,
"text": "1 <-> 2 3 <-> 4 <-> 5"
},
{
"code": null,
"e": 808,
"s": 664,
"text": "Now, there doesn’t exist any path between every pair of nodes in the array. Therefore, the minimum number of edges that should be removed is 1."
},
{
"code": null,
"e": 873,
"s": 808,
"text": "Input: arr[] = {{1, 8}, {2, 7}, {3, 5}, {4, 6}, {7, 9}}Output: 2"
},
{
"code": null,
"e": 1254,
"s": 873,
"text": "Approach: The given problem can be solved using a Greedy Approach. The idea is to sort the given array of pairs arr[] in increasing order of ending pairs and for each pair, say (u, v) remove the nearest edges connected to the vertex v so that all the other vertices on the connected components containing vertex v is unreachable. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 1332,
"s": 1254,
"text": "Create a variable, say minEdges as 0, that stores the count of removed edges."
},
{
"code": null,
"e": 1454,
"s": 1332,
"text": "Create a variable reachable as 0, that keeps track of the smallest vertex that is reachable from the last vertex i.e., N."
},
{
"code": null,
"e": 1544,
"s": 1454,
"text": "Sort the given array of pairs arr[] in increasing order of the second value of the pairs."
},
{
"code": null,
"e": 1861,
"s": 1544,
"text": "Traverse the given array arr[] and for every pair (u, v) in arr[], if reachable > u, it implies that there exists no path between u and v, otherwise removing the last edge between (v – 1) and v is the most optimal choice. Therefore, increment the value of minEdges by 1 and the value of reachable will be equal to v."
},
{
"code": null,
"e": 1934,
"s": 1861,
"text": "After completing the above steps, print the value of minEdges as result."
},
{
"code": null,
"e": 1985,
"s": 1934,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1989,
"s": 1985,
"text": "C++"
},
{
"code": null,
"e": 1994,
"s": 1989,
"text": "Java"
},
{
"code": null,
"e": 2002,
"s": 1994,
"text": "Python3"
},
{
"code": null,
"e": 2005,
"s": 2002,
"text": "C#"
},
{
"code": null,
"e": 2016,
"s": 2005,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Comparator function to sort the// given array of pairs in increasing// order of second value of the pairsbool comp(pair<int, int> a, pair<int, int> b){ if (a.second < b.second) { return true; } return false;} // Function to find minimum number of edges// to be removed such that there exist no// path between each pair in the array arr[]int findMinEdges(vector<pair<int, int> > arr, int N){ // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair sort(arr.begin(), arr.end(), comp); // Loop to iterate through array arr[] for (int i = 0; i < arr.size(); i++) { // If reachable > arr[i].first, there // exist no path between arr[i].first // and arr[i].second, hence continue if (reachable > arr[i].first) continue; else { // Update the reachable vertex reachable = arr[i].second; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges;} // Driver Codeint main(){ vector<pair<int, int> > arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; int N = arr.size(); cout << findMinEdges(arr, N); return 0;}",
"e": 3498,
"s": 2016,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays; class GFG{ // Comparator function to sort the // given array of pairs in increasing // order of second value of the pairs // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array arr[] public static int findMinEdges(int[][] arr, int N) { // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair Arrays.sort(arr, (a, b) -> (a[1] - b[1])); // Loop to iterate through array arr[] for (int i = 0; i < arr.length; i++) { // If reachable > arr[i][0], there // exist no path between arr[i][0] // and arr[i][1], hence continue if (reachable > arr[i][0]) continue; else { // Update the reachable vertex reachable = arr[i][1]; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code public static void main(String args[]) { int[][] arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; int N = arr.length; System.out.println(findMinEdges(arr, N)); }} // This code is contributed by _saurabh_jaiswal.",
"e": 5040,
"s": 3498,
"text": null
},
{
"code": "# Python 3 program for the above approach # Comparator function to sort the# given array of pairs in increasing# order of second value of the pairs # Function to find minimum number of edges# to be removed such that there exist no# path between each pair in the array arr[]def findMinEdges(arr, N): # Stores the count of edges to be deleted minEdges = 0 # Stores the smallest vertex reachable # from the current vertex reachable = 0 # Sort the array arr[] in increasing # order of the second value of the pair arr.sort() # Loop to iterate through array arr[] for i in range(len(arr)): # If reachable > arr[i].first, there # exist no path between arr[i].first # and arr[i].second, hence continue if (reachable > arr[i][0]): continue else: # Update the reachable vertex reachable = arr[i][1] # Increment minEdges by 1 minEdges += 1 # Return answer return minEdges+1 # Driver Codeif __name__ == '__main__': arr = [[1, 8],[2, 7],[3, 5],[4, 6],[7, 9]] N = len(arr) print(findMinEdges(arr, N)) # This code is contributed by SURENDRA_GANGWAR.",
"e": 6226,
"s": 5040,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Linq;using System.Collections.Generic;public class GFG { // Comparator function to sort the // given array of pairs in increasing // order of second value of the pairs // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array []arr public static int findMinEdges(List<List<int>> arr, int N) { // Stores the count of edges to be deleted int minEdges = 0; // Stores the smallest vertex reachable // from the current vertex int reachable = 0; // Sort the array []arr in increasing // order of the second value of the pair arr.Sort((a, b) => a[1] - b[1]); // Loop to iterate through array []arr for (int i = 0; i < arr.Count; i++) { // If reachable > arr[i,0], there // exist no path between arr[i,0] // and arr[i,1], hence continue if (reachable > arr[i][0]) continue; else { // Update the reachable vertex reachable = arr[i][1]; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code public static void Main(String []args) { int[,] arr = { { 1, 8 }, { 2, 7 }, { 3, 5 }, { 4, 6 }, { 7, 9 } }; List<List<int>> arr1 = new List<List<int>>(); for(int i = 0;i<arr.GetLength(0);i++){ List<int> arr2 = new List<int>(); arr2.Add(arr[i,0]); arr2.Add(arr[i,1]); arr1.Add(arr2); } int N = arr.GetLength(0); Console.WriteLine(findMinEdges(arr1, N)); }} // This code is contributed by Rajput-Ji",
"e": 8079,
"s": 6226,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Function to find minimum number of edges // to be removed such that there exist no // path between each pair in the array arr[] function findMinEdges(arr, N) { // Stores the count of edges to be deleted let minEdges = 0; // Stores the smallest vertex reachable // from the current vertex let reachable = 0; // Sort the array arr[] in increasing // order of the second value of the pair arr.sort(function (a, b) { return a.second - b.second }) // Loop to iterate through array arr[] for (let i = 0; i < arr.length; i++) { // If reachable > arr[i].first, there // exist no path between arr[i].first // and arr[i].second, hence continue if (reachable > arr[i].first) continue; else { // Update the reachable vertex reachable = arr[i].second; // Increment minEdges by 1 minEdges++; } } // Return answer return minEdges; } // Driver Code let arr = [{first: 1, second: 8}, { first: 2, second: 7 }, { first: 3, second: 5 }, { first: 4, second: 6 }, { first: 7, second: 9 }]; let N = arr.length; document.write(findMinEdges(arr, N)); // This code is contributed by Potta Lokesh </script>",
"e": 9724,
"s": 8079,
"text": null
},
{
"code": null,
"e": 9726,
"s": 9724,
"text": "2"
},
{
"code": null,
"e": 9777,
"s": 9728,
"text": "Time Complexity: O(M*log M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9794,
"s": 9777,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 9808,
"s": 9794,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 9825,
"s": 9808,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 9835,
"s": 9825,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9848,
"s": 9835,
"text": "simmytarika5"
},
{
"code": null,
"e": 9875,
"s": 9848,
"text": "Activity Selection Problem"
},
{
"code": null,
"e": 9882,
"s": 9875,
"text": "Arrays"
},
{
"code": null,
"e": 9888,
"s": 9882,
"text": "Graph"
},
{
"code": null,
"e": 9895,
"s": 9888,
"text": "Greedy"
},
{
"code": null,
"e": 9908,
"s": 9895,
"text": "Mathematical"
},
{
"code": null,
"e": 9916,
"s": 9908,
"text": "Sorting"
},
{
"code": null,
"e": 9923,
"s": 9916,
"text": "Arrays"
},
{
"code": null,
"e": 9930,
"s": 9923,
"text": "Greedy"
},
{
"code": null,
"e": 9943,
"s": 9930,
"text": "Mathematical"
},
{
"code": null,
"e": 9951,
"s": 9943,
"text": "Sorting"
},
{
"code": null,
"e": 9957,
"s": 9951,
"text": "Graph"
},
{
"code": null,
"e": 10055,
"s": 9957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10087,
"s": 10055,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10134,
"s": 10087,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 10159,
"s": 10134,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 10190,
"s": 10159,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 10248,
"s": 10190,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 10288,
"s": 10248,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 10326,
"s": 10288,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 10377,
"s": 10326,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 10428,
"s": 10377,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
}
]
|
Local Labels in C | 08 May, 2017
Everybody who has programmed in C programming language must be aware about “goto” and “labels” used in C to jump within a C function. GCC provides an extension to C called “local labels”.
Conventional Labels vs Local LabelsConventional labels in C have function scope. Where as local label can be scoped to a inner nested block. Therefore, conventional Labels cannot be declared more than once in a function and that is where local labels are used.
A label can appear more than once in function when the label is inside a macro and macro is expanded multiple times in a function. For example if a macro funcMacro() has definition which involves jump instructions (goto statement) within the block and funcMacro is used by a function foo() several times.
#define funcMacro(params ...)do { \ if (cond == true) \ goto x; \ <some code > \ \ x: \ <some code> \} while(0); \ Void foo(){ <some code> funcMacro(params ...); <some code > funcMacro(params...);}
In such a function foo() , the function macro will be expanded two times.This will result in having more than one definition of label ‘x’ in a function, which leads to confusion to the compiler and results in compilation error. In such cases local labels are useful. The above problem can be avoided by using local labels. A local label are declared as below:
__label__ label;
Local label declarations must come at the beginning of the block, before any ordinary declarations or statements.
Below is C example where a macro IS_STR_EMPTY() is expanded multiple times. Since local labels have block scope and every expansion of macro causes a new do while block, the program compiles and runs fine.
#include <stdio.h>#include <string.h> //Function macro using local labels#define IS_STR_EMPTY(str) \do { \ __label__ empty, not_empty, exit; \ if (strlen(str)) \ goto not_empty; \ else \ goto empty; \ \ not_empty: \ printf("string = %s\n", str); \ goto exit; \ empty: \ printf("string is empty\n"); \ exit: ; \} while(0); \ int main(){ char string[20] = {'\0'}; //Pass empty string to Macro function IS_STR_EMPTY(string); //Pass non-empty string to Macro function strcpy(string, "geeksForgeeks"); IS_STR_EMPTY(string); return 0;}
Output:
string is empty
string = geeksForgeeks
This article is contributed by Kashish Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
Memory Layout of C Programs
C Language Introduction | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 May, 2017"
},
{
"code": null,
"e": 216,
"s": 28,
"text": "Everybody who has programmed in C programming language must be aware about “goto” and “labels” used in C to jump within a C function. GCC provides an extension to C called “local labels”."
},
{
"code": null,
"e": 477,
"s": 216,
"text": "Conventional Labels vs Local LabelsConventional labels in C have function scope. Where as local label can be scoped to a inner nested block. Therefore, conventional Labels cannot be declared more than once in a function and that is where local labels are used."
},
{
"code": null,
"e": 782,
"s": 477,
"text": "A label can appear more than once in function when the label is inside a macro and macro is expanded multiple times in a function. For example if a macro funcMacro() has definition which involves jump instructions (goto statement) within the block and funcMacro is used by a function foo() several times."
},
{
"code": "#define funcMacro(params ...)do { \\ if (cond == true) \\ goto x; \\ <some code > \\ \\ x: \\ <some code> \\} while(0); \\ Void foo(){ <some code> funcMacro(params ...); <some code > funcMacro(params...);}",
"e": 1364,
"s": 782,
"text": null
},
{
"code": null,
"e": 1724,
"s": 1364,
"text": "In such a function foo() , the function macro will be expanded two times.This will result in having more than one definition of label ‘x’ in a function, which leads to confusion to the compiler and results in compilation error. In such cases local labels are useful. The above problem can be avoided by using local labels. A local label are declared as below:"
},
{
"code": null,
"e": 1747,
"s": 1724,
"text": " __label__ label; "
},
{
"code": null,
"e": 1861,
"s": 1747,
"text": "Local label declarations must come at the beginning of the block, before any ordinary declarations or statements."
},
{
"code": null,
"e": 2067,
"s": 1861,
"text": "Below is C example where a macro IS_STR_EMPTY() is expanded multiple times. Since local labels have block scope and every expansion of macro causes a new do while block, the program compiles and runs fine."
},
{
"code": "#include <stdio.h>#include <string.h> //Function macro using local labels#define IS_STR_EMPTY(str) \\do { \\ __label__ empty, not_empty, exit; \\ if (strlen(str)) \\ goto not_empty; \\ else \\ goto empty; \\ \\ not_empty: \\ printf(\"string = %s\\n\", str); \\ goto exit; \\ empty: \\ printf(\"string is empty\\n\"); \\ exit: ; \\} while(0); \\ int main(){ char string[20] = {'\\0'}; //Pass empty string to Macro function IS_STR_EMPTY(string); //Pass non-empty string to Macro function strcpy(string, \"geeksForgeeks\"); IS_STR_EMPTY(string); return 0;} ",
"e": 3397,
"s": 2067,
"text": null
},
{
"code": null,
"e": 3405,
"s": 3397,
"text": "Output:"
},
{
"code": null,
"e": 3445,
"s": 3405,
"text": "string is empty\nstring = geeksForgeeks"
},
{
"code": null,
"e": 3616,
"s": 3445,
"text": "This article is contributed by Kashish Bhatia. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 3627,
"s": 3616,
"text": "C Language"
},
{
"code": null,
"e": 3725,
"s": 3627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3742,
"s": 3725,
"text": "Substring in C++"
},
{
"code": null,
"e": 3777,
"s": 3742,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 3823,
"s": 3777,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3868,
"s": 3823,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3893,
"s": 3868,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3941,
"s": 3893,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 3969,
"s": 3941,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 3996,
"s": 3969,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 4024,
"s": 3996,
"text": "Memory Layout of C Programs"
}
]
|
NumberFormatException in Java with Examples | 18 Feb, 2022
The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. It is a subclass of IllegalArgumentException class. To handle this exception, try–catch block can be used.
While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt().
Usage of parseInt() method: As we already know there are two variants of this method namely as follows to get a better understanding
public static int parseInt(String s) throws NumberFormatException
This function parses the string argument as a signed decimal integer.
public static int parseInt(String s, int radix) throws NumberFormatException
This function parses the string argument as a signed integer in the radix specified by the second argument.
Return Type:
In simple words, both methods convert the string into its integer equivalent. The only difference being is that of the parameter radix. The first method can be considered as an equivalent of the second method with radix = 10 (Decimal).
Constructors:
public NumberFormatException(): Constructs a NumberFormatException with no detail message.public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’
public NumberFormatException(): Constructs a NumberFormatException with no detail message.
public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’
Common Reasons for NumberFormatException:
There are various issues related to improper string format for conversion in numeric value. A few of them are:
1. The input string is null
Integer.parseInt("null") ;
2. The input string is empty
Float.parseFloat(“”) ;
3. The input string with leading and/or trailing white spaces
Integer abc=new Integer(“ 432 “);
4. The input string with extra symbols
Float.parseFloat(4,236);
5. The input string with non-numeric data
Double.parseDouble(“ThirtyFour”);
6. The input string is alphanumeric
Integer.valueOf(“31.two”);
7. The input string might exceed the range of the datatype storing the parsed string
Integer.parseInt(“1326589741236”);
8. Data type mismatch between input string value and the type of the method which is being used for parsing
Integer.parseInt("13.26");
Example:
Java
// Java Program to illustrate NumberFormatException // Importing Scanner class to take// input number from the userimport java.util.Scanner; // Classpublic class GFG { // Main driver method public static void main(String[] arg) { // Declaring an variable which // holds the input number entered int number; // Creating a Scanner class object to // take input from keyboard // System.in -> Keyboard Scanner sc = new Scanner(System.in); // Condition check // If condition holds true, Continue loop until // valid integer is entered by user while (true) { // Display message System.out.println("Enter any valid Integer: "); // Try block to check if any exception occurs try { // Parsing user input to integer // using the parseInt() method number = Integer.parseInt(sc.next()); // Number can be valid or invalid // If number is valid, print and display // the message and number System.out.println("You entered: " + number); // Get off from this loop break; } // Catch block to handle NumberFormatException catch (NumberFormatException e) { // Print the message if exception occurred System.out.println( "NumberFormatException occurred"); } } }}
Output: The below output is for different numbers been entered by the user
Enter any valid Integer:
12,017
NumberFormatException occurred
Enter any valid Integer:
Sixty4
NumberFormatException occurred
Enter any valid Integer:
null
NumberFormatException occurred
Enter any valid Integer:
436.25
NumberFormatException occurred
Enter any valid Integer:
3.o
NumberFormatException occurred
Enter any valid Integer:
98562341789
NumberFormatException occurred
Enter any valid Integer:
1000
You entered: 1000
arorakashish0911
saurabh1990aror
khushboogoyal499
nikhatkhan11
Java-Exceptions
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 461,
"s": 54,
"text": "The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. It is a subclass of IllegalArgumentException class. To handle this exception, try–catch block can be used."
},
{
"code": null,
"e": 664,
"s": 461,
"text": "While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt()."
},
{
"code": null,
"e": 798,
"s": 664,
"text": "Usage of parseInt() method: As we already know there are two variants of this method namely as follows to get a better understanding "
},
{
"code": null,
"e": 935,
"s": 798,
"text": "public static int parseInt(String s) throws NumberFormatException\n\nThis function parses the string argument as a signed decimal integer."
},
{
"code": null,
"e": 1121,
"s": 935,
"text": "public static int parseInt(String s, int radix) throws NumberFormatException\n\nThis function parses the string argument as a signed integer in the radix specified by the second argument."
},
{
"code": null,
"e": 1134,
"s": 1121,
"text": "Return Type:"
},
{
"code": null,
"e": 1370,
"s": 1134,
"text": "In simple words, both methods convert the string into its integer equivalent. The only difference being is that of the parameter radix. The first method can be considered as an equivalent of the second method with radix = 10 (Decimal)."
},
{
"code": null,
"e": 1384,
"s": 1370,
"text": "Constructors:"
},
{
"code": null,
"e": 1581,
"s": 1384,
"text": "public NumberFormatException(): Constructs a NumberFormatException with no detail message.public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’"
},
{
"code": null,
"e": 1672,
"s": 1581,
"text": "public NumberFormatException(): Constructs a NumberFormatException with no detail message."
},
{
"code": null,
"e": 1779,
"s": 1672,
"text": "public NumberFormatException(String msg): Constructs a NumberFormatException with the detail message ‘msg’"
},
{
"code": null,
"e": 1821,
"s": 1779,
"text": "Common Reasons for NumberFormatException:"
},
{
"code": null,
"e": 1932,
"s": 1821,
"text": "There are various issues related to improper string format for conversion in numeric value. A few of them are:"
},
{
"code": null,
"e": 1960,
"s": 1932,
"text": "1. The input string is null"
},
{
"code": null,
"e": 1987,
"s": 1960,
"text": "Integer.parseInt(\"null\") ;"
},
{
"code": null,
"e": 2016,
"s": 1987,
"text": "2. The input string is empty"
},
{
"code": null,
"e": 2040,
"s": 2016,
"text": "Float.parseFloat(“”) ; "
},
{
"code": null,
"e": 2102,
"s": 2040,
"text": "3. The input string with leading and/or trailing white spaces"
},
{
"code": null,
"e": 2137,
"s": 2102,
"text": "Integer abc=new Integer(“ 432 “);"
},
{
"code": null,
"e": 2176,
"s": 2137,
"text": "4. The input string with extra symbols"
},
{
"code": null,
"e": 2201,
"s": 2176,
"text": "Float.parseFloat(4,236);"
},
{
"code": null,
"e": 2244,
"s": 2201,
"text": "5. The input string with non-numeric data"
},
{
"code": null,
"e": 2278,
"s": 2244,
"text": "Double.parseDouble(“ThirtyFour”);"
},
{
"code": null,
"e": 2314,
"s": 2278,
"text": "6. The input string is alphanumeric"
},
{
"code": null,
"e": 2341,
"s": 2314,
"text": "Integer.valueOf(“31.two”);"
},
{
"code": null,
"e": 2426,
"s": 2341,
"text": "7. The input string might exceed the range of the datatype storing the parsed string"
},
{
"code": null,
"e": 2462,
"s": 2426,
"text": "Integer.parseInt(“1326589741236”); "
},
{
"code": null,
"e": 2570,
"s": 2462,
"text": "8. Data type mismatch between input string value and the type of the method which is being used for parsing"
},
{
"code": null,
"e": 2597,
"s": 2570,
"text": "Integer.parseInt(\"13.26\");"
},
{
"code": null,
"e": 2606,
"s": 2597,
"text": "Example:"
},
{
"code": null,
"e": 2611,
"s": 2606,
"text": "Java"
},
{
"code": "// Java Program to illustrate NumberFormatException // Importing Scanner class to take// input number from the userimport java.util.Scanner; // Classpublic class GFG { // Main driver method public static void main(String[] arg) { // Declaring an variable which // holds the input number entered int number; // Creating a Scanner class object to // take input from keyboard // System.in -> Keyboard Scanner sc = new Scanner(System.in); // Condition check // If condition holds true, Continue loop until // valid integer is entered by user while (true) { // Display message System.out.println(\"Enter any valid Integer: \"); // Try block to check if any exception occurs try { // Parsing user input to integer // using the parseInt() method number = Integer.parseInt(sc.next()); // Number can be valid or invalid // If number is valid, print and display // the message and number System.out.println(\"You entered: \" + number); // Get off from this loop break; } // Catch block to handle NumberFormatException catch (NumberFormatException e) { // Print the message if exception occurred System.out.println( \"NumberFormatException occurred\"); } } }}",
"e": 4168,
"s": 2611,
"text": null
},
{
"code": null,
"e": 4245,
"s": 4168,
"text": " Output: The below output is for different numbers been entered by the user "
},
{
"code": null,
"e": 4671,
"s": 4245,
"text": "Enter any valid Integer:\n12,017\nNumberFormatException occurred\nEnter any valid Integer:\nSixty4\nNumberFormatException occurred\nEnter any valid Integer:\nnull\nNumberFormatException occurred\nEnter any valid Integer:\n436.25\nNumberFormatException occurred\nEnter any valid Integer:\n3.o\nNumberFormatException occurred\nEnter any valid Integer:\n98562341789\nNumberFormatException occurred\nEnter any valid Integer:\n1000\nYou entered: 1000"
},
{
"code": null,
"e": 4688,
"s": 4671,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4704,
"s": 4688,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4721,
"s": 4704,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 4734,
"s": 4721,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 4750,
"s": 4734,
"text": "Java-Exceptions"
},
{
"code": null,
"e": 4757,
"s": 4750,
"text": "Picked"
},
{
"code": null,
"e": 4762,
"s": 4757,
"text": "Java"
},
{
"code": null,
"e": 4767,
"s": 4762,
"text": "Java"
},
{
"code": null,
"e": 4865,
"s": 4767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4880,
"s": 4865,
"text": "Stream In Java"
},
{
"code": null,
"e": 4901,
"s": 4880,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4922,
"s": 4901,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4941,
"s": 4922,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4958,
"s": 4941,
"text": "Generics in Java"
},
{
"code": null,
"e": 4984,
"s": 4958,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5014,
"s": 4984,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5030,
"s": 5014,
"text": "Strings in Java"
},
{
"code": null,
"e": 5067,
"s": 5030,
"text": "Differences between JDK, JRE and JVM"
}
]
|
Python List pop() Method | Python list method pop() removes and returns last object or obj from the list.
Following is the syntax for pop() method −
list.pop(obj = list[-1])
obj − This is an optional parameter, index of the object to be removed from the list.
obj − This is an optional parameter, index of the object to be removed from the list.
This method returns the removed object from the list.
The following example shows the usage of pop() method.
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc'];
print "A List : ", aList.pop()
print "B List : ", aList.pop(2)
When we run above program, it produces following result −
A List : abc
B List : zara | [
{
"code": null,
"e": 2457,
"s": 2378,
"text": "Python list method pop() removes and returns last object or obj from the list."
},
{
"code": null,
"e": 2500,
"s": 2457,
"text": "Following is the syntax for pop() method −"
},
{
"code": null,
"e": 2526,
"s": 2500,
"text": "list.pop(obj = list[-1])\n"
},
{
"code": null,
"e": 2612,
"s": 2526,
"text": "obj − This is an optional parameter, index of the object to be removed from the list."
},
{
"code": null,
"e": 2698,
"s": 2612,
"text": "obj − This is an optional parameter, index of the object to be removed from the list."
},
{
"code": null,
"e": 2752,
"s": 2698,
"text": "This method returns the removed object from the list."
},
{
"code": null,
"e": 2807,
"s": 2752,
"text": "The following example shows the usage of pop() method."
},
{
"code": null,
"e": 2926,
"s": 2807,
"text": "#!/usr/bin/python\n\naList = [123, 'xyz', 'zara', 'abc'];\nprint \"A List : \", aList.pop()\nprint \"B List : \", aList.pop(2)"
},
{
"code": null,
"e": 2984,
"s": 2926,
"text": "When we run above program, it produces following result −"
}
]
|
Limited rows selection with given column in Pandas | Python | 24 Oct, 2019
Methods in Pandas like iloc[], iat[] are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods.
Example 1: Select two columns
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select three rows and two columns print(df.loc[1:3, ['Name', 'Qualification']])
Output:
Name Qualification
1 Princi MA
2 Gaurav MCA
3 Anuj Phd
Example 2: First filtering rows and selecting columns by label format and then Select all columns.
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # .loc DataFrame method # filtering rows and selecting columns by label format # df.loc[rows, columns] # row 1, all columns print(df.loc[0, :] )
Output:
Address Delhi
Age 27
Name Jai
Qualification Msc
Name: 0, dtype: object
Example 3: Select all or some columns, one to another using .iloc.
# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # iloc[row slicing, column slicing] print(df.iloc [0:2, 1:3] )
Output:
Age Name
0 27 Jai
1 24 Princi
pandas-dataframe-program
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2019"
},
{
"code": null,
"e": 240,
"s": 28,
"text": "Methods in Pandas like iloc[], iat[] are generally used to select the data from a given dataframe. In this article, we will learn how to select the limited rows with given columns with the help of these methods."
},
{
"code": null,
"e": 270,
"s": 240,
"text": "Example 1: Select two columns"
},
{
"code": "# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # select three rows and two columns print(df.loc[1:3, ['Name', 'Qualification']])",
"e": 720,
"s": 270,
"text": null
},
{
"code": null,
"e": 728,
"s": 720,
"text": "Output:"
},
{
"code": null,
"e": 825,
"s": 728,
"text": " Name Qualification\n1 Princi MA\n2 Gaurav MCA\n3 Anuj Phd\n"
},
{
"code": null,
"e": 924,
"s": 825,
"text": "Example 2: First filtering rows and selecting columns by label format and then Select all columns."
},
{
"code": "# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd'] } # Convert the dictionary into DataFrame df = pd.DataFrame(data) # .loc DataFrame method # filtering rows and selecting columns by label format # df.loc[rows, columns] # row 1, all columns print(df.loc[0, :] )",
"e": 1443,
"s": 924,
"text": null
},
{
"code": null,
"e": 1451,
"s": 1443,
"text": "Output:"
},
{
"code": null,
"e": 1568,
"s": 1451,
"text": "Address Delhi\nAge 27\nName Jai\nQualification Msc\nName: 0, dtype: object\n\n"
},
{
"code": null,
"e": 1635,
"s": 1568,
"text": "Example 3: Select all or some columns, one to another using .iloc."
},
{
"code": "# Import pandas package import pandas as pd # Define a dictionary containing employee data data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'], 'Age':[27, 24, 22, 32], 'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'], 'Qualification':['Msc', 'MA', 'MCA', 'Phd']} # Convert the dictionary into DataFrame df = pd.DataFrame(data) # iloc[row slicing, column slicing] print(df.iloc [0:2, 1:3] )",
"e": 2066,
"s": 1635,
"text": null
},
{
"code": null,
"e": 2074,
"s": 2066,
"text": "Output:"
},
{
"code": null,
"e": 2120,
"s": 2074,
"text": " Age Name\n0 27 Jai\n1 24 Princi\n"
},
{
"code": null,
"e": 2145,
"s": 2120,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2159,
"s": 2145,
"text": "Python-pandas"
},
{
"code": null,
"e": 2166,
"s": 2159,
"text": "Python"
},
{
"code": null,
"e": 2264,
"s": 2166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2296,
"s": 2264,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2323,
"s": 2296,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2344,
"s": 2323,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2375,
"s": 2344,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2431,
"s": 2375,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2454,
"s": 2431,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2496,
"s": 2454,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2538,
"s": 2496,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2577,
"s": 2538,
"text": "Python | datetime.timedelta() function"
}
]
|
Quorum Consistency in Cassandra | 24 Jun, 2022
In this article, we will discuss how quorum consistency is helpful in Cassandra and how we can calculate it, and also discuss how quorum consistency works.
What is Quorum Consistency?
Quorum consistency is consistency in Cassandra for high mechanism and to ensure that how many nodes will respond when we will define the read and write consistency in Cassandra. In Quorum consistency a majority of (n/2 +1) nodes of the replicas must respond. In Quorum, we check the majority of replicas (which simply means the number of replication factors). for example, if we have a replication factor of 3 in 2 data centers then how many their replicas will be there. so, there will be 6 and the majority is 4. (total_sum_replicas/2 + 1). Generally, we use local quorum in most cases in which we need 2 nodes from the LOCAL DC to succeed when if there are three replicas each in 3 data centers. Now, here we are just going to define the CQL query for the same. let’s have a look.
CREATE KEYSPACE cluster1
with replication = {'class' : 'NetworkTopologyStrategy',
'DC1': 3, 'DC2': 3, 'DC3': 3}
AND DURABLE_WRITES = false;
To verify the results used the following CQL query given below.
SELECT *
FROM system_schema.keyspaces;
Output: How QUORUM is calculated?
This is how we calculate quorum which simply means how many nodes will acknowledge.
Quorum = (sum_of_replication_factors / 2) + 1
Quorum is equal to the sum of replication factors division by 2 and added 1. It’s because to make it a whole number.
Quorum consistency: The sum of all the replication_factor settings for each data center is the sum_of_replication_factors.
Total_sum_of_replication_factor = DC1_RF + DC2_RF + DC3_RF+ ... +DC_RF
How does Quorum consistency work?
If there are three nodes that are in majority and they have to respond in Quorum consistency then in the below-given diagram acknowledgment is showing that there are three nodes responding and at the time writing data then committed nodes showing that we committed our data into three nodes.
In the above “Commit data” diagram if we are inserting data into a table and RF =3 that means data will be replicated on three nodes that are available. The commit operation is complete only after successfully replicating in at least 3 nodes. In the “Acknowledgement” diagram, it shows that if we are reading data and there are a total of 5 nodes while applying the quorum consistency we get (5/2 +1)=3 nodes. Hence we need acknowledgment from 3 nodes before responding to a read request.
srinitishkp0309
Apache
Technical Scripter 2019
DBMS
Technical Scripter
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "In this article, we will discuss how quorum consistency is helpful in Cassandra and how we can calculate it, and also discuss how quorum consistency works. "
},
{
"code": null,
"e": 214,
"s": 185,
"text": "What is Quorum Consistency? "
},
{
"code": null,
"e": 998,
"s": 214,
"text": "Quorum consistency is consistency in Cassandra for high mechanism and to ensure that how many nodes will respond when we will define the read and write consistency in Cassandra. In Quorum consistency a majority of (n/2 +1) nodes of the replicas must respond. In Quorum, we check the majority of replicas (which simply means the number of replication factors). for example, if we have a replication factor of 3 in 2 data centers then how many their replicas will be there. so, there will be 6 and the majority is 4. (total_sum_replicas/2 + 1). Generally, we use local quorum in most cases in which we need 2 nodes from the LOCAL DC to succeed when if there are three replicas each in 3 data centers. Now, here we are just going to define the CQL query for the same. let’s have a look."
},
{
"code": null,
"e": 1162,
"s": 998,
"text": "CREATE KEYSPACE cluster1\nwith replication = {'class' : 'NetworkTopologyStrategy', \n 'DC1': 3, 'DC2': 3, 'DC3': 3}\nAND DURABLE_WRITES = false; "
},
{
"code": null,
"e": 1226,
"s": 1162,
"text": "To verify the results used the following CQL query given below."
},
{
"code": null,
"e": 1267,
"s": 1226,
"text": "SELECT * \nFROM system_schema.keyspaces; "
},
{
"code": null,
"e": 1303,
"s": 1267,
"text": "Output: How QUORUM is calculated? "
},
{
"code": null,
"e": 1387,
"s": 1303,
"text": "This is how we calculate quorum which simply means how many nodes will acknowledge."
},
{
"code": null,
"e": 1434,
"s": 1387,
"text": "Quorum = (sum_of_replication_factors / 2) + 1 "
},
{
"code": null,
"e": 1552,
"s": 1434,
"text": "Quorum is equal to the sum of replication factors division by 2 and added 1. It’s because to make it a whole number. "
},
{
"code": null,
"e": 1675,
"s": 1552,
"text": "Quorum consistency: The sum of all the replication_factor settings for each data center is the sum_of_replication_factors."
},
{
"code": null,
"e": 1747,
"s": 1675,
"text": "Total_sum_of_replication_factor = DC1_RF + DC2_RF + DC3_RF+ ... +DC_RF "
},
{
"code": null,
"e": 1782,
"s": 1747,
"text": "How does Quorum consistency work? "
},
{
"code": null,
"e": 2074,
"s": 1782,
"text": "If there are three nodes that are in majority and they have to respond in Quorum consistency then in the below-given diagram acknowledgment is showing that there are three nodes responding and at the time writing data then committed nodes showing that we committed our data into three nodes."
},
{
"code": null,
"e": 2568,
"s": 2077,
"text": "In the above “Commit data” diagram if we are inserting data into a table and RF =3 that means data will be replicated on three nodes that are available. The commit operation is complete only after successfully replicating in at least 3 nodes. In the “Acknowledgement” diagram, it shows that if we are reading data and there are a total of 5 nodes while applying the quorum consistency we get (5/2 +1)=3 nodes. Hence we need acknowledgment from 3 nodes before responding to a read request."
},
{
"code": null,
"e": 2584,
"s": 2568,
"text": "srinitishkp0309"
},
{
"code": null,
"e": 2591,
"s": 2584,
"text": "Apache"
},
{
"code": null,
"e": 2615,
"s": 2591,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 2620,
"s": 2615,
"text": "DBMS"
},
{
"code": null,
"e": 2639,
"s": 2620,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2644,
"s": 2639,
"text": "DBMS"
}
]
|
unordered_map count() in C++ | 26 Sep, 2018
The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key.
Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the unordered_map with a given key or not.
Syntax:
size_type count(Key);
Parameters: This function accepts a single parameter key which is needed to be checked in the given unordered_map container.
Return Value: This function returns 1 if there exists a value in the map with the given key, otherwise it returns 0.
Below programs illustrate the unordered_map::count() function:
Program 1:
// C++ program to illustrate the // unordered_map::count() function #include<iostream>#include<unordered_map> using namespace std; int main(){ // unordered map unordered_map<int , string> umap; // Inserting elements into the map umap.insert(make_pair(1,"Welcome")); umap.insert(make_pair(2,"to")); umap.insert(make_pair(3,"GeeksforGeeks")); // Check if element with key 1 is present using // count() function if(umap.count(1)) { cout<<"Element Found"<<endl; } else { cout<<"Element Not Found"<<endl; } return 0;}
Element Found
Program 2:
// C++ program to illustrate the // unordered_map::count() function #include<iostream>#include<unordered_map> using namespace std; int main(){ // unordered map unordered_map<int , string> umap; // Inserting elements into the map umap.insert(make_pair(1,"Welcome")); umap.insert(make_pair(2,"to")); umap.insert(make_pair(3,"GeeksforGeeks")); // Try inserting element with // duplicate keys umap.insert(make_pair(3,"CS Portal")); // Print the count of values with key 3 // to check if duplicate values are stored // or not cout<<"Count of elements in map, mapped with key 3: " <<umap.count(3); return 0;}
Count of elements in map, mapped with key 3: 1
cpp-unordered_map-functions
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Sep, 2018"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "The unordered_map::count() is a builtin method in C++ which is used to count the number of elements present in an unordered_map with a given key."
},
{
"code": null,
"e": 389,
"s": 198,
"text": "Note: As unordered_map does not allow to store elements with duplicate keys, so the count() function basically checks if there exists an element in the unordered_map with a given key or not."
},
{
"code": null,
"e": 397,
"s": 389,
"text": "Syntax:"
},
{
"code": null,
"e": 420,
"s": 397,
"text": "size_type count(Key);\n"
},
{
"code": null,
"e": 545,
"s": 420,
"text": "Parameters: This function accepts a single parameter key which is needed to be checked in the given unordered_map container."
},
{
"code": null,
"e": 662,
"s": 545,
"text": "Return Value: This function returns 1 if there exists a value in the map with the given key, otherwise it returns 0."
},
{
"code": null,
"e": 725,
"s": 662,
"text": "Below programs illustrate the unordered_map::count() function:"
},
{
"code": null,
"e": 736,
"s": 725,
"text": "Program 1:"
},
{
"code": "// C++ program to illustrate the // unordered_map::count() function #include<iostream>#include<unordered_map> using namespace std; int main(){ // unordered map unordered_map<int , string> umap; // Inserting elements into the map umap.insert(make_pair(1,\"Welcome\")); umap.insert(make_pair(2,\"to\")); umap.insert(make_pair(3,\"GeeksforGeeks\")); // Check if element with key 1 is present using // count() function if(umap.count(1)) { cout<<\"Element Found\"<<endl; } else { cout<<\"Element Not Found\"<<endl; } return 0;}",
"e": 1334,
"s": 736,
"text": null
},
{
"code": null,
"e": 1349,
"s": 1334,
"text": "Element Found\n"
},
{
"code": null,
"e": 1360,
"s": 1349,
"text": "Program 2:"
},
{
"code": "// C++ program to illustrate the // unordered_map::count() function #include<iostream>#include<unordered_map> using namespace std; int main(){ // unordered map unordered_map<int , string> umap; // Inserting elements into the map umap.insert(make_pair(1,\"Welcome\")); umap.insert(make_pair(2,\"to\")); umap.insert(make_pair(3,\"GeeksforGeeks\")); // Try inserting element with // duplicate keys umap.insert(make_pair(3,\"CS Portal\")); // Print the count of values with key 3 // to check if duplicate values are stored // or not cout<<\"Count of elements in map, mapped with key 3: \" <<umap.count(3); return 0;}",
"e": 2044,
"s": 1360,
"text": null
},
{
"code": null,
"e": 2092,
"s": 2044,
"text": "Count of elements in map, mapped with key 3: 1\n"
},
{
"code": null,
"e": 2120,
"s": 2092,
"text": "cpp-unordered_map-functions"
},
{
"code": null,
"e": 2127,
"s": 2120,
"text": "Picked"
},
{
"code": null,
"e": 2131,
"s": 2127,
"text": "C++"
},
{
"code": null,
"e": 2135,
"s": 2131,
"text": "CPP"
}
]
|
What is the TouchableHighlight in react native ? | 28 Jun, 2021
TouchableHighlight is a component that is used to provide a wrapper to Views in order to make them respond correctly to touch-based input. On press down the TouchableHighlight component has its opacity decreased which allows the underlying View or other component’s style to get highlighted.
This component must have only one child component. If there is more than one child component then wrap them inside a View component. It is necessary that there be a child component of TouchableHighlight.
Syntax:
<TouchableHighlight>
// Child Component
</TouchableHighlight>
TouchableHighlight Props:
onPress: It is used to specify a function that is called when the touch is released.
disabled: If its value is true disable all interactions. The default is ‘false’.
style: It is used to specify the style of the TouchableHighlight component
activeOpacity: It is used to specify the opacity value of the wrapped View when the touch is active. It takes a value between 0 and 1 and the default value is 0.85.
underlayColor: It is used to specify the color of the underlay that is shown when the touch is active.
Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init TouchableHighlightDemo
Step 2: Now create a project by the following command.
expo init TouchableHighlightDemo
Step 3: Now go into your project folder i.e. TouchableHighlightDemocd TouchableHighlightDemo
Step 3: Now go into your project folder i.e. TouchableHighlightDemo
cd TouchableHighlightDemo
Project Structure: It will look like the following:
Example: Now let’s implement the TouchableHighlight. In the following example, we have a button, and when the user clicks on it, the TouchableHighlight functionality is demonstrated.
App.js
import React from 'react';import { StyleSheet, Text, View, TouchableHighlight, Alert } from 'react-native'; export default function App() { return ( <View style={styles.container}> <TouchableHighlight onPress={() => { Alert.alert("Touchable Highlight pressed."); }} style={styles.touchable} activeOpacity={0.5} underlayColor="#67c904" > <Text style={styles.text}>Click Me!</Text> </TouchableHighlight> </View> );} const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, touchable: { height: 50, width: 200, borderRadius: 10, alignItems: 'center', justifyContent: 'center', backgroundColor: '#4287f5' }, text: { color: "#fff" }});
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.
Reference: https://reactnative.dev/docs/touchablehighlight
Picked
React-Native
React-Native Component
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
ReactJS | Router
Axios in React: A Guide for Beginners | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 320,
"s": 28,
"text": "TouchableHighlight is a component that is used to provide a wrapper to Views in order to make them respond correctly to touch-based input. On press down the TouchableHighlight component has its opacity decreased which allows the underlying View or other component’s style to get highlighted."
},
{
"code": null,
"e": 524,
"s": 320,
"text": "This component must have only one child component. If there is more than one child component then wrap them inside a View component. It is necessary that there be a child component of TouchableHighlight."
},
{
"code": null,
"e": 532,
"s": 524,
"text": "Syntax:"
},
{
"code": null,
"e": 598,
"s": 532,
"text": "<TouchableHighlight>\n // Child Component\n</TouchableHighlight>"
},
{
"code": null,
"e": 624,
"s": 598,
"text": "TouchableHighlight Props:"
},
{
"code": null,
"e": 709,
"s": 624,
"text": "onPress: It is used to specify a function that is called when the touch is released."
},
{
"code": null,
"e": 790,
"s": 709,
"text": "disabled: If its value is true disable all interactions. The default is ‘false’."
},
{
"code": null,
"e": 865,
"s": 790,
"text": "style: It is used to specify the style of the TouchableHighlight component"
},
{
"code": null,
"e": 1030,
"s": 865,
"text": "activeOpacity: It is used to specify the opacity value of the wrapped View when the touch is active. It takes a value between 0 and 1 and the default value is 0.85."
},
{
"code": null,
"e": 1133,
"s": 1030,
"text": "underlayColor: It is used to specify the color of the underlay that is shown when the touch is active."
},
{
"code": null,
"e": 1176,
"s": 1135,
"text": "Now let’s start with the implementation:"
},
{
"code": null,
"e": 1273,
"s": 1176,
"text": "Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli"
},
{
"code": null,
"e": 1347,
"s": 1273,
"text": "Step 1: Open your terminal and install expo-cli by the following command."
},
{
"code": null,
"e": 1371,
"s": 1347,
"text": "npm install -g expo-cli"
},
{
"code": null,
"e": 1458,
"s": 1371,
"text": "Step 2: Now create a project by the following command.expo init TouchableHighlightDemo"
},
{
"code": null,
"e": 1513,
"s": 1458,
"text": "Step 2: Now create a project by the following command."
},
{
"code": null,
"e": 1546,
"s": 1513,
"text": "expo init TouchableHighlightDemo"
},
{
"code": null,
"e": 1639,
"s": 1546,
"text": "Step 3: Now go into your project folder i.e. TouchableHighlightDemocd TouchableHighlightDemo"
},
{
"code": null,
"e": 1707,
"s": 1639,
"text": "Step 3: Now go into your project folder i.e. TouchableHighlightDemo"
},
{
"code": null,
"e": 1733,
"s": 1707,
"text": "cd TouchableHighlightDemo"
},
{
"code": null,
"e": 1785,
"s": 1733,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 1968,
"s": 1785,
"text": "Example: Now let’s implement the TouchableHighlight. In the following example, we have a button, and when the user clicks on it, the TouchableHighlight functionality is demonstrated."
},
{
"code": null,
"e": 1975,
"s": 1968,
"text": "App.js"
},
{
"code": "import React from 'react';import { StyleSheet, Text, View, TouchableHighlight, Alert } from 'react-native'; export default function App() { return ( <View style={styles.container}> <TouchableHighlight onPress={() => { Alert.alert(\"Touchable Highlight pressed.\"); }} style={styles.touchable} activeOpacity={0.5} underlayColor=\"#67c904\" > <Text style={styles.text}>Click Me!</Text> </TouchableHighlight> </View> );} const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, touchable: { height: 50, width: 200, borderRadius: 10, alignItems: 'center', justifyContent: 'center', backgroundColor: '#4287f5' }, text: { color: \"#fff\" }});",
"e": 2823,
"s": 1975,
"text": null
},
{
"code": null,
"e": 2872,
"s": 2823,
"text": "Start the server by using the following command."
},
{
"code": null,
"e": 2888,
"s": 2872,
"text": "npm run android"
},
{
"code": null,
"e": 3056,
"s": 2888,
"text": "Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again."
},
{
"code": null,
"e": 3115,
"s": 3056,
"text": "Reference: https://reactnative.dev/docs/touchablehighlight"
},
{
"code": null,
"e": 3122,
"s": 3115,
"text": "Picked"
},
{
"code": null,
"e": 3135,
"s": 3122,
"text": "React-Native"
},
{
"code": null,
"e": 3158,
"s": 3135,
"text": "React-Native Component"
},
{
"code": null,
"e": 3175,
"s": 3158,
"text": "Web Technologies"
},
{
"code": null,
"e": 3273,
"s": 3175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3334,
"s": 3273,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3377,
"s": 3334,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3449,
"s": 3377,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3489,
"s": 3449,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3513,
"s": 3489,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3555,
"s": 3513,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3602,
"s": 3555,
"text": "How to float three div side by side using CSS?"
},
{
"code": null,
"e": 3643,
"s": 3602,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3660,
"s": 3643,
"text": "ReactJS | Router"
}
]
|
static Keyword in Java | 02 Dec, 2021
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class. The static keyword is used for a constant variable or a method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the following:
BlocksVariablesMethodsClasses
Blocks
Variables
Methods
Classes
Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. For example, in the below java program, we are accessing static method m1() without creating any object of the Test class.
Java
// Java program to demonstrate that a static member// can be accessed before instantiating a class class Test{ // static method static void m1() { System.out.println("from m1"); } public static void main(String[] args) { // calling m1 without creating // any object of class Test m1(); }}
from m1
If you need to do the computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating the use of static blocks.
Java
// Java program to demonstrate use of static blocks class Test{ // static variable static int a = 10; static int b; // static block static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String[] args) { System.out.println("from main"); System.out.println("Value of a : "+a); System.out.println("Value of b : "+b); }}
Static block initialized.
from main
Value of a : 10
Value of b : 40
For a detailed article on static blocks, see static blocks
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Important points for static variables:
We can create static variables at the class level only. See here
static block and static variables are executed in the order they are present in a program.
Below is the Java program to demonstrate that static block and static variables are executed in the order they are present in a program.
Java
// Java program to demonstrate execution// of static blocks and variables class Test{ // static variable static int a = m1(); // static block static { System.out.println("Inside static block"); } // static method static int m1() { System.out.println("from m1"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println("Value of a : "+a); System.out.println("from main"); }}
from m1
Inside static block
Value of a : 20
from main
When a method is declared with the static keyword, it is known as the static method. The most common example of a static method is the main( ) method. As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Below is the java program to demonstrate restrictions on static methods.
Java
// Java program to demonstrate restriction on static methods class Test{ // static variable static int a = 10; // instance variable int b = 20; // static method static void m1() { a = 20; System.out.println("from m1"); // Cannot make a static reference to the non-static field b b = 10; // compilation error // Cannot make a static reference to the // non-static method m2() from the type Test m2(); // compilation error // Cannot use super in a static context System.out.println(super.a); // compiler error } // instance method void m2() { System.out.println("from m2"); } public static void main(String[] args) { // main method }}
Output:
prog.java:18: error: non-static variable b cannot be referenced from a static context
b = 10; // compilation error
^
prog.java:22: error: non-static method m2() cannot be referenced from a static context
m2(); // compilation error
^
prog.java:25: error: non-static variable super cannot be referenced from a static context
System.out.println(super.a); // compiler error
^
prog.java:25: error: cannot find symbol
System.out.println(super.a); // compiler error
^
symbol: variable a
4 errors
Use the static variable for the property that is common to all objects. For example, in class Student, all students share the same college name. Use static methods for changing static variables.
Consider the following java program, that illustrates the use of static keywords with variables and methods.
Java
// A java program to demonstrate use of// static keyword with methods and variables // Student classclass Student { String name; int rollNo; // static variable static String cllgName; // static counter to set unique roll no static int counter = 0; public Student(String name) { this.name = name; this.rollNo = setRollNo(); } // getting unique rollNo // through static variable(counter) static int setRollNo() { counter++; return counter; } // static method static void setCllg(String name) { cllgName = name; } // instance method void getStudentInfo() { System.out.println("name : " + this.name); System.out.println("rollNo : " + this.rollNo); // accessing static variable System.out.println("cllgName : " + cllgName); }} // Driver classpublic class StaticDemo { public static void main(String[] args) { // calling static method // without instantiating Student class Student.setCllg("XYZ"); Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); s1.getStudentInfo(); s2.getStudentInfo(); }}
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ
A class can be made static only if it is a nested class. We cannot declare a top-level class with a static modifier but can declare nested classes as static. Such types of classes are called Nested static classes. Nested static class doesn’t need a reference of Outer class. In this case, a static class cannot access non-static members of the Outer class.
Note: For static nested class, see a static nested class in java
Implementation:
Java
// A java program to demonstrate use// of static keyword with Classes import java.io.*; public class GFG { private static String str = "GeeksforGeeks"; // Static class static class MyNestedClass { // non-static method public void disp(){ System.out.println(str); } } public static void main(String args[]) { GFG.MyNestedClass obj = new GFG.MyNestedClass(); obj.disp(); }}
GeeksforGeeks
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nishkarshgandhi
Java-keyword
Java-Library
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 478,
"s": 52,
"text": "The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class. The static keyword is used for a constant variable or a method that is the same for every instance of a class."
},
{
"code": null,
"e": 569,
"s": 478,
"text": "The static keyword is a non-access modifier in Java that is applicable for the following: "
},
{
"code": null,
"e": 599,
"s": 569,
"text": "BlocksVariablesMethodsClasses"
},
{
"code": null,
"e": 606,
"s": 599,
"text": "Blocks"
},
{
"code": null,
"e": 616,
"s": 606,
"text": "Variables"
},
{
"code": null,
"e": 624,
"s": 616,
"text": "Methods"
},
{
"code": null,
"e": 632,
"s": 624,
"text": "Classes"
},
{
"code": null,
"e": 754,
"s": 632,
"text": "Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. "
},
{
"code": null,
"e": 1013,
"s": 754,
"text": "When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. For example, in the below java program, we are accessing static method m1() without creating any object of the Test class. "
},
{
"code": null,
"e": 1018,
"s": 1013,
"text": "Java"
},
{
"code": "// Java program to demonstrate that a static member// can be accessed before instantiating a class class Test{ // static method static void m1() { System.out.println(\"from m1\"); } public static void main(String[] args) { // calling m1 without creating // any object of class Test m1(); }}",
"e": 1366,
"s": 1018,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "from m1"
},
{
"code": null,
"e": 1551,
"s": 1374,
"text": "If you need to do the computation in order to initialize your static variables, you can declare a static block that gets executed exactly once, when the class is first loaded. "
},
{
"code": null,
"e": 1628,
"s": 1551,
"text": "Consider the following java program demonstrating the use of static blocks. "
},
{
"code": null,
"e": 1633,
"s": 1628,
"text": "Java"
},
{
"code": "// Java program to demonstrate use of static blocks class Test{ // static variable static int a = 10; static int b; // static block static { System.out.println(\"Static block initialized.\"); b = a * 4; } public static void main(String[] args) { System.out.println(\"from main\"); System.out.println(\"Value of a : \"+a); System.out.println(\"Value of b : \"+b); }}",
"e": 2059,
"s": 1633,
"text": null
},
{
"code": null,
"e": 2127,
"s": 2059,
"text": "Static block initialized.\nfrom main\nValue of a : 10\nValue of b : 40"
},
{
"code": null,
"e": 2186,
"s": 2127,
"text": "For a detailed article on static blocks, see static blocks"
},
{
"code": null,
"e": 2432,
"s": 2186,
"text": "When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable."
},
{
"code": null,
"e": 2471,
"s": 2432,
"text": "Important points for static variables:"
},
{
"code": null,
"e": 2536,
"s": 2471,
"text": "We can create static variables at the class level only. See here"
},
{
"code": null,
"e": 2627,
"s": 2536,
"text": "static block and static variables are executed in the order they are present in a program."
},
{
"code": null,
"e": 2765,
"s": 2627,
"text": "Below is the Java program to demonstrate that static block and static variables are executed in the order they are present in a program. "
},
{
"code": null,
"e": 2770,
"s": 2765,
"text": "Java"
},
{
"code": "// Java program to demonstrate execution// of static blocks and variables class Test{ // static variable static int a = m1(); // static block static { System.out.println(\"Inside static block\"); } // static method static int m1() { System.out.println(\"from m1\"); return 20; } // static method(main !!) public static void main(String[] args) { System.out.println(\"Value of a : \"+a); System.out.println(\"from main\"); }}",
"e": 3275,
"s": 2770,
"text": null
},
{
"code": null,
"e": 3329,
"s": 3275,
"text": "from m1\nInside static block\nValue of a : 20\nfrom main"
},
{
"code": null,
"e": 3671,
"s": 3329,
"text": "When a method is declared with the static keyword, it is known as the static method. The most common example of a static method is the main( ) method. As discussed above, Any static member can be accessed before any objects of its class are created, and without reference to any object. Methods declared as static have several restrictions: "
},
{
"code": null,
"e": 3721,
"s": 3671,
"text": "They can only directly call other static methods."
},
{
"code": null,
"e": 3764,
"s": 3721,
"text": "They can only directly access static data."
},
{
"code": null,
"e": 3811,
"s": 3764,
"text": "They cannot refer to this or super in any way."
},
{
"code": null,
"e": 3884,
"s": 3811,
"text": "Below is the java program to demonstrate restrictions on static methods."
},
{
"code": null,
"e": 3889,
"s": 3884,
"text": "Java"
},
{
"code": "// Java program to demonstrate restriction on static methods class Test{ // static variable static int a = 10; // instance variable int b = 20; // static method static void m1() { a = 20; System.out.println(\"from m1\"); // Cannot make a static reference to the non-static field b b = 10; // compilation error // Cannot make a static reference to the // non-static method m2() from the type Test m2(); // compilation error // Cannot use super in a static context System.out.println(super.a); // compiler error } // instance method void m2() { System.out.println(\"from m2\"); } public static void main(String[] args) { // main method }}",
"e": 4744,
"s": 3889,
"text": null
},
{
"code": null,
"e": 4752,
"s": 4744,
"text": "Output:"
},
{
"code": null,
"e": 5361,
"s": 4752,
"text": "prog.java:18: error: non-static variable b cannot be referenced from a static context\n b = 10; // compilation error\n ^\nprog.java:22: error: non-static method m2() cannot be referenced from a static context\n m2(); // compilation error\n ^\nprog.java:25: error: non-static variable super cannot be referenced from a static context\n System.out.println(super.a); // compiler error \n ^\nprog.java:25: error: cannot find symbol\n System.out.println(super.a); // compiler error \n ^\n symbol: variable a\n4 errors"
},
{
"code": null,
"e": 5556,
"s": 5361,
"text": "Use the static variable for the property that is common to all objects. For example, in class Student, all students share the same college name. Use static methods for changing static variables."
},
{
"code": null,
"e": 5665,
"s": 5556,
"text": "Consider the following java program, that illustrates the use of static keywords with variables and methods."
},
{
"code": null,
"e": 5670,
"s": 5665,
"text": "Java"
},
{
"code": "// A java program to demonstrate use of// static keyword with methods and variables // Student classclass Student { String name; int rollNo; // static variable static String cllgName; // static counter to set unique roll no static int counter = 0; public Student(String name) { this.name = name; this.rollNo = setRollNo(); } // getting unique rollNo // through static variable(counter) static int setRollNo() { counter++; return counter; } // static method static void setCllg(String name) { cllgName = name; } // instance method void getStudentInfo() { System.out.println(\"name : \" + this.name); System.out.println(\"rollNo : \" + this.rollNo); // accessing static variable System.out.println(\"cllgName : \" + cllgName); }} // Driver classpublic class StaticDemo { public static void main(String[] args) { // calling static method // without instantiating Student class Student.setCllg(\"XYZ\"); Student s1 = new Student(\"Alice\"); Student s2 = new Student(\"Bob\"); s1.getStudentInfo(); s2.getStudentInfo(); }}",
"e": 6871,
"s": 5670,
"text": null
},
{
"code": null,
"e": 6947,
"s": 6871,
"text": "name : Alice\nrollNo : 1\ncllgName : XYZ\nname : Bob\nrollNo : 2\ncllgName : XYZ"
},
{
"code": null,
"e": 7305,
"s": 6947,
"text": "A class can be made static only if it is a nested class. We cannot declare a top-level class with a static modifier but can declare nested classes as static. Such types of classes are called Nested static classes. Nested static class doesn’t need a reference of Outer class. In this case, a static class cannot access non-static members of the Outer class. "
},
{
"code": null,
"e": 7370,
"s": 7305,
"text": "Note: For static nested class, see a static nested class in java"
},
{
"code": null,
"e": 7386,
"s": 7370,
"text": "Implementation:"
},
{
"code": null,
"e": 7391,
"s": 7386,
"text": "Java"
},
{
"code": "// A java program to demonstrate use// of static keyword with Classes import java.io.*; public class GFG { private static String str = \"GeeksforGeeks\"; // Static class static class MyNestedClass { // non-static method public void disp(){ System.out.println(str); } } public static void main(String args[]) { GFG.MyNestedClass obj = new GFG.MyNestedClass(); obj.disp(); }}",
"e": 7859,
"s": 7391,
"text": null
},
{
"code": null,
"e": 7873,
"s": 7859,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 8296,
"s": 7873,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8312,
"s": 8296,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 8325,
"s": 8312,
"text": "Java-keyword"
},
{
"code": null,
"e": 8338,
"s": 8325,
"text": "Java-Library"
},
{
"code": null,
"e": 8343,
"s": 8338,
"text": "Java"
},
{
"code": null,
"e": 8348,
"s": 8343,
"text": "Java"
}
]
|
Remove Duplicate rows in R using Dplyr | 21 Jul, 2021
In this article, we are going to remove duplicate rows in R programming language using Dplyr package.
This function is used to remove the duplicate rows in the dataframe and get the unique data
Syntax:
distinct(dataframe)
We can also remove duplicate rows based on the multiple columns/variables in the dataframe
Syntax:
distinct(dataframe,column1,column2,.,column n)
Dataset in use:
Example 1: R program to remove duplicate rows from the dataframe
R
# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rowsprint(distinct(data1))
Output:
Example 2: Remove duplicate rows based on single column
R
# load the packagelibrary(dplyr) # create dataframe with three columns # named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows based on name # columnprint(distinct(data1,name))
Output:
Example 3: Remove duplicate rows based on multiple columns
R
# load the packagelibrary(dplyr) # create dataframe with three columns # named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows based on # name and address columnsprint(distinct(data1,address,name))
Output:
duplicated() function will return the duplicated rows and !duplicated() function will return the unique rows.
Syntax:
dataframe[!duplicated(dataframe$column_name), ]
Here, dataframe is the input dataframe and column_name is the column in dataframe, based on that column the duplicate data is removed.
Example: R program to remove duplicate data based on particular column
R
# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows using duplicated()# function based on name columnprint(data1[!duplicated(data1$name), ] )print("=====================") # remove duplicate rows using duplicated()# function based on id columnprint(data1[!duplicated(data1$id), ] )print("=====================") # remove duplicate rows using duplicated()# function based on address columnprint(data1[!duplicated(data1$address), ] )print("=====================")
Output:
unique() function is used to remove duplicate rows by returning the unique data
Syntax:
unique(dataframe)
To get unique data from column pass the name of the column along with the name of the dataframe,
Syntax:
unique(dataframe$column_name)
Where, dataframe is the input dataframe and column_name is the column in the dataframe.
Example 1: R program to remove duplicates using unique() function
R
# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # get unique data from the dataframeprint(unique(data1))
Output:
Example 2: R program to remove duplicate in particular column
R
# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # get unique data from the dataframe# in id columnprint(unique(data1$id)) # get unique data from the dataframe # in name columnprint(unique(data1$name)) # get unique data from the dataframe # in address columnprint(unique(data1$address))
Output:
Picked
R Dplyr
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": "\n21 Jul, 2021"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "In this article, we are going to remove duplicate rows in R programming language using Dplyr package."
},
{
"code": null,
"e": 222,
"s": 130,
"text": "This function is used to remove the duplicate rows in the dataframe and get the unique data"
},
{
"code": null,
"e": 230,
"s": 222,
"text": "Syntax:"
},
{
"code": null,
"e": 250,
"s": 230,
"text": "distinct(dataframe)"
},
{
"code": null,
"e": 341,
"s": 250,
"text": "We can also remove duplicate rows based on the multiple columns/variables in the dataframe"
},
{
"code": null,
"e": 349,
"s": 341,
"text": "Syntax:"
},
{
"code": null,
"e": 396,
"s": 349,
"text": "distinct(dataframe,column1,column2,.,column n)"
},
{
"code": null,
"e": 412,
"s": 396,
"text": "Dataset in use:"
},
{
"code": null,
"e": 477,
"s": 412,
"text": "Example 1: R program to remove duplicate rows from the dataframe"
},
{
"code": null,
"e": 479,
"s": 477,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rowsprint(distinct(data1))",
"e": 1063,
"s": 479,
"text": null
},
{
"code": null,
"e": 1071,
"s": 1063,
"text": "Output:"
},
{
"code": null,
"e": 1127,
"s": 1071,
"text": "Example 2: Remove duplicate rows based on single column"
},
{
"code": null,
"e": 1129,
"s": 1127,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns # named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows based on name # columnprint(distinct(data1,name))",
"e": 1742,
"s": 1129,
"text": null
},
{
"code": null,
"e": 1750,
"s": 1742,
"text": "Output:"
},
{
"code": null,
"e": 1809,
"s": 1750,
"text": "Example 3: Remove duplicate rows based on multiple columns"
},
{
"code": null,
"e": 1811,
"s": 1809,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns # named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows based on # name and address columnsprint(distinct(data1,address,name))",
"e": 2445,
"s": 1811,
"text": null
},
{
"code": null,
"e": 2453,
"s": 2445,
"text": "Output:"
},
{
"code": null,
"e": 2563,
"s": 2453,
"text": "duplicated() function will return the duplicated rows and !duplicated() function will return the unique rows."
},
{
"code": null,
"e": 2571,
"s": 2563,
"text": "Syntax:"
},
{
"code": null,
"e": 2619,
"s": 2571,
"text": "dataframe[!duplicated(dataframe$column_name), ]"
},
{
"code": null,
"e": 2754,
"s": 2619,
"text": "Here, dataframe is the input dataframe and column_name is the column in dataframe, based on that column the duplicate data is removed."
},
{
"code": null,
"e": 2825,
"s": 2754,
"text": "Example: R program to remove duplicate data based on particular column"
},
{
"code": null,
"e": 2827,
"s": 2825,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove duplicate rows using duplicated()# function based on name columnprint(data1[!duplicated(data1$name), ] )print(\"=====================\") # remove duplicate rows using duplicated()# function based on id columnprint(data1[!duplicated(data1$id), ] )print(\"=====================\") # remove duplicate rows using duplicated()# function based on address columnprint(data1[!duplicated(data1$address), ] )print(\"=====================\")",
"e": 3801,
"s": 2827,
"text": null
},
{
"code": null,
"e": 3809,
"s": 3801,
"text": "Output:"
},
{
"code": null,
"e": 3889,
"s": 3809,
"text": "unique() function is used to remove duplicate rows by returning the unique data"
},
{
"code": null,
"e": 3897,
"s": 3889,
"text": "Syntax:"
},
{
"code": null,
"e": 3915,
"s": 3897,
"text": "unique(dataframe)"
},
{
"code": null,
"e": 4012,
"s": 3915,
"text": "To get unique data from column pass the name of the column along with the name of the dataframe,"
},
{
"code": null,
"e": 4020,
"s": 4012,
"text": "Syntax:"
},
{
"code": null,
"e": 4050,
"s": 4020,
"text": "unique(dataframe$column_name)"
},
{
"code": null,
"e": 4138,
"s": 4050,
"text": "Where, dataframe is the input dataframe and column_name is the column in the dataframe."
},
{
"code": null,
"e": 4204,
"s": 4138,
"text": "Example 1: R program to remove duplicates using unique() function"
},
{
"code": null,
"e": 4206,
"s": 4204,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # get unique data from the dataframeprint(unique(data1))",
"e": 4801,
"s": 4206,
"text": null
},
{
"code": null,
"e": 4809,
"s": 4801,
"text": "Output:"
},
{
"code": null,
"e": 4871,
"s": 4809,
"text": "Example 2: R program to remove duplicate in particular column"
},
{
"code": null,
"e": 4873,
"s": 4871,
"text": "R"
},
{
"code": "# load the packagelibrary(dplyr) # create dataframe with three columns# named id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # get unique data from the dataframe# in id columnprint(unique(data1$id)) # get unique data from the dataframe # in name columnprint(unique(data1$name)) # get unique data from the dataframe # in address columnprint(unique(data1$address))",
"e": 5652,
"s": 4873,
"text": null
},
{
"code": null,
"e": 5660,
"s": 5652,
"text": "Output:"
},
{
"code": null,
"e": 5667,
"s": 5660,
"text": "Picked"
},
{
"code": null,
"e": 5675,
"s": 5667,
"text": "R Dplyr"
},
{
"code": null,
"e": 5686,
"s": 5675,
"text": "R Language"
}
]
|
Decimal.Compare() Method in C# | 29 Jan, 2019
This method is used to compare two specified Decimal values.
Syntax: public static int Compare (decimal a1, decimal a2);
Parameters:a1:This parameter specifies the first value to compare.a2:This parameter specifies the second value to compare.
Return Value: It returns a signed number indicating the relative values of a1 & a2.
If the value is less than zero, it means a1 is less than a2.
If the value is greater than zero, it means a1 is greater than a2.
If the value is zero, it means a1 is equal to a2.
Below programs illustrate the use of Decimal.Compare(Decimal, Decimal) Method
Example 1: When a1 is greater than a2.
// C# program to demonstrate the// Decimal.Compare(Decimal, // Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 4; Decimal a2 = 3; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine("The compare value is : {0}", value); }}
The compare value is : 1
Example 2: When a1 is less than a2.
// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 1; Decimal a2 = 9; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine("The compare value is : {0}", value); }}
The compare value is : -1
Example 3: When a1 is equals to a2.
// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 5; Decimal a2 = 5; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine("The compare value is : {0}", value); }}
The compare value is : 0
CSharp-Decimal-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jan, 2019"
},
{
"code": null,
"e": 89,
"s": 28,
"text": "This method is used to compare two specified Decimal values."
},
{
"code": null,
"e": 149,
"s": 89,
"text": "Syntax: public static int Compare (decimal a1, decimal a2);"
},
{
"code": null,
"e": 272,
"s": 149,
"text": "Parameters:a1:This parameter specifies the first value to compare.a2:This parameter specifies the second value to compare."
},
{
"code": null,
"e": 356,
"s": 272,
"text": "Return Value: It returns a signed number indicating the relative values of a1 & a2."
},
{
"code": null,
"e": 417,
"s": 356,
"text": "If the value is less than zero, it means a1 is less than a2."
},
{
"code": null,
"e": 484,
"s": 417,
"text": "If the value is greater than zero, it means a1 is greater than a2."
},
{
"code": null,
"e": 534,
"s": 484,
"text": "If the value is zero, it means a1 is equal to a2."
},
{
"code": null,
"e": 612,
"s": 534,
"text": "Below programs illustrate the use of Decimal.Compare(Decimal, Decimal) Method"
},
{
"code": null,
"e": 651,
"s": 612,
"text": "Example 1: When a1 is greater than a2."
},
{
"code": "// C# program to demonstrate the// Decimal.Compare(Decimal, // Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 4; Decimal a2 = 3; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine(\"The compare value is : {0}\", value); }}",
"e": 1207,
"s": 651,
"text": null
},
{
"code": null,
"e": 1233,
"s": 1207,
"text": "The compare value is : 1\n"
},
{
"code": null,
"e": 1269,
"s": 1233,
"text": "Example 2: When a1 is less than a2."
},
{
"code": "// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 1; Decimal a2 = 9; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine(\"The compare value is : {0}\", value); }}",
"e": 1824,
"s": 1269,
"text": null
},
{
"code": null,
"e": 1851,
"s": 1824,
"text": "The compare value is : -1\n"
},
{
"code": null,
"e": 1887,
"s": 1851,
"text": "Example 3: When a1 is equals to a2."
},
{
"code": "// C# program to demonstrate the// Decimal.Compare(Decimal,// Decimal) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring the decimal variables Decimal a1 = 5; Decimal a2 = 5; // comparing the two Decimal value // using Compare() method; Decimal value = Decimal.Compare(a1, a2); // Display the compare value Console.WriteLine(\"The compare value is : {0}\", value); }}",
"e": 2442,
"s": 1887,
"text": null
},
{
"code": null,
"e": 2468,
"s": 2442,
"text": "The compare value is : 0\n"
},
{
"code": null,
"e": 2490,
"s": 2468,
"text": "CSharp-Decimal-Struct"
},
{
"code": null,
"e": 2504,
"s": 2490,
"text": "CSharp-method"
},
{
"code": null,
"e": 2507,
"s": 2504,
"text": "C#"
},
{
"code": null,
"e": 2605,
"s": 2507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2633,
"s": 2605,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2676,
"s": 2633,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2707,
"s": 2676,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2722,
"s": 2707,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2771,
"s": 2722,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2787,
"s": 2771,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2810,
"s": 2787,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 2850,
"s": 2810,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 2872,
"s": 2850,
"text": "C# | Class and Object"
}
]
|
Python program to check if string is empty or not | 30 Sep, 2021
Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and solution to it. Let’s see different methods of checking if string is empty or not.Method #1 : Using len() Using len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as empty string even its non zero.
Python3
# Python3 code to demonstrate# to check if string is empty# using len() # initializing stringtest_str1 = ""test_str2 = " " # checking if string is emptyprint ("The zero length string without spaces is empty ? : ", end = "")if(len(test_str1) == 0): print ("Yes")else : print ("No") # prints Noprint ("The zero length string with just spaces is empty ? : ", end = "")if(len(test_str2) == 0): print ("Yes")else : print ("No")
Output :
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No
Method #2 : Using not not operator can also perform the task similar to len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Python3
# Python3 code to demonstrate# to check if string is empty# using not # initializing stringtest_str1 = ""test_str2 = " " # checking if string is emptyprint ("The zero length string without spaces is empty ? : ", end = "")if(not test_str1): print ("Yes")else : print ("No") # prints Noprint ("The zero length string with just spaces is empty ? : ", end = "")if(not test_str2): print ("Yes")else : print ("No")
Output :
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No
Method #3 : Using not + str.strip() The problem of empty + zero length string can be possibly be removed by using strip(), strip() returns true if it encounters the spaces, hence checking for it can solve the problem of checking for a purely empty string.
Python3
# Python3 code to demonstrate# to check if string is empty# using not + strip() # initializing stringtest_str1 = ""test_str2 = " " # checking if string is emptyprint ("The zero length string without spaces is empty ? : ", end = "")if(not (test_str1 and test_str1.strip())): print ("Yes")else : print ("No") # prints Yesprint ("The zero length string with just spaces is empty ? : ", end = "")if(not(test_str2 and test_str2.strip())): print ("Yes")else : print ("No")
Output :
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes
Method #4 : Using not + str.isspace Works in similar way as the above method, and checks for spaces in the string. This method is more efficient because, strip() requires to perform the strip operation also which takes computation loads, if no. of spaces are of good number.
Python3
# Python 3 code to demonstrate# to check if string is empty# using not + isspace() # initializing stringtest_str1 = ""test_str2 = " " # checking if string is emptyprint ("The zero length string without spaces is empty ? : ", end = "")if(not (test_str1 and not test_str1.isspace())): print ("Yes")else : print ("No") # prints Yesprint ("The zero length string with just spaces is empty ? : ", end = "")if(not (test_str2 and not test_str2.isspace())): print ("Yes")else : print ("No")
Output :
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes
anikaseth98
Python string-programs
python-string
Python
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, 2021"
},
{
"code": null,
"e": 573,
"s": 28,
"text": "Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and solution to it. Let’s see different methods of checking if string is empty or not.Method #1 : Using len() Using len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as empty string even its non zero. "
},
{
"code": null,
"e": 581,
"s": 573,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to check if string is empty# using len() # initializing stringtest_str1 = \"\"test_str2 = \" \" # checking if string is emptyprint (\"The zero length string without spaces is empty ? : \", end = \"\")if(len(test_str1) == 0): print (\"Yes\")else : print (\"No\") # prints Noprint (\"The zero length string with just spaces is empty ? : \", end = \"\")if(len(test_str2) == 0): print (\"Yes\")else : print (\"No\")",
"e": 1017,
"s": 581,
"text": null
},
{
"code": null,
"e": 1028,
"s": 1017,
"text": "Output : "
},
{
"code": null,
"e": 1139,
"s": 1028,
"text": "The zero length string without spaces is empty ? : Yes\nThe zero length string with just spaces is empty ? : No"
},
{
"code": null,
"e": 1377,
"s": 1139,
"text": " Method #2 : Using not not operator can also perform the task similar to len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true. "
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to check if string is empty# using not # initializing stringtest_str1 = \"\"test_str2 = \" \" # checking if string is emptyprint (\"The zero length string without spaces is empty ? : \", end = \"\")if(not test_str1): print (\"Yes\")else : print (\"No\") # prints Noprint (\"The zero length string with just spaces is empty ? : \", end = \"\")if(not test_str2): print (\"Yes\")else : print (\"No\")",
"e": 1807,
"s": 1385,
"text": null
},
{
"code": null,
"e": 1818,
"s": 1807,
"text": "Output : "
},
{
"code": null,
"e": 1929,
"s": 1818,
"text": "The zero length string without spaces is empty ? : Yes\nThe zero length string with just spaces is empty ? : No"
},
{
"code": null,
"e": 2189,
"s": 1929,
"text": " Method #3 : Using not + str.strip() The problem of empty + zero length string can be possibly be removed by using strip(), strip() returns true if it encounters the spaces, hence checking for it can solve the problem of checking for a purely empty string. "
},
{
"code": null,
"e": 2197,
"s": 2189,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to check if string is empty# using not + strip() # initializing stringtest_str1 = \"\"test_str2 = \" \" # checking if string is emptyprint (\"The zero length string without spaces is empty ? : \", end = \"\")if(not (test_str1 and test_str1.strip())): print (\"Yes\")else : print (\"No\") # prints Yesprint (\"The zero length string with just spaces is empty ? : \", end = \"\")if(not(test_str2 and test_str2.strip())): print (\"Yes\")else : print (\"No\")",
"e": 2677,
"s": 2197,
"text": null
},
{
"code": null,
"e": 2688,
"s": 2677,
"text": "Output : "
},
{
"code": null,
"e": 2800,
"s": 2688,
"text": "The zero length string without spaces is empty ? : Yes\nThe zero length string with just spaces is empty ? : Yes"
},
{
"code": null,
"e": 3078,
"s": 2800,
"text": " Method #4 : Using not + str.isspace Works in similar way as the above method, and checks for spaces in the string. This method is more efficient because, strip() requires to perform the strip operation also which takes computation loads, if no. of spaces are of good number. "
},
{
"code": null,
"e": 3086,
"s": 3078,
"text": "Python3"
},
{
"code": "# Python 3 code to demonstrate# to check if string is empty# using not + isspace() # initializing stringtest_str1 = \"\"test_str2 = \" \" # checking if string is emptyprint (\"The zero length string without spaces is empty ? : \", end = \"\")if(not (test_str1 and not test_str1.isspace())): print (\"Yes\")else : print (\"No\") # prints Yesprint (\"The zero length string with just spaces is empty ? : \", end = \"\")if(not (test_str2 and not test_str2.isspace())): print (\"Yes\")else : print (\"No\")",
"e": 3582,
"s": 3086,
"text": null
},
{
"code": null,
"e": 3593,
"s": 3582,
"text": "Output : "
},
{
"code": null,
"e": 3705,
"s": 3593,
"text": "The zero length string without spaces is empty ? : Yes\nThe zero length string with just spaces is empty ? : Yes"
},
{
"code": null,
"e": 3719,
"s": 3707,
"text": "anikaseth98"
},
{
"code": null,
"e": 3742,
"s": 3719,
"text": "Python string-programs"
},
{
"code": null,
"e": 3756,
"s": 3742,
"text": "python-string"
},
{
"code": null,
"e": 3763,
"s": 3756,
"text": "Python"
}
]
|
p5.js | fullscreen() function | 16 Apr, 2019
The fullscreen() function in p5.js is used to get the current fullscreen state of the user’s browser window. If an argument is given, sets the sketch to fullscreen or not based on the value of the argument. If no argument is given, returns the current fullscreen state. Note that due to browser restrictions this can only be called on user input.
Syntax:
fullscreen()
Parameters: The function does not accept any parameters.
Below program illustrates the fullscreen() function in p5.js:
Example:
function setup() { // Set the background color background(200);}function mousePressed() { // Set the value of fullscreen // into the variable let fs = fullscreen(); // Call to fullscreen function fullscreen(!fs); }
Output:Before Clicking the screen:
After Clicking the screen:
Reference: https://p5js.org/reference/#/p5/fullscreen
JavaScript-p5.js
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": "\n16 Apr, 2019"
},
{
"code": null,
"e": 375,
"s": 28,
"text": "The fullscreen() function in p5.js is used to get the current fullscreen state of the user’s browser window. If an argument is given, sets the sketch to fullscreen or not based on the value of the argument. If no argument is given, returns the current fullscreen state. Note that due to browser restrictions this can only be called on user input."
},
{
"code": null,
"e": 383,
"s": 375,
"text": "Syntax:"
},
{
"code": null,
"e": 396,
"s": 383,
"text": "fullscreen()"
},
{
"code": null,
"e": 453,
"s": 396,
"text": "Parameters: The function does not accept any parameters."
},
{
"code": null,
"e": 515,
"s": 453,
"text": "Below program illustrates the fullscreen() function in p5.js:"
},
{
"code": null,
"e": 524,
"s": 515,
"text": "Example:"
},
{
"code": "function setup() { // Set the background color background(200);}function mousePressed() { // Set the value of fullscreen // into the variable let fs = fullscreen(); // Call to fullscreen function fullscreen(!fs); }",
"e": 778,
"s": 524,
"text": null
},
{
"code": null,
"e": 813,
"s": 778,
"text": "Output:Before Clicking the screen:"
},
{
"code": null,
"e": 840,
"s": 813,
"text": "After Clicking the screen:"
},
{
"code": null,
"e": 894,
"s": 840,
"text": "Reference: https://p5js.org/reference/#/p5/fullscreen"
},
{
"code": null,
"e": 911,
"s": 894,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 922,
"s": 911,
"text": "JavaScript"
},
{
"code": null,
"e": 939,
"s": 922,
"text": "Web Technologies"
}
]
|
Python program to check if a string is palindrome or not | 16 Jun, 2022
Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome.
Examples:
Input : malayalam
Output : Yes
Input : geeks
Output : No
Method #1
Find reverse of stringCheck if reverse and original are same or not.
Find reverse of string
Check if reverse and original are same or not.
Python
# function which return reverse of a string def isPalindrome(s): return s == s[::-1] # Driver codes = "malayalam"ans = isPalindrome(s) if ans: print("Yes")else: print("No")
Output :
Yes
Time complexity: O(n)
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.
Auxiliary Space: O(1)
Iterative Method: This method is contributed by Shariq Raza. Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on .... If any character mismatches, the string wouldn’t be a palindrome.
Below is the implementation of above approach:
Python
# function to check string is# palindrome or notdef isPalindrome(str): # Run loop from 0 to len/2 for i in range(0, int(len(str)/2)): if str[i] != str[len(str)-i-1]: return False return True # main functions = "malayalam"ans = isPalindrome(s) if (ans): print("Yes")else: print("No")
Output:
Yes
Time complexity: O(n)
Auxiliary Space: O(1)
Method using the inbuilt function to reverse a string: This method is contributed by Shariq Raza. In this method, predefined function ‘ ‘.join(reversed(string)) is used to reverse string.
Below is the implementation of the above approach:
Python
# function to check string is# palindrome or notdef isPalindrome(s): # Using predefined function to # reverse to string print(s) rev = ''.join(reversed(s)) # Checking if both string are # equal or not if (s == rev): return True return False # main functions = "malayalam"ans = isPalindrome(s) if (ans): print("Yes")else: print("No")
Output:
Yes
Time complexity: O(n)
Auxiliary Space: O(n)
Method using one extra variable: In this method, the user takes a character of string one by one and store it in an empty variable. After storing all the characters user will compare both the string and check whether it is palindrome or not.
Python
# Python program to check# if a string is palindrome# or not x = "malayalam" w = ""for i in x: w = i + w if (x == w): print("Yes")else: print("No")
Output:
Yes
Time complexity: O(n)
Auxiliary Space: O(n)
Method using flag: In this method, the user compares each character from starting and ending in a for loop and if the character does not match then it will change the status of the flag. Then it will check the status of the flag and accordingly and print whether it is a palindrome or not.
Python
# Python program to check# if a string is palindrome# or notst = 'malayalam'j = -1flag = 0for i in st: if i != st[j]: flag = 1 break j = j - 1if flag == 1: print("NO")else: print("Yes")
Output:
Yes
Time complexity: O(n)
Auxiliary Space: O(1)
Method using recursion:
This method compares the first and the last element of the string and gives the rest of the substring to a recursive call to itself.
Python3
# Recursive function to check if a# string is palindromedef isPalindrome(s): # to change it the string is similar case s = s.lower() # length of s l = len(s) # if length is less than 2 if l < 2: return True # If s[0] and s[l-1] are equal elif s[0] == s[l - 1]: # Call is palindrome form substring(1,l-1) return isPalindrome(s[1: l - 1]) else: return False # Driver Codes = "MalaYaLam"ans = isPalindrome(s) if ans: print("Yes") else: print("No")
Output:
Yes
Time complexity: O(n)
Auxiliary Space: O(n)
This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mmishraofficial
geeksforgeeks84
goylshubham
VaibhavThakur
kyle3
dineshsharmaindia
perrymishra051298alok
rajumahapatra096
sumitgumber28
kothavvsaakash
riya55
Python string-programs
Python
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 286,
"s": 52,
"text": "Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome."
},
{
"code": null,
"e": 297,
"s": 286,
"text": "Examples: "
},
{
"code": null,
"e": 355,
"s": 297,
"text": "Input : malayalam\nOutput : Yes\n\nInput : geeks\nOutput : No"
},
{
"code": null,
"e": 366,
"s": 355,
"text": "Method #1 "
},
{
"code": null,
"e": 435,
"s": 366,
"text": "Find reverse of stringCheck if reverse and original are same or not."
},
{
"code": null,
"e": 458,
"s": 435,
"text": "Find reverse of string"
},
{
"code": null,
"e": 505,
"s": 458,
"text": "Check if reverse and original are same or not."
},
{
"code": null,
"e": 512,
"s": 505,
"text": "Python"
},
{
"code": "# function which return reverse of a string def isPalindrome(s): return s == s[::-1] # Driver codes = \"malayalam\"ans = isPalindrome(s) if ans: print(\"Yes\")else: print(\"No\")",
"e": 695,
"s": 512,
"text": null
},
{
"code": null,
"e": 705,
"s": 695,
"text": "Output : "
},
{
"code": null,
"e": 709,
"s": 705,
"text": "Yes"
},
{
"code": null,
"e": 731,
"s": 709,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 740,
"s": 731,
"text": "Chapters"
},
{
"code": null,
"e": 767,
"s": 740,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 817,
"s": 767,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 840,
"s": 817,
"text": "captions off, selected"
},
{
"code": null,
"e": 848,
"s": 840,
"text": "English"
},
{
"code": null,
"e": 872,
"s": 848,
"text": "This is a modal window."
},
{
"code": null,
"e": 941,
"s": 872,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 963,
"s": 941,
"text": "End of dialog window."
},
{
"code": null,
"e": 985,
"s": 963,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1260,
"s": 985,
"text": "Iterative Method: This method is contributed by Shariq Raza. Run a loop from starting to length/2 and check the first character to the last character of the string and second to second last one and so on .... If any character mismatches, the string wouldn’t be a palindrome."
},
{
"code": null,
"e": 1308,
"s": 1260,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 1315,
"s": 1308,
"text": "Python"
},
{
"code": "# function to check string is# palindrome or notdef isPalindrome(str): # Run loop from 0 to len/2 for i in range(0, int(len(str)/2)): if str[i] != str[len(str)-i-1]: return False return True # main functions = \"malayalam\"ans = isPalindrome(s) if (ans): print(\"Yes\")else: print(\"No\")",
"e": 1632,
"s": 1315,
"text": null
},
{
"code": null,
"e": 1641,
"s": 1632,
"text": "Output: "
},
{
"code": null,
"e": 1645,
"s": 1641,
"text": "Yes"
},
{
"code": null,
"e": 1667,
"s": 1645,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 1689,
"s": 1667,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1878,
"s": 1689,
"text": "Method using the inbuilt function to reverse a string: This method is contributed by Shariq Raza. In this method, predefined function ‘ ‘.join(reversed(string)) is used to reverse string. "
},
{
"code": null,
"e": 1930,
"s": 1878,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1937,
"s": 1930,
"text": "Python"
},
{
"code": "# function to check string is# palindrome or notdef isPalindrome(s): # Using predefined function to # reverse to string print(s) rev = ''.join(reversed(s)) # Checking if both string are # equal or not if (s == rev): return True return False # main functions = \"malayalam\"ans = isPalindrome(s) if (ans): print(\"Yes\")else: print(\"No\")",
"e": 2306,
"s": 1937,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2306,
"text": "Output: "
},
{
"code": null,
"e": 2319,
"s": 2315,
"text": "Yes"
},
{
"code": null,
"e": 2341,
"s": 2319,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 2363,
"s": 2341,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 2606,
"s": 2363,
"text": "Method using one extra variable: In this method, the user takes a character of string one by one and store it in an empty variable. After storing all the characters user will compare both the string and check whether it is palindrome or not. "
},
{
"code": null,
"e": 2613,
"s": 2606,
"text": "Python"
},
{
"code": "# Python program to check# if a string is palindrome# or not x = \"malayalam\" w = \"\"for i in x: w = i + w if (x == w): print(\"Yes\")else: print(\"No\")",
"e": 2770,
"s": 2613,
"text": null
},
{
"code": null,
"e": 2779,
"s": 2770,
"text": "Output: "
},
{
"code": null,
"e": 2783,
"s": 2779,
"text": "Yes"
},
{
"code": null,
"e": 2805,
"s": 2783,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 2827,
"s": 2805,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 3119,
"s": 2827,
"text": "Method using flag: In this method, the user compares each character from starting and ending in a for loop and if the character does not match then it will change the status of the flag. Then it will check the status of the flag and accordingly and print whether it is a palindrome or not. "
},
{
"code": null,
"e": 3126,
"s": 3119,
"text": "Python"
},
{
"code": "# Python program to check# if a string is palindrome# or notst = 'malayalam'j = -1flag = 0for i in st: if i != st[j]: flag = 1 break j = j - 1if flag == 1: print(\"NO\")else: print(\"Yes\")",
"e": 3338,
"s": 3126,
"text": null
},
{
"code": null,
"e": 3347,
"s": 3338,
"text": "Output: "
},
{
"code": null,
"e": 3351,
"s": 3347,
"text": "Yes"
},
{
"code": null,
"e": 3373,
"s": 3351,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 3395,
"s": 3373,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3420,
"s": 3395,
"text": "Method using recursion: "
},
{
"code": null,
"e": 3554,
"s": 3420,
"text": "This method compares the first and the last element of the string and gives the rest of the substring to a recursive call to itself. "
},
{
"code": null,
"e": 3562,
"s": 3554,
"text": "Python3"
},
{
"code": "# Recursive function to check if a# string is palindromedef isPalindrome(s): # to change it the string is similar case s = s.lower() # length of s l = len(s) # if length is less than 2 if l < 2: return True # If s[0] and s[l-1] are equal elif s[0] == s[l - 1]: # Call is palindrome form substring(1,l-1) return isPalindrome(s[1: l - 1]) else: return False # Driver Codes = \"MalaYaLam\"ans = isPalindrome(s) if ans: print(\"Yes\") else: print(\"No\")",
"e": 4073,
"s": 3562,
"text": null
},
{
"code": null,
"e": 4081,
"s": 4073,
"text": "Output:"
},
{
"code": null,
"e": 4085,
"s": 4081,
"text": "Yes"
},
{
"code": null,
"e": 4107,
"s": 4085,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 4129,
"s": 4107,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 4425,
"s": 4129,
"text": "This article is contributed by Sahil Rajput. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4550,
"s": 4425,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4566,
"s": 4550,
"text": "mmishraofficial"
},
{
"code": null,
"e": 4582,
"s": 4566,
"text": "geeksforgeeks84"
},
{
"code": null,
"e": 4594,
"s": 4582,
"text": "goylshubham"
},
{
"code": null,
"e": 4608,
"s": 4594,
"text": "VaibhavThakur"
},
{
"code": null,
"e": 4614,
"s": 4608,
"text": "kyle3"
},
{
"code": null,
"e": 4632,
"s": 4614,
"text": "dineshsharmaindia"
},
{
"code": null,
"e": 4654,
"s": 4632,
"text": "perrymishra051298alok"
},
{
"code": null,
"e": 4671,
"s": 4654,
"text": "rajumahapatra096"
},
{
"code": null,
"e": 4685,
"s": 4671,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4700,
"s": 4685,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 4707,
"s": 4700,
"text": "riya55"
},
{
"code": null,
"e": 4730,
"s": 4707,
"text": "Python string-programs"
},
{
"code": null,
"e": 4737,
"s": 4730,
"text": "Python"
},
{
"code": null,
"e": 4756,
"s": 4737,
"text": "School Programming"
},
{
"code": null,
"e": 4764,
"s": 4756,
"text": "Strings"
},
{
"code": null,
"e": 4772,
"s": 4764,
"text": "Strings"
}
]
|
fmt.Println() Function in Golang With Examples | 05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Println() function in Go language formats using the default formats for its operands and writes to standard output. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Println(a ...interface{}) (n int, err error)
Here, “a ...interface{}” contains some strings including specified constant variables.
Return Value: It returns the number of bytes written and any write error encountered.
Example 1:
// Golang program to illustrate the usage of// fmt.Println() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling Println() function fmt.Println(name, "is", "a", dept, "Portal.") // It is conventional not to worry about any // error returned by Println. }
Output:
GeeksforGeeks is a CS Portal.
In the above code, it can be seen that the function Println() is not containing any space within the specified strings still in output is print space that can be seen from the above output.
Example 2:
// Golang program to illustrate the usage of// fmt.Println() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3, num4 = 5, 10, 15, 50 // Calling Println() function fmt.Println(num1, "+", num2, "=", num3) fmt.Println(num1, "*", num2, "=", num4) // It is conventional not to worry about any // error returned by Println. }
Output:
5 + 10 = 15
5 * 10 = 50
In the above code, it can be seen that the function Println() is not using any newline (\n) still in the output it prints new line that can be seen from above shown output.
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 486,
"s": 28,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Println() function in Go language formats using the default formats for its operands and writes to standard output. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions."
},
{
"code": null,
"e": 494,
"s": 486,
"text": "Syntax:"
},
{
"code": null,
"e": 545,
"s": 494,
"text": "func Println(a ...interface{}) (n int, err error)\n"
},
{
"code": null,
"e": 632,
"s": 545,
"text": "Here, “a ...interface{}” contains some strings including specified constant variables."
},
{
"code": null,
"e": 718,
"s": 632,
"text": "Return Value: It returns the number of bytes written and any write error encountered."
},
{
"code": null,
"e": 729,
"s": 718,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Println() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const name, dept = \"GeeksforGeeks\", \"CS\" // Calling Println() function fmt.Println(name, \"is\", \"a\", dept, \"Portal.\") // It is conventional not to worry about any // error returned by Println. }",
"e": 1161,
"s": 729,
"text": null
},
{
"code": null,
"e": 1169,
"s": 1161,
"text": "Output:"
},
{
"code": null,
"e": 1200,
"s": 1169,
"text": "GeeksforGeeks is a CS Portal.\n"
},
{
"code": null,
"e": 1390,
"s": 1200,
"text": "In the above code, it can be seen that the function Println() is not containing any space within the specified strings still in output is print space that can be seen from the above output."
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Println() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3, num4 = 5, 10, 15, 50 // Calling Println() function fmt.Println(num1, \"+\", num2, \"=\", num3) fmt.Println(num1, \"*\", num2, \"=\", num4) // It is conventional not to worry about any // error returned by Println. }",
"e": 1874,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1882,
"s": 1874,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1882,
"text": "5 + 10 = 15\n5 * 10 = 50\n"
},
{
"code": null,
"e": 2080,
"s": 1907,
"text": "In the above code, it can be seen that the function Println() is not using any newline (\\n) still in the output it prints new line that can be seen from above shown output."
},
{
"code": null,
"e": 2091,
"s": 2080,
"text": "Golang-fmt"
},
{
"code": null,
"e": 2103,
"s": 2091,
"text": "Go Language"
}
]
|
Python – Accessing Items in Lists Within Dictionary | 23 Aug, 2021
Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary.
This is a straightforward method, where the key from which the values have to be extracted is passed along with the index for a specific value.
Syntax:
dictionary_name[key][index]
Example: direct indexing
Python3
# Creating dictionary which contains listscountry = { "India": ["Delhi", "Maharastra", "Haryana", "Uttar Pradesh", "Himachal Pradesh"], "Japan": ["Hokkaido", "Chubu", "Tohoku", "Shikoku"], "United States": ["New York", "Texas", "Indiana", "New Jersey", "Hawaii", "Alaska"]} print(country["India"])print(country["India"][0])print(country["India"][1])print(country["United States"][3])print(country['Japan'][2])
Output :
[‘Delhi’, ‘Maharastra’, ‘Haryana’, ‘Uttar Pradesh’, ‘Himachal Pradesh’]
Delhi
Maharastra
New Jersey
Tohoku
The easiest way to achieve the task given is to iterate over the dictionary.
Example: Using loop
Python3
# Creating dictionary which contains listscountry = { "India": ["Delhi", "Maharastra", "Haryana", "Uttar Pradesh", "Himachal Pradesh"], "Japan": ["Hokkaido", "Chubu", "Tohoku", "Shikoku"], "United States": ["New York", "Texas", "Indiana", "New Jersey", "Hawaii", "Alaska"]} for key, val in country.items(): for i in val: print("{} : {}".format(key, i)) print("--------------------")
Output :
India : Delhi
India : Maharastra
India : Haryana
India : Uttar Pradesh
India : Himachal Pradesh
——————–
Japan : Hokkaido
Japan : Chubu
Japan : Tohoku
Japan : Shikoku
——————–
United States : New York
United States : Texas
United States : Indiana
United States : New Jersey
United States : Hawaii
United States : Alaska
——————–
This is more or less the first two methods combined, where using the key the value list is iterated.
Example: Accessing a particular list of the key
Python3
# Creating dictionary which contains listscountry = { "India": ["Delhi", "Maharastra", "Haryana", "Uttar Pradesh", "Himachal Pradesh"], "Japan": ["Hokkaido", "Chubu", "Tohoku", "Shikoku"], "United States": ["New York", "Texas", "Indiana", "New Jersey", "Hawaii", "Alaska"]} for i in country['Japan']: print(i) for i in country['India']: print(i) for i in country['United States']: print(i)
Output:
Hokkaido
Chubu
Tohoku
Shikoku
Delhi
Maharastra
Haryana
Uttar Pradesh
Himachal Pradesh
New York
Texas
Indiana
New Jersey
Hawaii
Alaska
This is a modified version of the first method, here instead of index for the value list, we pass the slicing range.
Syntax:
dictionary_name[key][start_index : end_index]
Example: using list slicing
Python3
# Creating dictionary which contains listscountry = { "India": ["Delhi", "Maharastra", "Haryana", "Uttar Pradesh", "Himachal Pradesh"], "Japan": ["Hokkaido", "Chubu", "Tohoku", "Shikoku"], "United States": ["New York", "Texas", "Indiana", "New Jersey", "Hawaii", "Alaska"]} # extract the first 3 cities of Indiaprint(country["India"][:3]) # extract last 2 cities from Japanprint(country["Japan"][-2:]) # extract all cities except last 3 cities from indiaprint(country["India"][:-3]) # extract 2th to 5th cities from usprint(country["United States"][1:5])
Output :
[‘Delhi’, ‘Maharastra’, ‘Haryana’]
[‘Tohoku’, ‘Shikoku’]
[‘Delhi’, ‘Maharastra’]
[‘Texas’, ‘Indiana’, ‘New Jersey’, ‘Hawaii’]
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 166,
"s": 28,
"text": "Given a dictionary with values as a list, the task is to write a python program that can access list value items within this dictionary. "
},
{
"code": null,
"e": 310,
"s": 166,
"text": "This is a straightforward method, where the key from which the values have to be extracted is passed along with the index for a specific value."
},
{
"code": null,
"e": 318,
"s": 310,
"text": "Syntax:"
},
{
"code": null,
"e": 346,
"s": 318,
"text": "dictionary_name[key][index]"
},
{
"code": null,
"e": 371,
"s": 346,
"text": "Example: direct indexing"
},
{
"code": null,
"e": 379,
"s": 371,
"text": "Python3"
},
{
"code": "# Creating dictionary which contains listscountry = { \"India\": [\"Delhi\", \"Maharastra\", \"Haryana\", \"Uttar Pradesh\", \"Himachal Pradesh\"], \"Japan\": [\"Hokkaido\", \"Chubu\", \"Tohoku\", \"Shikoku\"], \"United States\": [\"New York\", \"Texas\", \"Indiana\", \"New Jersey\", \"Hawaii\", \"Alaska\"]} print(country[\"India\"])print(country[\"India\"][0])print(country[\"India\"][1])print(country[\"United States\"][3])print(country['Japan'][2])",
"e": 836,
"s": 379,
"text": null
},
{
"code": null,
"e": 845,
"s": 836,
"text": "Output :"
},
{
"code": null,
"e": 917,
"s": 845,
"text": "[‘Delhi’, ‘Maharastra’, ‘Haryana’, ‘Uttar Pradesh’, ‘Himachal Pradesh’]"
},
{
"code": null,
"e": 923,
"s": 917,
"text": "Delhi"
},
{
"code": null,
"e": 934,
"s": 923,
"text": "Maharastra"
},
{
"code": null,
"e": 945,
"s": 934,
"text": "New Jersey"
},
{
"code": null,
"e": 952,
"s": 945,
"text": "Tohoku"
},
{
"code": null,
"e": 1029,
"s": 952,
"text": "The easiest way to achieve the task given is to iterate over the dictionary."
},
{
"code": null,
"e": 1049,
"s": 1029,
"text": "Example: Using loop"
},
{
"code": null,
"e": 1057,
"s": 1049,
"text": "Python3"
},
{
"code": "# Creating dictionary which contains listscountry = { \"India\": [\"Delhi\", \"Maharastra\", \"Haryana\", \"Uttar Pradesh\", \"Himachal Pradesh\"], \"Japan\": [\"Hokkaido\", \"Chubu\", \"Tohoku\", \"Shikoku\"], \"United States\": [\"New York\", \"Texas\", \"Indiana\", \"New Jersey\", \"Hawaii\", \"Alaska\"]} for key, val in country.items(): for i in val: print(\"{} : {}\".format(key, i)) print(\"--------------------\")",
"e": 1500,
"s": 1057,
"text": null
},
{
"code": null,
"e": 1509,
"s": 1500,
"text": "Output :"
},
{
"code": null,
"e": 1523,
"s": 1509,
"text": "India : Delhi"
},
{
"code": null,
"e": 1542,
"s": 1523,
"text": "India : Maharastra"
},
{
"code": null,
"e": 1558,
"s": 1542,
"text": "India : Haryana"
},
{
"code": null,
"e": 1580,
"s": 1558,
"text": "India : Uttar Pradesh"
},
{
"code": null,
"e": 1605,
"s": 1580,
"text": "India : Himachal Pradesh"
},
{
"code": null,
"e": 1613,
"s": 1605,
"text": "——————–"
},
{
"code": null,
"e": 1630,
"s": 1613,
"text": "Japan : Hokkaido"
},
{
"code": null,
"e": 1644,
"s": 1630,
"text": "Japan : Chubu"
},
{
"code": null,
"e": 1659,
"s": 1644,
"text": "Japan : Tohoku"
},
{
"code": null,
"e": 1675,
"s": 1659,
"text": "Japan : Shikoku"
},
{
"code": null,
"e": 1683,
"s": 1675,
"text": "——————–"
},
{
"code": null,
"e": 1708,
"s": 1683,
"text": "United States : New York"
},
{
"code": null,
"e": 1730,
"s": 1708,
"text": "United States : Texas"
},
{
"code": null,
"e": 1754,
"s": 1730,
"text": "United States : Indiana"
},
{
"code": null,
"e": 1781,
"s": 1754,
"text": "United States : New Jersey"
},
{
"code": null,
"e": 1804,
"s": 1781,
"text": "United States : Hawaii"
},
{
"code": null,
"e": 1827,
"s": 1804,
"text": "United States : Alaska"
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "——————–"
},
{
"code": null,
"e": 1936,
"s": 1835,
"text": "This is more or less the first two methods combined, where using the key the value list is iterated."
},
{
"code": null,
"e": 1984,
"s": 1936,
"text": "Example: Accessing a particular list of the key"
},
{
"code": null,
"e": 1992,
"s": 1984,
"text": "Python3"
},
{
"code": "# Creating dictionary which contains listscountry = { \"India\": [\"Delhi\", \"Maharastra\", \"Haryana\", \"Uttar Pradesh\", \"Himachal Pradesh\"], \"Japan\": [\"Hokkaido\", \"Chubu\", \"Tohoku\", \"Shikoku\"], \"United States\": [\"New York\", \"Texas\", \"Indiana\", \"New Jersey\", \"Hawaii\", \"Alaska\"]} for i in country['Japan']: print(i) for i in country['India']: print(i) for i in country['United States']: print(i)",
"e": 2440,
"s": 1992,
"text": null
},
{
"code": null,
"e": 2448,
"s": 2440,
"text": "Output:"
},
{
"code": null,
"e": 2457,
"s": 2448,
"text": "Hokkaido"
},
{
"code": null,
"e": 2463,
"s": 2457,
"text": "Chubu"
},
{
"code": null,
"e": 2470,
"s": 2463,
"text": "Tohoku"
},
{
"code": null,
"e": 2478,
"s": 2470,
"text": "Shikoku"
},
{
"code": null,
"e": 2484,
"s": 2478,
"text": "Delhi"
},
{
"code": null,
"e": 2495,
"s": 2484,
"text": "Maharastra"
},
{
"code": null,
"e": 2503,
"s": 2495,
"text": "Haryana"
},
{
"code": null,
"e": 2517,
"s": 2503,
"text": "Uttar Pradesh"
},
{
"code": null,
"e": 2534,
"s": 2517,
"text": "Himachal Pradesh"
},
{
"code": null,
"e": 2543,
"s": 2534,
"text": "New York"
},
{
"code": null,
"e": 2549,
"s": 2543,
"text": "Texas"
},
{
"code": null,
"e": 2557,
"s": 2549,
"text": "Indiana"
},
{
"code": null,
"e": 2568,
"s": 2557,
"text": "New Jersey"
},
{
"code": null,
"e": 2575,
"s": 2568,
"text": "Hawaii"
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": "Alaska"
},
{
"code": null,
"e": 2699,
"s": 2582,
"text": "This is a modified version of the first method, here instead of index for the value list, we pass the slicing range."
},
{
"code": null,
"e": 2707,
"s": 2699,
"text": "Syntax:"
},
{
"code": null,
"e": 2753,
"s": 2707,
"text": "dictionary_name[key][start_index : end_index]"
},
{
"code": null,
"e": 2781,
"s": 2753,
"text": "Example: using list slicing"
},
{
"code": null,
"e": 2789,
"s": 2781,
"text": "Python3"
},
{
"code": "# Creating dictionary which contains listscountry = { \"India\": [\"Delhi\", \"Maharastra\", \"Haryana\", \"Uttar Pradesh\", \"Himachal Pradesh\"], \"Japan\": [\"Hokkaido\", \"Chubu\", \"Tohoku\", \"Shikoku\"], \"United States\": [\"New York\", \"Texas\", \"Indiana\", \"New Jersey\", \"Hawaii\", \"Alaska\"]} # extract the first 3 cities of Indiaprint(country[\"India\"][:3]) # extract last 2 cities from Japanprint(country[\"Japan\"][-2:]) # extract all cities except last 3 cities from indiaprint(country[\"India\"][:-3]) # extract 2th to 5th cities from usprint(country[\"United States\"][1:5])",
"e": 3392,
"s": 2789,
"text": null
},
{
"code": null,
"e": 3401,
"s": 3392,
"text": "Output :"
},
{
"code": null,
"e": 3436,
"s": 3401,
"text": "[‘Delhi’, ‘Maharastra’, ‘Haryana’]"
},
{
"code": null,
"e": 3458,
"s": 3436,
"text": "[‘Tohoku’, ‘Shikoku’]"
},
{
"code": null,
"e": 3482,
"s": 3458,
"text": "[‘Delhi’, ‘Maharastra’]"
},
{
"code": null,
"e": 3527,
"s": 3482,
"text": "[‘Texas’, ‘Indiana’, ‘New Jersey’, ‘Hawaii’]"
},
{
"code": null,
"e": 3534,
"s": 3527,
"text": "Picked"
},
{
"code": null,
"e": 3561,
"s": 3534,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 3573,
"s": 3561,
"text": "python-dict"
},
{
"code": null,
"e": 3580,
"s": 3573,
"text": "Python"
},
{
"code": null,
"e": 3596,
"s": 3580,
"text": "Python Programs"
},
{
"code": null,
"e": 3608,
"s": 3596,
"text": "python-dict"
},
{
"code": null,
"e": 3706,
"s": 3608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3738,
"s": 3706,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3765,
"s": 3738,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3786,
"s": 3765,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3809,
"s": 3786,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3840,
"s": 3809,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3862,
"s": 3840,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3901,
"s": 3862,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3939,
"s": 3901,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3988,
"s": 3939,
"text": "Python | Convert string dictionary to dictionary"
}
]
|
Print the frequency of each character in Alphabetical order | 10 Jun, 2021
Given a string str, the task is to print the frequency of each of the characters of str in alphabetical order.Example:
Input: str = “aabccccddd” Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: str = “geeksforgeeks” Output: e4f1g2k2o1r1s2
Approach:
Create a Map to store the frequency of each of the characters of the given string.Iterate through the string and check if the character is present in the map.If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1.Finally, print the frequency of each of the character in alphabetical order.
Create a Map to store the frequency of each of the characters of the given string.
Iterate through the string and check if the character is present in the map.
If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1.
Finally, print the frequency of each of the character in alphabetical order.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 26; // Function to print the frequency// of each of the characters of// s in alphabetical ordervoid compressString(string s, int n){ // To store the frequency // of the characters int freq[MAX] = { 0 }; // Update the frequency array for (int i = 0; i < n; i++) { freq[s[i] - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; cout << (char)(i + 'a') << freq[i]; }} // Driver codeint main(){ string s = "geeksforgeeks"; int n = s.length(); compressString(s, n); return 0;}
// Java implementation of the approachclass GFG{ static int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString(String s, int n) { // To store the frequency // of the characters int freq[] = new int[MAX] ; // Update the frequency array for (int i = 0; i < n; i++) { freq[s.charAt(i) - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; System.out.print((char)(i + 'a') +""+ freq[i]); } } // Driver code public static void main (String[] args) { String s = "geeksforgeeks"; int n = s.length(); compressString(s, n); }} // This code is contributed by AnkitRai01
# Python3 implementation of the approachMAX = 26; # Function to print the frequency# of each of the characters of# s in alphabetical orderdef compressString(s, n) : # To store the frequency # of the characters freq = [ 0 ] * MAX; # Update the frequency array for i in range(n) : freq[ord(s[i]) - ord('a')] += 1; # Print the frequency in alphatecial order for i in range(MAX) : # If the current alphabet doesn't # appear in the string if (freq[i] == 0) : continue; print((chr)(i + ord('a')),freq[i],end = " "); # Driver codeif __name__ == "__main__" : s = "geeksforgeeks"; n = len(s); compressString(s, n); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ static int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString(string s, int n) { // To store the frequency // of the characters int []freq = new int[MAX] ; // Update the frequency array for (int i = 0; i < n; i++) { freq[s[i] - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; Console.Write((char)(i + 'a') +""+ freq[i]); } } // Driver code public static void Main() { string s = "geeksforgeeks"; int n = s.Length; compressString(s, n); }} // This code is contributed by AnkitRai01
<script> // Javascript implementation of the approach let MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order function compressString(s, n) { // To store the frequency // of the characters let freq = new Array(MAX); freq.fill(0); // Update the frequency array for (let i = 0; i < n; i++) { freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; } // Print the frequency in alphatecial order for (let i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; document.write(String.fromCharCode(i + 'a'.charCodeAt()) +""+ freq[i]); } } let s = "geeksforgeeks"; let n = s.length; compressString(s, n); </script>
e4f1g2k2o1r1s2
Time Complexity: O(n) Auxiliary Space: O(1)
ankthon
raghumarusu
suresh07
frequency-counting
school-programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Data Structure: Types, Classifications and Applications
Top 50 String Coding Problems for Interviews
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Palindrome Partitioning | DP-17
Find the smallest window in a string containing all characters of another string
Convert character array to string in C++
Remove first and last character of a string in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 175,
"s": 54,
"text": "Given a string str, the task is to print the frequency of each of the characters of str in alphabetical order.Example: "
},
{
"code": null,
"e": 379,
"s": 175,
"text": "Input: str = “aabccccddd” Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: str = “geeksforgeeks” Output: e4f1g2k2o1r1s2 "
},
{
"code": null,
"e": 393,
"s": 381,
"text": "Approach: "
},
{
"code": null,
"e": 744,
"s": 393,
"text": "Create a Map to store the frequency of each of the characters of the given string.Iterate through the string and check if the character is present in the map.If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1.Finally, print the frequency of each of the character in alphabetical order."
},
{
"code": null,
"e": 827,
"s": 744,
"text": "Create a Map to store the frequency of each of the characters of the given string."
},
{
"code": null,
"e": 904,
"s": 827,
"text": "Iterate through the string and check if the character is present in the map."
},
{
"code": null,
"e": 1021,
"s": 904,
"text": "If the character is not present, insert it in the map with 1 as the initial value else increment its frequency by 1."
},
{
"code": null,
"e": 1098,
"s": 1021,
"text": "Finally, print the frequency of each of the character in alphabetical order."
},
{
"code": null,
"e": 1151,
"s": 1098,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1155,
"s": 1151,
"text": "C++"
},
{
"code": null,
"e": 1160,
"s": 1155,
"text": "Java"
},
{
"code": null,
"e": 1168,
"s": 1160,
"text": "Python3"
},
{
"code": null,
"e": 1171,
"s": 1168,
"text": "C#"
},
{
"code": null,
"e": 1182,
"s": 1171,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 26; // Function to print the frequency// of each of the characters of// s in alphabetical ordervoid compressString(string s, int n){ // To store the frequency // of the characters int freq[MAX] = { 0 }; // Update the frequency array for (int i = 0; i < n; i++) { freq[s[i] - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; cout << (char)(i + 'a') << freq[i]; }} // Driver codeint main(){ string s = \"geeksforgeeks\"; int n = s.length(); compressString(s, n); return 0;}",
"e": 1965,
"s": 1182,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString(String s, int n) { // To store the frequency // of the characters int freq[] = new int[MAX] ; // Update the frequency array for (int i = 0; i < n; i++) { freq[s.charAt(i) - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; System.out.print((char)(i + 'a') +\"\"+ freq[i]); } } // Driver code public static void main (String[] args) { String s = \"geeksforgeeks\"; int n = s.length(); compressString(s, n); }} // This code is contributed by AnkitRai01",
"e": 2967,
"s": 1965,
"text": null
},
{
"code": "# Python3 implementation of the approachMAX = 26; # Function to print the frequency# of each of the characters of# s in alphabetical orderdef compressString(s, n) : # To store the frequency # of the characters freq = [ 0 ] * MAX; # Update the frequency array for i in range(n) : freq[ord(s[i]) - ord('a')] += 1; # Print the frequency in alphatecial order for i in range(MAX) : # If the current alphabet doesn't # appear in the string if (freq[i] == 0) : continue; print((chr)(i + ord('a')),freq[i],end = \" \"); # Driver codeif __name__ == \"__main__\" : s = \"geeksforgeeks\"; n = len(s); compressString(s, n); # This code is contributed by AnkitRai01",
"e": 3697,
"s": 2967,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order static void compressString(string s, int n) { // To store the frequency // of the characters int []freq = new int[MAX] ; // Update the frequency array for (int i = 0; i < n; i++) { freq[s[i] - 'a']++; } // Print the frequency in alphatecial order for (int i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; Console.Write((char)(i + 'a') +\"\"+ freq[i]); } } // Driver code public static void Main() { string s = \"geeksforgeeks\"; int n = s.Length; compressString(s, n); }} // This code is contributed by AnkitRai01",
"e": 4685,
"s": 3697,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let MAX = 26; // Function to print the frequency // of each of the characters of // s in alphabetical order function compressString(s, n) { // To store the frequency // of the characters let freq = new Array(MAX); freq.fill(0); // Update the frequency array for (let i = 0; i < n; i++) { freq[s[i].charCodeAt() - 'a'.charCodeAt()]++; } // Print the frequency in alphatecial order for (let i = 0; i < MAX; i++) { // If the current alphabet doesn't // appear in the string if (freq[i] == 0) continue; document.write(String.fromCharCode(i + 'a'.charCodeAt()) +\"\"+ freq[i]); } } let s = \"geeksforgeeks\"; let n = s.length; compressString(s, n); </script>",
"e": 5638,
"s": 4685,
"text": null
},
{
"code": null,
"e": 5653,
"s": 5638,
"text": "e4f1g2k2o1r1s2"
},
{
"code": null,
"e": 5700,
"s": 5655,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5708,
"s": 5700,
"text": "ankthon"
},
{
"code": null,
"e": 5720,
"s": 5708,
"text": "raghumarusu"
},
{
"code": null,
"e": 5729,
"s": 5720,
"text": "suresh07"
},
{
"code": null,
"e": 5748,
"s": 5729,
"text": "frequency-counting"
},
{
"code": null,
"e": 5767,
"s": 5748,
"text": "school-programming"
},
{
"code": null,
"e": 5775,
"s": 5767,
"text": "Strings"
},
{
"code": null,
"e": 5783,
"s": 5775,
"text": "Strings"
},
{
"code": null,
"e": 5881,
"s": 5783,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5945,
"s": 5881,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 5990,
"s": 5945,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 6035,
"s": 5990,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 6070,
"s": 6035,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 6135,
"s": 6070,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 6164,
"s": 6135,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 6196,
"s": 6164,
"text": "Palindrome Partitioning | DP-17"
},
{
"code": null,
"e": 6277,
"s": 6196,
"text": "Find the smallest window in a string containing all characters of another string"
},
{
"code": null,
"e": 6318,
"s": 6277,
"text": "Convert character array to string in C++"
}
]
|
std::string::append() in C++ | 06 Jul, 2017
This member function appends characters in the end of string.
Syntax 1 : Appends the characters of string str. It Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str)
str : is the string to be appended.
Returns : *this// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << "Using append() : "; cout << str1 << endl;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World!
Using append() : Hello World! GeeksforGeeks
Syntax 2 : Appends at most, str_num characters of string str, starting with index str_idx. It throws out_of_range if str_idx > str. size(). It throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str, size_type str_idx, size_type str_num)
str : is the string to be appended
str_num : being number of characters
str_idx : is index number.
Returns : *this.
// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << "Using append() : "; cout << str1;} // Driver codeint main(){ string str1("GeeksforGeeks "); string str2("Hello World! "); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : GeeksforGeeks
Using append() : GeeksforGeeks Hello
Syntax 3: Appends the characters of the C-string cstr. Throw length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* cstr)
*cstr : is the pointer to C-string.
Note : that cstr may not be a null pointer (NULL).
Return : *this
// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends "GeeksforGeeks" // in str str.append("GeeksforGeeks"); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : World of
Using append() : World of GeeksforGeeks
Syntax 4: Appends chars_len characters of the character array chars. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* chars, size_type chars_len)
*chars is the pointer to character array to be appended.
chrs_len : is the number of characters from *chars to be appended.
Note that chars must have at least chars_len characters.
Returns : *this.
// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from "GeeksforGeeks" // to str str.append("GeeksforGeeks", 5); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : World of
Using append() : World of Geeks
Syntax 5: Appends num occurrences of character c. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (size_type num, char c)
num : is the number of occurrences
c : is the character which is to be appended repeatedly.
Returns : *this.
// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << "After append() : "; cout << str; } // Driver codeint main(){ string str("#########"); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : #########
After append() : #########$$$$$$$$$$
Syntax 6: Appends all characters of the range [beg, end). Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (InputIterator beg, InputIterator end)
first, last : Input iterators to the initial and final positions
in a sequence.
Returns *this.
// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << "Using append : "; cout << str1;}// Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World!
Using append : Hello World! forGeeks
Syntax 1 : Appends the characters of string str. It Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str)
str : is the string to be appended.
Returns : *this// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << "Using append() : "; cout << str1 << endl;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World!
Using append() : Hello World! GeeksforGeeks
string& string::append (const string& str)
str : is the string to be appended.
Returns : *this
// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << "Using append() : "; cout << str1 << endl;} // Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
Using append() : Hello World! GeeksforGeeks
Syntax 2 : Appends at most, str_num characters of string str, starting with index str_idx. It throws out_of_range if str_idx > str. size(). It throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str, size_type str_idx, size_type str_num)
str : is the string to be appended
str_num : being number of characters
str_idx : is index number.
Returns : *this.
// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << "Using append() : "; cout << str1;} // Driver codeint main(){ string str1("GeeksforGeeks "); string str2("Hello World! "); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : GeeksforGeeks
Using append() : GeeksforGeeks Hello
string& string::append (const string& str, size_type str_idx, size_type str_num)
str : is the string to be appended
str_num : being number of characters
str_idx : is index number.
Returns : *this.
// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << "Using append() : "; cout << str1;} // Driver codeint main(){ string str1("GeeksforGeeks "); string str2("Hello World! "); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}
Output:
Original String : GeeksforGeeks
Using append() : GeeksforGeeks Hello
Syntax 3: Appends the characters of the C-string cstr. Throw length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* cstr)
*cstr : is the pointer to C-string.
Note : that cstr may not be a null pointer (NULL).
Return : *this
// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends "GeeksforGeeks" // in str str.append("GeeksforGeeks"); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : World of
Using append() : World of GeeksforGeeks
string& string::append (const char* cstr)
*cstr : is the pointer to C-string.
Note : that cstr may not be a null pointer (NULL).
Return : *this
// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends "GeeksforGeeks" // in str str.append("GeeksforGeeks"); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}
Output:
Original String : World of
Using append() : World of GeeksforGeeks
Syntax 4: Appends chars_len characters of the character array chars. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* chars, size_type chars_len)
*chars is the pointer to character array to be appended.
chrs_len : is the number of characters from *chars to be appended.
Note that chars must have at least chars_len characters.
Returns : *this.
// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from "GeeksforGeeks" // to str str.append("GeeksforGeeks", 5); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : World of
Using append() : World of Geeks
string& string::append (const char* chars, size_type chars_len)
*chars is the pointer to character array to be appended.
chrs_len : is the number of characters from *chars to be appended.
Note that chars must have at least chars_len characters.
Returns : *this.
// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from "GeeksforGeeks" // to str str.append("GeeksforGeeks", 5); cout << "Using append() : "; cout << str << endl;} // Driver codeint main(){ string str("World of "); cout << "Original String : " << str << endl; appendDemo(str); return 0;}
Output:
Original String : World of
Using append() : World of Geeks
Syntax 5: Appends num occurrences of character c. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (size_type num, char c)
num : is the number of occurrences
c : is the character which is to be appended repeatedly.
Returns : *this.
// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << "After append() : "; cout << str; } // Driver codeint main(){ string str("#########"); cout << "Original String : " << str << endl; appendDemo(str); return 0;}Output:Original String : #########
After append() : #########$$$$$$$$$$
string& string::append (size_type num, char c)
num : is the number of occurrences
c : is the character which is to be appended repeatedly.
Returns : *this.
// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << "After append() : "; cout << str; } // Driver codeint main(){ string str("#########"); cout << "Original String : " << str << endl; appendDemo(str); return 0;}
Output:
Original String : #########
After append() : #########$$$$$$$$$$
Syntax 6: Appends all characters of the range [beg, end). Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (InputIterator beg, InputIterator end)
first, last : Input iterators to the initial and final positions
in a sequence.
Returns *this.
// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << "Using append : "; cout << str1;}// Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World!
Using append : Hello World! forGeeks
string& string::append (InputIterator beg, InputIterator end)
first, last : Input iterators to the initial and final positions
in a sequence.
Returns *this.
// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << "Using append : "; cout << str1;}// Driver codeint main(){ string str1("Hello World! "); string str2("GeeksforGeeks"); cout << "Original String : " << str1 << endl; appendDemo(str1, str2); return 0;}
Output:
Original String : Hello World!
Using append : Hello World! forGeeks
This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Priority Queue in C++ Standard Template Library (STL)
The C++ Standard Template Library (STL)
Sorting a vector in C++
Substring in C++
C++ Classes and Objects | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2017"
},
{
"code": null,
"e": 114,
"s": 52,
"text": "This member function appends characters in the end of string."
},
{
"code": null,
"e": 5516,
"s": 114,
"text": "Syntax 1 : Appends the characters of string str. It Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str)\n\nstr : is the string to be appended.\nReturns : *this// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << \"Using append() : \"; cout << str1 << endl;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World! \nUsing append() : Hello World! GeeksforGeeks\nSyntax 2 : Appends at most, str_num characters of string str, starting with index str_idx. It throws out_of_range if str_idx > str. size(). It throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str, size_type str_idx, size_type str_num)\n\nstr : is the string to be appended\nstr_num : being number of characters\nstr_idx : is index number.\nReturns : *this.\n// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << \"Using append() : \"; cout << str1;} // Driver codeint main(){ string str1(\"GeeksforGeeks \"); string str2(\"Hello World! \"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : GeeksforGeeks \nUsing append() : GeeksforGeeks Hello\nSyntax 3: Appends the characters of the C-string cstr. Throw length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* cstr)\n\n*cstr : is the pointer to C-string.\nNote : that cstr may not be a null pointer (NULL).\nReturn : *this\n// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends \"GeeksforGeeks\" // in str str.append(\"GeeksforGeeks\"); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : World of \nUsing append() : World of GeeksforGeeks\nSyntax 4: Appends chars_len characters of the character array chars. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* chars, size_type chars_len)\n\n*chars is the pointer to character array to be appended.\nchrs_len : is the number of characters from *chars to be appended.\nNote that chars must have at least chars_len characters. \nReturns : *this.\n// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from \"GeeksforGeeks\" // to str str.append(\"GeeksforGeeks\", 5); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : World of \nUsing append() : World of Geeks\nSyntax 5: Appends num occurrences of character c. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (size_type num, char c)\n\nnum : is the number of occurrences\nc : is the character which is to be appended repeatedly. \nReturns : *this.\n// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << \"After append() : \"; cout << str; } // Driver codeint main(){ string str(\"#########\"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : #########\nAfter append() : #########$$$$$$$$$$\nSyntax 6: Appends all characters of the range [beg, end). Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (InputIterator beg, InputIterator end)\n\nfirst, last : Input iterators to the initial and final positions \nin a sequence.\nReturns *this.\n// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << \"Using append : \"; cout << str1;}// Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World! \nUsing append : Hello World! forGeeks\n"
},
{
"code": null,
"e": 6306,
"s": 5516,
"text": "Syntax 1 : Appends the characters of string str. It Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str)\n\nstr : is the string to be appended.\nReturns : *this// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << \"Using append() : \"; cout << str1 << endl;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World! \nUsing append() : Hello World! GeeksforGeeks\n"
},
{
"code": null,
"e": 6404,
"s": 6306,
"text": "string& string::append (const string& str)\n\nstr : is the string to be appended.\nReturns : *this"
},
{
"code": "// CPP code to demonstrate append(str) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends str2 in str1 str1.append(str2); cout << \"Using append() : \"; cout << str1 << endl;} // Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}",
"e": 6879,
"s": 6404,
"text": null
},
{
"code": null,
"e": 6887,
"s": 6879,
"text": "Output:"
},
{
"code": null,
"e": 6964,
"s": 6887,
"text": "Original String : Hello World! \nUsing append() : Hello World! GeeksforGeeks\n"
},
{
"code": null,
"e": 8013,
"s": 6964,
"text": "Syntax 2 : Appends at most, str_num characters of string str, starting with index str_idx. It throws out_of_range if str_idx > str. size(). It throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const string& str, size_type str_idx, size_type str_num)\n\nstr : is the string to be appended\nstr_num : being number of characters\nstr_idx : is index number.\nReturns : *this.\n// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << \"Using append() : \"; cout << str1;} // Driver codeint main(){ string str1(\"GeeksforGeeks \"); string str2(\"Hello World! \"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : GeeksforGeeks \nUsing append() : GeeksforGeeks Hello\n"
},
{
"code": null,
"e": 8212,
"s": 8013,
"text": "string& string::append (const string& str, size_type str_idx, size_type str_num)\n\nstr : is the string to be appended\nstr_num : being number of characters\nstr_idx : is index number.\nReturns : *this.\n"
},
{
"code": "// CPP code to demonstrate // append(const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate append()void appendDemo(string str1, string str2){ // Appends 5 characters from 0th index of // str2 to str1 str1.append(str2, 0, 5); cout << \"Using append() : \"; cout << str1;} // Driver codeint main(){ string str1(\"GeeksforGeeks \"); string str2(\"Hello World! \"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}",
"e": 8760,
"s": 8212,
"text": null
},
{
"code": null,
"e": 8768,
"s": 8760,
"text": "Output:"
},
{
"code": null,
"e": 8839,
"s": 8768,
"text": "Original String : GeeksforGeeks \nUsing append() : GeeksforGeeks Hello\n"
},
{
"code": null,
"e": 9646,
"s": 8839,
"text": "Syntax 3: Appends the characters of the C-string cstr. Throw length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* cstr)\n\n*cstr : is the pointer to C-string.\nNote : that cstr may not be a null pointer (NULL).\nReturn : *this\n// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends \"GeeksforGeeks\" // in str str.append(\"GeeksforGeeks\"); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : World of \nUsing append() : World of GeeksforGeeks\n"
},
{
"code": null,
"e": 9792,
"s": 9646,
"text": "string& string::append (const char* cstr)\n\n*cstr : is the pointer to C-string.\nNote : that cstr may not be a null pointer (NULL).\nReturn : *this\n"
},
{
"code": "// CPP code to demonstrate append(const char* cstr) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends \"GeeksforGeeks\" // in str str.append(\"GeeksforGeeks\"); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}",
"e": 10242,
"s": 9792,
"text": null
},
{
"code": null,
"e": 10250,
"s": 10242,
"text": "Output:"
},
{
"code": null,
"e": 10319,
"s": 10250,
"text": "Original String : World of \nUsing append() : World of GeeksforGeeks\n"
},
{
"code": null,
"e": 11292,
"s": 10319,
"text": "Syntax 4: Appends chars_len characters of the character array chars. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (const char* chars, size_type chars_len)\n\n*chars is the pointer to character array to be appended.\nchrs_len : is the number of characters from *chars to be appended.\nNote that chars must have at least chars_len characters. \nReturns : *this.\n// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from \"GeeksforGeeks\" // to str str.append(\"GeeksforGeeks\", 5); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : World of \nUsing append() : World of Geeks\n"
},
{
"code": null,
"e": 11557,
"s": 11292,
"text": "string& string::append (const char* chars, size_type chars_len)\n\n*chars is the pointer to character array to be appended.\nchrs_len : is the number of characters from *chars to be appended.\nNote that chars must have at least chars_len characters. \nReturns : *this.\n"
},
{
"code": "// CPP code to demonstrate // (const char* chars, size_type chars_len) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 5 characters from \"GeeksforGeeks\" // to str str.append(\"GeeksforGeeks\", 5); cout << \"Using append() : \"; cout << str << endl;} // Driver codeint main(){ string str(\"World of \"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}",
"e": 12047,
"s": 11557,
"text": null
},
{
"code": null,
"e": 12055,
"s": 12047,
"text": "Output:"
},
{
"code": null,
"e": 12116,
"s": 12055,
"text": "Original String : World of \nUsing append() : World of Geeks\n"
},
{
"code": null,
"e": 12957,
"s": 12116,
"text": "Syntax 5: Appends num occurrences of character c. Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (size_type num, char c)\n\nnum : is the number of occurrences\nc : is the character which is to be appended repeatedly. \nReturns : *this.\n// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << \"After append() : \"; cout << str; } // Driver codeint main(){ string str(\"#########\"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}Output:Original String : #########\nAfter append() : #########$$$$$$$$$$\n"
},
{
"code": null,
"e": 13116,
"s": 12957,
"text": "string& string::append (size_type num, char c)\n\nnum : is the number of occurrences\nc : is the character which is to be appended repeatedly. \nReturns : *this.\n"
},
{
"code": "// CPP code to illustrate// string& string::append (size_type num, char c) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str){ // Appends 10 occurrences of '$' // to str str.append(10, '$'); cout << \"After append() : \"; cout << str; } // Driver codeint main(){ string str(\"#########\"); cout << \"Original String : \" << str << endl; appendDemo(str); return 0;}",
"e": 13594,
"s": 13116,
"text": null
},
{
"code": null,
"e": 13602,
"s": 13594,
"text": "Output:"
},
{
"code": null,
"e": 13668,
"s": 13602,
"text": "Original String : #########\nAfter append() : #########$$$$$$$$$$\n"
},
{
"code": null,
"e": 14615,
"s": 13668,
"text": "Syntax 6: Appends all characters of the range [beg, end). Throws length_error if the resulting size exceeds the maximum number of characters.string& string::append (InputIterator beg, InputIterator end)\n\nfirst, last : Input iterators to the initial and final positions \nin a sequence.\nReturns *this.\n// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << \"Using append : \"; cout << str1;}// Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}Output:Original String : Hello World! \nUsing append : Hello World! forGeeks\n"
},
{
"code": null,
"e": 14775,
"s": 14615,
"text": "string& string::append (InputIterator beg, InputIterator end)\n\nfirst, last : Input iterators to the initial and final positions \nin a sequence.\nReturns *this.\n"
},
{
"code": "// CPP code to illustrate// append (InputIterator beg, InputIterator end) #include <iostream>#include <string>using namespace std; // Function to demonstrate appendvoid appendDemo(string str1, string str2){ // Appends all characters from // str2.begin()+5, str2.end() to str1 str1.append(str2.begin() + 5, str2.end()); cout << \"Using append : \"; cout << str1;}// Driver codeint main(){ string str1(\"Hello World! \"); string str2(\"GeeksforGeeks\"); cout << \"Original String : \" << str1 << endl; appendDemo(str1, str2); return 0;}",
"e": 15346,
"s": 14775,
"text": null
},
{
"code": null,
"e": 15354,
"s": 15346,
"text": "Output:"
},
{
"code": null,
"e": 15424,
"s": 15354,
"text": "Original String : Hello World! \nUsing append : Hello World! forGeeks\n"
},
{
"code": null,
"e": 15742,
"s": 15424,
"text": "This article is contributed by Sakshi Tiwari. If you like GeeksforGeeks(We know you do!) and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 15867,
"s": 15742,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15887,
"s": 15867,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 15891,
"s": 15887,
"text": "STL"
},
{
"code": null,
"e": 15895,
"s": 15891,
"text": "C++"
},
{
"code": null,
"e": 15899,
"s": 15895,
"text": "STL"
},
{
"code": null,
"e": 15903,
"s": 15899,
"text": "CPP"
},
{
"code": null,
"e": 16001,
"s": 15903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16028,
"s": 16001,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 16071,
"s": 16028,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16105,
"s": 16071,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 16130,
"s": 16105,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 16149,
"s": 16130,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 16203,
"s": 16149,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16243,
"s": 16203,
"text": "The C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 16267,
"s": 16243,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 16284,
"s": 16267,
"text": "Substring in C++"
}
]
|
Java Swing | JTable | 12 Oct, 2021
The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.Constructors in JTable:
JTable(): A table is created with empty cells.JTable(int rows, int cols): Creates a table of size rows * cols.JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.
JTable(): A table is created with empty cells.
JTable(int rows, int cols): Creates a table of size rows * cols.
JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.
Functions in JTable:
addColumn(TableColumn []column) : adds a column at the end of the JTable.clearSelection() : Selects all the selected rows and columns.editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position row, col in the JTable.
addColumn(TableColumn []column) : adds a column at the end of the JTable.
clearSelection() : Selects all the selected rows and columns.
editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.
setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position row, col in the JTable.
Below is the program to illustrate the various methods of JTable:
Java
// Packages to importimport javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTable; public class JTableExamples { // frame JFrame f; // Table JTable j; // Constructor JTableExamples() { // Frame initialization f = new JFrame(); // Frame Title f.setTitle("JTable Example"); // Data to be displayed in the JTable String[][] data = { { "Kundan Kumar Jha", "4031", "CSE" }, { "Anand Jha", "6014", "IT" } }; // Column Names String[] columnNames = { "Name", "Roll Number", "Department" }; // Initializing the JTable j = new JTable(data, columnNames); j.setBounds(30, 40, 200, 300); // adding it to JScrollPane JScrollPane sp = new JScrollPane(j); f.add(sp); // Frame Size f.setSize(500, 200); // Frame Visible = true f.setVisible(true); } // Driver method public static void main(String[] args) { new JTableExamples(); }}
Output:
surindertarika1234
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 297,
"s": 54,
"text": "The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form.Constructors in JTable: "
},
{
"code": null,
"e": 533,
"s": 297,
"text": "JTable(): A table is created with empty cells.JTable(int rows, int cols): Creates a table of size rows * cols.JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names."
},
{
"code": null,
"e": 580,
"s": 533,
"text": "JTable(): A table is created with empty cells."
},
{
"code": null,
"e": 645,
"s": 580,
"text": "JTable(int rows, int cols): Creates a table of size rows * cols."
},
{
"code": null,
"e": 771,
"s": 645,
"text": "JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names."
},
{
"code": null,
"e": 793,
"s": 771,
"text": "Functions in JTable: "
},
{
"code": null,
"e": 1235,
"s": 793,
"text": "addColumn(TableColumn []column) : adds a column at the end of the JTable.clearSelection() : Selects all the selected rows and columns.editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable.setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position row, col in the JTable."
},
{
"code": null,
"e": 1309,
"s": 1235,
"text": "addColumn(TableColumn []column) : adds a column at the end of the JTable."
},
{
"code": null,
"e": 1371,
"s": 1309,
"text": "clearSelection() : Selects all the selected rows and columns."
},
{
"code": null,
"e": 1563,
"s": 1371,
"text": "editCellAt(int row, int col) : edits the intersecting cell of the column number col and row number row programmatically, if the given indices are valid and the corresponding cell is editable."
},
{
"code": null,
"e": 1680,
"s": 1563,
"text": "setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the position row, col in the JTable."
},
{
"code": null,
"e": 1747,
"s": 1680,
"text": "Below is the program to illustrate the various methods of JTable: "
},
{
"code": null,
"e": 1752,
"s": 1747,
"text": "Java"
},
{
"code": "// Packages to importimport javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTable; public class JTableExamples { // frame JFrame f; // Table JTable j; // Constructor JTableExamples() { // Frame initialization f = new JFrame(); // Frame Title f.setTitle(\"JTable Example\"); // Data to be displayed in the JTable String[][] data = { { \"Kundan Kumar Jha\", \"4031\", \"CSE\" }, { \"Anand Jha\", \"6014\", \"IT\" } }; // Column Names String[] columnNames = { \"Name\", \"Roll Number\", \"Department\" }; // Initializing the JTable j = new JTable(data, columnNames); j.setBounds(30, 40, 200, 300); // adding it to JScrollPane JScrollPane sp = new JScrollPane(j); f.add(sp); // Frame Size f.setSize(500, 200); // Frame Visible = true f.setVisible(true); } // Driver method public static void main(String[] args) { new JTableExamples(); }}",
"e": 2795,
"s": 1752,
"text": null
},
{
"code": null,
"e": 2804,
"s": 2795,
"text": "Output: "
},
{
"code": null,
"e": 2823,
"s": 2804,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2834,
"s": 2823,
"text": "java-swing"
},
{
"code": null,
"e": 2839,
"s": 2834,
"text": "Java"
},
{
"code": null,
"e": 2844,
"s": 2839,
"text": "Java"
}
]
|
p5.js | keyReleased() Function | 27 Mar, 2020
The keyReleased() function is invoked whenever a key is called every time when a key is pressed. The most recently typed ASCII key is stored into the ‘key’ variable, however, it does not distinguish between uppercase and lowercase characters. The non-ASCII characters can be accessed in the ‘keyCode’ variable with their respective codes.
Different browsers may have their own default behavior attached to some of the keys. This can be prevented by adding “return false” to the end of the function.
Syntax:
keyReleased()
Parameters: This method does not accept any parameters.
Below examples illustrate the keyReleased() function in p5.js:
Example:
function setup() { createCanvas(600, 200); textSize(20); text("Press any key to check if " + "it is being pressed or " + "released", 10, 20);} function keyPressed() { clear(); textSize(20); text("Press any key to check if " + "it is being pressed or " + "released", 10, 20); textSize(30); text("You are pressing: " + key, 20, 100);} function keyReleased() { clear(); textSize(20); text("Press any key to check if " + "it is being pressed or " + "released", 10, 20); textSize(30); text("You released: " + key, 20, 100);}
Output:
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/keyReleased
JavaScript-p5.js
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": "\n27 Mar, 2020"
},
{
"code": null,
"e": 367,
"s": 28,
"text": "The keyReleased() function is invoked whenever a key is called every time when a key is pressed. The most recently typed ASCII key is stored into the ‘key’ variable, however, it does not distinguish between uppercase and lowercase characters. The non-ASCII characters can be accessed in the ‘keyCode’ variable with their respective codes."
},
{
"code": null,
"e": 527,
"s": 367,
"text": "Different browsers may have their own default behavior attached to some of the keys. This can be prevented by adding “return false” to the end of the function."
},
{
"code": null,
"e": 535,
"s": 527,
"text": "Syntax:"
},
{
"code": null,
"e": 549,
"s": 535,
"text": "keyReleased()"
},
{
"code": null,
"e": 605,
"s": 549,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 668,
"s": 605,
"text": "Below examples illustrate the keyReleased() function in p5.js:"
},
{
"code": null,
"e": 677,
"s": 668,
"text": "Example:"
},
{
"code": "function setup() { createCanvas(600, 200); textSize(20); text(\"Press any key to check if \" + \"it is being pressed or \" + \"released\", 10, 20);} function keyPressed() { clear(); textSize(20); text(\"Press any key to check if \" + \"it is being pressed or \" + \"released\", 10, 20); textSize(30); text(\"You are pressing: \" + key, 20, 100);} function keyReleased() { clear(); textSize(20); text(\"Press any key to check if \" + \"it is being pressed or \" + \"released\", 10, 20); textSize(30); text(\"You released: \" + key, 20, 100);}",
"e": 1279,
"s": 677,
"text": null
},
{
"code": null,
"e": 1287,
"s": 1279,
"text": "Output:"
},
{
"code": null,
"e": 1385,
"s": 1287,
"text": "Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 1440,
"s": 1385,
"text": "Reference: https://p5js.org/reference/#/p5/keyReleased"
},
{
"code": null,
"e": 1457,
"s": 1440,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1468,
"s": 1457,
"text": "JavaScript"
},
{
"code": null,
"e": 1485,
"s": 1468,
"text": "Web Technologies"
}
]
|
How to Dynamically Load Modules or Classes in Python | 27 Feb, 2020
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it.
Note: For more information, refer to Python Modules
Example: A simple example of importing a module is shown below in which, there are 2 files that are module.py and importing_mod.py in the same directory. The module.py file acts as a module to import_mod.py file.
module.py
# welcome method in the module def welcome(str): print("Hi ! % s Welcome to GfG" % str)
import_mod.py file
# importing module.py file import module as mod # running the welcome methodmod.welcome("User_1")
Output
Hi! User_1 Welcome to GfG
The modules added in the above code are importing modules statically i.e in compile time. In Python we can import modules dynamically by two ways
By using __import__() method: __import__() is a dunder method (methods of class starting and ending with double underscore also called magic method) and all classes own it. It is used to import a module or a class within the instance of a class. There is an example on this method given as follows, in which we will be importing a module dynamically. The module file is now modified as:module.py# class inside the moduleclass Welcome: def welcome(str): print("Hi ! % s Welcome to GfG" % str)Dynamic_import.pyclass Dimport: def __init__(self, module_name, class_name): #__import__ method used # to fetch module module = __import__(module_name) # getting attribute by # getattr() method my_class = getattr(module, class_name) my_class.welcome('User_1') # Driver Code obj = Dimport("module", "Welcome")OutputHi! User_1 Welcome to GfG
module.py
# class inside the moduleclass Welcome: def welcome(str): print("Hi ! % s Welcome to GfG" % str)
Dynamic_import.py
class Dimport: def __init__(self, module_name, class_name): #__import__ method used # to fetch module module = __import__(module_name) # getting attribute by # getattr() method my_class = getattr(module, class_name) my_class.welcome('User_1') # Driver Code obj = Dimport("module", "Welcome")
Output
Hi! User_1 Welcome to GfG
Using the imp module: Modules can be imported dynamically by the imp module in python. The example below is a demonstration on the using the imp module. It provides the find_module() method to find the module and the import_module() method to import it.Dynamic_import.pyimport impimport sys # dynamic import def dynamic_imp(name, class_name): # find_module() method is used # to find the module and return # its description and path try: fp, path, desc = imp.find_module(name) except ImportError: print ("module not found: " + name) try: # load_modules loads the module # dynamically ans takes the filepath # module and description as parameter example_package = imp.load_module(name, fp, path, desc) except Exception as e: print(e) try: myclass = imp.load_module("% s.% s" % (name, class_name), fp, path, desc) except Exception as e: print(e) return example_package, myclass # Driver codeif __name__ == "__main__": mod, modCl = dynamic_imp("GFG", "addNumbers") modCl.addNumbers(1, 2)OutputHi! User_1 Welcome to GfG
Dynamic_import.py
import impimport sys # dynamic import def dynamic_imp(name, class_name): # find_module() method is used # to find the module and return # its description and path try: fp, path, desc = imp.find_module(name) except ImportError: print ("module not found: " + name) try: # load_modules loads the module # dynamically ans takes the filepath # module and description as parameter example_package = imp.load_module(name, fp, path, desc) except Exception as e: print(e) try: myclass = imp.load_module("% s.% s" % (name, class_name), fp, path, desc) except Exception as e: print(e) return example_package, myclass # Driver codeif __name__ == "__main__": mod, modCl = dynamic_imp("GFG", "addNumbers") modCl.addNumbers(1, 2)
Output
Hi! User_1 Welcome to GfG
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it."
},
{
"code": null,
"e": 295,
"s": 243,
"text": "Note: For more information, refer to Python Modules"
},
{
"code": null,
"e": 508,
"s": 295,
"text": "Example: A simple example of importing a module is shown below in which, there are 2 files that are module.py and importing_mod.py in the same directory. The module.py file acts as a module to import_mod.py file."
},
{
"code": null,
"e": 518,
"s": 508,
"text": "module.py"
},
{
"code": "# welcome method in the module def welcome(str): print(\"Hi ! % s Welcome to GfG\" % str)",
"e": 609,
"s": 518,
"text": null
},
{
"code": null,
"e": 628,
"s": 609,
"text": "import_mod.py file"
},
{
"code": "# importing module.py file import module as mod # running the welcome methodmod.welcome(\"User_1\") ",
"e": 730,
"s": 628,
"text": null
},
{
"code": null,
"e": 737,
"s": 730,
"text": "Output"
},
{
"code": null,
"e": 763,
"s": 737,
"text": "Hi! User_1 Welcome to GfG"
},
{
"code": null,
"e": 909,
"s": 763,
"text": "The modules added in the above code are importing modules statically i.e in compile time. In Python we can import modules dynamically by two ways"
},
{
"code": null,
"e": 1808,
"s": 909,
"text": "By using __import__() method: __import__() is a dunder method (methods of class starting and ending with double underscore also called magic method) and all classes own it. It is used to import a module or a class within the instance of a class. There is an example on this method given as follows, in which we will be importing a module dynamically. The module file is now modified as:module.py# class inside the moduleclass Welcome: def welcome(str): print(\"Hi ! % s Welcome to GfG\" % str)Dynamic_import.pyclass Dimport: def __init__(self, module_name, class_name): #__import__ method used # to fetch module module = __import__(module_name) # getting attribute by # getattr() method my_class = getattr(module, class_name) my_class.welcome('User_1') # Driver Code obj = Dimport(\"module\", \"Welcome\")OutputHi! User_1 Welcome to GfG"
},
{
"code": null,
"e": 1818,
"s": 1808,
"text": "module.py"
},
{
"code": "# class inside the moduleclass Welcome: def welcome(str): print(\"Hi ! % s Welcome to GfG\" % str)",
"e": 1925,
"s": 1818,
"text": null
},
{
"code": null,
"e": 1943,
"s": 1925,
"text": "Dynamic_import.py"
},
{
"code": "class Dimport: def __init__(self, module_name, class_name): #__import__ method used # to fetch module module = __import__(module_name) # getting attribute by # getattr() method my_class = getattr(module, class_name) my_class.welcome('User_1') # Driver Code obj = Dimport(\"module\", \"Welcome\")",
"e": 2293,
"s": 1943,
"text": null
},
{
"code": null,
"e": 2300,
"s": 2293,
"text": "Output"
},
{
"code": null,
"e": 2326,
"s": 2300,
"text": "Hi! User_1 Welcome to GfG"
},
{
"code": null,
"e": 3626,
"s": 2326,
"text": "Using the imp module: Modules can be imported dynamically by the imp module in python. The example below is a demonstration on the using the imp module. It provides the find_module() method to find the module and the import_module() method to import it.Dynamic_import.pyimport impimport sys # dynamic import def dynamic_imp(name, class_name): # find_module() method is used # to find the module and return # its description and path try: fp, path, desc = imp.find_module(name) except ImportError: print (\"module not found: \" + name) try: # load_modules loads the module # dynamically ans takes the filepath # module and description as parameter example_package = imp.load_module(name, fp, path, desc) except Exception as e: print(e) try: myclass = imp.load_module(\"% s.% s\" % (name, class_name), fp, path, desc) except Exception as e: print(e) return example_package, myclass # Driver codeif __name__ == \"__main__\": mod, modCl = dynamic_imp(\"GFG\", \"addNumbers\") modCl.addNumbers(1, 2)OutputHi! User_1 Welcome to GfG"
},
{
"code": null,
"e": 3644,
"s": 3626,
"text": "Dynamic_import.py"
},
{
"code": "import impimport sys # dynamic import def dynamic_imp(name, class_name): # find_module() method is used # to find the module and return # its description and path try: fp, path, desc = imp.find_module(name) except ImportError: print (\"module not found: \" + name) try: # load_modules loads the module # dynamically ans takes the filepath # module and description as parameter example_package = imp.load_module(name, fp, path, desc) except Exception as e: print(e) try: myclass = imp.load_module(\"% s.% s\" % (name, class_name), fp, path, desc) except Exception as e: print(e) return example_package, myclass # Driver codeif __name__ == \"__main__\": mod, modCl = dynamic_imp(\"GFG\", \"addNumbers\") modCl.addNumbers(1, 2)",
"e": 4643,
"s": 3644,
"text": null
},
{
"code": null,
"e": 4650,
"s": 4643,
"text": "Output"
},
{
"code": null,
"e": 4676,
"s": 4650,
"text": "Hi! User_1 Welcome to GfG"
},
{
"code": null,
"e": 4691,
"s": 4676,
"text": "python-modules"
},
{
"code": null,
"e": 4698,
"s": 4691,
"text": "Python"
},
{
"code": null,
"e": 4796,
"s": 4698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4814,
"s": 4796,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4856,
"s": 4814,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4878,
"s": 4856,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4913,
"s": 4878,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4939,
"s": 4913,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4971,
"s": 4939,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5000,
"s": 4971,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5030,
"s": 5000,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5051,
"s": 5030,
"text": "Python OOPs Concepts"
}
]
|
Sum of squares of first n natural numbers | 28 May, 2022
Given n, find sum of squares of first n natural numbers. Examples :
Input : n = 2
Output : 5
Explanation: 1^2+2^2 = 5
Input : n = 8
Output : 204
Explanation :
1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 = 204
Naive approach : A naive approach will be to run a loop from 1 to n and sum up all the squares.
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to calculate// 1^2+2^2+3^2+...#include <iostream>using namespace std; // Function to calculate sumint summation(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driver codeint main(){ int n = 2; cout << summation(n); return 0;}
// C program to calculate// 1^2+2^2+3^2+...#include <stdio.h> // Function to calculate sumint summation(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driver codeint main(){ int n = 2; printf("%d",summation(n)); return 0;}
// Java program to calculate// 1^2+2^2+3^2+...import java.util.*;import java.lang.*; class GFG{ // Function to calculate sum public static int summation(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code public static void main(String args[]) { int n = 2; System.out.println(summation(n)); }} // This code is contributed// by Sachin Bisht
# Python3 program to# calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2+.. # Function to calculate seriesdef summation(n): return sum([i**2 for i in range(1, n + 1)]) # Driver Codeif __name__ == "__main__": n = 2 print(summation(n))
// C# program to calculate// 1^2+2^2+3^2+...using System;class GFG{ // Function to calculate sum public static int summation(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code public static void Main() { int n = 2; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m
<?php// PHP program to calculate// 1^2+2^2+3^2+... // Function to calculate sumfunction summation($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += ($i * $i); return $sum;} // Driver code $n = 2; echo summation($n); // This code is contributed by aj_36?>
<script>// JavaScript program to calculate// 1^2+2^2+3^2+... // Function to calculate sum function summation(n) { let sum = 0; for (let i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code let n = 2; document.write(summation(n)); // This code is contributed by Surbhi Tyagi </script>
Output :
5
Time Complexity: O(n)Auxiliary Space: O(1)
Efficient Approach : There exists a formula for finding the sum of squares of first n numbers. 1 + 2 + ........... + n = n(n+1) / 2 12 + 22 + ......... + n2 = n(n+1)(2n+1) / 6
n * (n + 1) * (2*n + 1) / 6
Example : n = 3
= 3 * (3 + 1) * (2*3 + 1) / 6
= (3 * 4 * 7) / 6
= 84 / 6
= 14
How does this work?
We can prove this formula using induction.
We can easily see that the formula is true for
n = 1 and n = 2 as sums are 1 and 5 respectively.
Let it be true for n = k-1. So sum of k-1 numbers
is (k - 1) * k * (2 * k - 1)) / 6
In the following steps, we show that it is true
for k assuming that it is true for k-1.
Sum of k numbers = Sum of k-1 numbers + k2
= (k - 1) * k * (2 * k - 1) / 6 + k2
= ((k2 - k) * (2*k - 1) + 6k2)/6
= (2k3 - 2k2 - k2 + k + 6k2)/6
= (2k3 + 3k2 + k)/6
= k * (k + 1) * (2*k + 1) / 6
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to get the sum// of the following series#include <iostream>using namespace std; // Function calculating// the seriesint summation(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; cout << summation(n) << endl; return 0;} // This code is contributed by shubhamsingh10
// C program to get the sum// of the following series#include <stdio.h> // Function calculating// the seriesint summation(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; printf("%d", summation(n)); return 0;}
// Java program to get// the sum of the seriesimport java.util.*;import java.lang.*; class GFG{ // Function calculating // the series public static int summation(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void main(String args[]) { int n = 10; System.out.println(summation(n)); }} // This code is contributed// by Sachin Bisht
# Python code to find sum of# squares of first n natural numbers.def summation(n): return (n * (n + 1) * (2 * n + 1)) / 6 # Driver Codeif __name__ == '__main__': n = 10 print(summation(n))
// C# program to get the sum// of the seriesusing System; class GFG{ // Function calculating // the series public static int summation(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m
<?php// PHP program to get the// sum of the following series // Function calculating// the seriesfunction summation($n){ return ($n * ($n + 1) * (2 * $n + 1)) / 6;} // Driver Code$n = 10;echo summation($n); // This code is contributed by aj_36?>
<p id="demo"></p> <script>var x = summation(10);document.getElementById("demo").innerHTML = x; function summation(n) { return (n * (n + 1) * (2 * n + 1)) / 6;}</script>
Output :
385
Time Complexity: O(1)Auxiliary Space: O(1)
jit_t
SHUBHAMSINGH10
Akanksha_Rai
surbhityagi15
sravankumar8128
kothavvsaakash
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 122,
"s": 52,
"text": "Given n, find sum of squares of first n natural numbers. Examples : "
},
{
"code": null,
"e": 268,
"s": 122,
"text": "Input : n = 2\nOutput : 5\nExplanation: 1^2+2^2 = 5\n\nInput : n = 8\nOutput : 204\nExplanation : \n1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 = 204 "
},
{
"code": null,
"e": 368,
"s": 270,
"text": "Naive approach : A naive approach will be to run a loop from 1 to n and sum up all the squares. "
},
{
"code": null,
"e": 372,
"s": 368,
"text": "C++"
},
{
"code": null,
"e": 374,
"s": 372,
"text": "C"
},
{
"code": null,
"e": 379,
"s": 374,
"text": "Java"
},
{
"code": null,
"e": 387,
"s": 379,
"text": "Python3"
},
{
"code": null,
"e": 390,
"s": 387,
"text": "C#"
},
{
"code": null,
"e": 394,
"s": 390,
"text": "PHP"
},
{
"code": null,
"e": 405,
"s": 394,
"text": "Javascript"
},
{
"code": "// CPP program to calculate// 1^2+2^2+3^2+...#include <iostream>using namespace std; // Function to calculate sumint summation(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driver codeint main(){ int n = 2; cout << summation(n); return 0;}",
"e": 707,
"s": 405,
"text": null
},
{
"code": "// C program to calculate// 1^2+2^2+3^2+...#include <stdio.h> // Function to calculate sumint summation(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum;} // Driver codeint main(){ int n = 2; printf(\"%d\",summation(n)); return 0;}",
"e": 992,
"s": 707,
"text": null
},
{
"code": "// Java program to calculate// 1^2+2^2+3^2+...import java.util.*;import java.lang.*; class GFG{ // Function to calculate sum public static int summation(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code public static void main(String args[]) { int n = 2; System.out.println(summation(n)); }} // This code is contributed// by Sachin Bisht",
"e": 1448,
"s": 992,
"text": null
},
{
"code": "# Python3 program to# calculate 1 ^ 2 + 2 ^ 2 + 3 ^ 2+.. # Function to calculate seriesdef summation(n): return sum([i**2 for i in range(1, n + 1)]) # Driver Codeif __name__ == \"__main__\": n = 2 print(summation(n))",
"e": 1686,
"s": 1448,
"text": null
},
{
"code": "// C# program to calculate// 1^2+2^2+3^2+...using System;class GFG{ // Function to calculate sum public static int summation(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code public static void Main() { int n = 2; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m",
"e": 2092,
"s": 1686,
"text": null
},
{
"code": "<?php// PHP program to calculate// 1^2+2^2+3^2+... // Function to calculate sumfunction summation($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum += ($i * $i); return $sum;} // Driver code $n = 2; echo summation($n); // This code is contributed by aj_36?>",
"e": 2380,
"s": 2092,
"text": null
},
{
"code": "<script>// JavaScript program to calculate// 1^2+2^2+3^2+... // Function to calculate sum function summation(n) { let sum = 0; for (let i = 1; i <= n; i++) sum += (i * i); return sum; } // Driver code let n = 2; document.write(summation(n)); // This code is contributed by Surbhi Tyagi </script>",
"e": 2737,
"s": 2380,
"text": null
},
{
"code": null,
"e": 2748,
"s": 2737,
"text": "Output : "
},
{
"code": null,
"e": 2750,
"s": 2748,
"text": "5"
},
{
"code": null,
"e": 2793,
"s": 2750,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2970,
"s": 2793,
"text": "Efficient Approach : There exists a formula for finding the sum of squares of first n numbers. 1 + 2 + ........... + n = n(n+1) / 2 12 + 22 + ......... + n2 = n(n+1)(2n+1) / 6 "
},
{
"code": null,
"e": 3109,
"s": 2970,
"text": "n * (n + 1) * (2*n + 1) / 6\n\nExample : n = 3\n = 3 * (3 + 1) * (2*3 + 1) / 6\n = (3 * 4 * 7) / 6\n = 84 / 6\n = 14"
},
{
"code": null,
"e": 3131,
"s": 3109,
"text": "How does this work? "
},
{
"code": null,
"e": 3696,
"s": 3131,
"text": "We can prove this formula using induction.\nWe can easily see that the formula is true for\nn = 1 and n = 2 as sums are 1 and 5 respectively.\n\nLet it be true for n = k-1. So sum of k-1 numbers\nis (k - 1) * k * (2 * k - 1)) / 6\n\nIn the following steps, we show that it is true \nfor k assuming that it is true for k-1.\n\nSum of k numbers = Sum of k-1 numbers + k2\n = (k - 1) * k * (2 * k - 1) / 6 + k2\n = ((k2 - k) * (2*k - 1) + 6k2)/6\n = (2k3 - 2k2 - k2 + k + 6k2)/6\n = (2k3 + 3k2 + k)/6\n = k * (k + 1) * (2*k + 1) / 6"
},
{
"code": null,
"e": 3702,
"s": 3698,
"text": "C++"
},
{
"code": null,
"e": 3704,
"s": 3702,
"text": "C"
},
{
"code": null,
"e": 3709,
"s": 3704,
"text": "Java"
},
{
"code": null,
"e": 3717,
"s": 3709,
"text": "Python3"
},
{
"code": null,
"e": 3720,
"s": 3717,
"text": "C#"
},
{
"code": null,
"e": 3724,
"s": 3720,
"text": "PHP"
},
{
"code": null,
"e": 3735,
"s": 3724,
"text": "Javascript"
},
{
"code": "// C++ program to get the sum// of the following series#include <iostream>using namespace std; // Function calculating// the seriesint summation(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; cout << summation(n) << endl; return 0;} // This code is contributed by shubhamsingh10",
"e": 4073,
"s": 3735,
"text": null
},
{
"code": "// C program to get the sum// of the following series#include <stdio.h> // Function calculating// the seriesint summation(int n){ return (n * (n + 1) * (2 * n + 1)) / 6;} // Driver Codeint main(){ int n = 10; printf(\"%d\", summation(n)); return 0;}",
"e": 4343,
"s": 4073,
"text": null
},
{
"code": "// Java program to get// the sum of the seriesimport java.util.*;import java.lang.*; class GFG{ // Function calculating // the series public static int summation(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void main(String args[]) { int n = 10; System.out.println(summation(n)); }} // This code is contributed// by Sachin Bisht",
"e": 4770,
"s": 4343,
"text": null
},
{
"code": "# Python code to find sum of# squares of first n natural numbers.def summation(n): return (n * (n + 1) * (2 * n + 1)) / 6 # Driver Codeif __name__ == '__main__': n = 10 print(summation(n))",
"e": 4982,
"s": 4770,
"text": null
},
{
"code": "// C# program to get the sum// of the seriesusing System; class GFG{ // Function calculating // the series public static int summation(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(summation(n)); }} // This code is contributed by vt_m",
"e": 5360,
"s": 4982,
"text": null
},
{
"code": "<?php// PHP program to get the// sum of the following series // Function calculating// the seriesfunction summation($n){ return ($n * ($n + 1) * (2 * $n + 1)) / 6;} // Driver Code$n = 10;echo summation($n); // This code is contributed by aj_36?>",
"e": 5619,
"s": 5360,
"text": null
},
{
"code": "<p id=\"demo\"></p> <script>var x = summation(10);document.getElementById(\"demo\").innerHTML = x; function summation(n) { return (n * (n + 1) * (2 * n + 1)) / 6;}</script>",
"e": 5799,
"s": 5619,
"text": null
},
{
"code": null,
"e": 5810,
"s": 5799,
"text": "Output : "
},
{
"code": null,
"e": 5814,
"s": 5810,
"text": "385"
},
{
"code": null,
"e": 5858,
"s": 5814,
"text": "Time Complexity: O(1)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5864,
"s": 5858,
"text": "jit_t"
},
{
"code": null,
"e": 5879,
"s": 5864,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 5892,
"s": 5879,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5906,
"s": 5892,
"text": "surbhityagi15"
},
{
"code": null,
"e": 5922,
"s": 5906,
"text": "sravankumar8128"
},
{
"code": null,
"e": 5937,
"s": 5922,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 5951,
"s": 5937,
"text": "number-theory"
},
{
"code": null,
"e": 5958,
"s": 5951,
"text": "series"
},
{
"code": null,
"e": 5971,
"s": 5958,
"text": "Mathematical"
},
{
"code": null,
"e": 5985,
"s": 5971,
"text": "number-theory"
},
{
"code": null,
"e": 5998,
"s": 5985,
"text": "Mathematical"
},
{
"code": null,
"e": 6005,
"s": 5998,
"text": "series"
},
{
"code": null,
"e": 6103,
"s": 6005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6127,
"s": 6103,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 6148,
"s": 6127,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 6162,
"s": 6148,
"text": "Prime Numbers"
},
{
"code": null,
"e": 6215,
"s": 6162,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 6252,
"s": 6215,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 6295,
"s": 6252,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 6327,
"s": 6295,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 6368,
"s": 6327,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 6395,
"s": 6368,
"text": "Modulo 10^9+7 (1000000007)"
}
]
|
How to get seconds since epoch in JavaScript? | 14 May, 2020
Given a date, we have to find the number of seconds since the epoch (i.e. 1 January 1970, 00:00:00 UTC ). The getTime() method in the JavaScript returns the number of milliseconds since January 1, 1970, or epoch. If we divide these milliseconds by 1000 and then integer part will give us the number of seconds since epoch.
Example:
Input: Date = 27-04-2020, 11:55:55
Output: Seconds since epoch - 1587968755
Syntax:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:
<script type="text/javascript"> function seconds_since_epoch(d){ return Math.floor( d / 1000 ); } // Driver Code var d = new Date(2020, 4, 29, 22, 00, 00, 00); var sec = seconds_since_epoch(d); document.write("Date " + d + " has " + sec+ " seconds till epoch.");</script>
Output:
Date Fri May 29 2020 22:00:00 GMT+0530 (India Standard Time)
has 1590769800 seconds till epoch.
javascript-date
Picked
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "Given a date, we have to find the number of seconds since the epoch (i.e. 1 January 1970, 00:00:00 UTC ). The getTime() method in the JavaScript returns the number of milliseconds since January 1, 1970, or epoch. If we divide these milliseconds by 1000 and then integer part will give us the number of seconds since epoch."
},
{
"code": null,
"e": 360,
"s": 351,
"text": "Example:"
},
{
"code": null,
"e": 437,
"s": 360,
"text": "Input: Date = 27-04-2020, 11:55:55\nOutput: Seconds since epoch - 1587968755\n"
},
{
"code": null,
"e": 445,
"s": 437,
"text": "Syntax:"
},
{
"code": null,
"e": 511,
"s": 445,
"text": "new Date(year, month, day, hours, minutes, seconds, milliseconds)"
},
{
"code": null,
"e": 520,
"s": 511,
"text": "Example:"
},
{
"code": "<script type=\"text/javascript\"> function seconds_since_epoch(d){ return Math.floor( d / 1000 ); } // Driver Code var d = new Date(2020, 4, 29, 22, 00, 00, 00); var sec = seconds_since_epoch(d); document.write(\"Date \" + d + \" has \" + sec+ \" seconds till epoch.\");</script> ",
"e": 864,
"s": 520,
"text": null
},
{
"code": null,
"e": 872,
"s": 864,
"text": "Output:"
},
{
"code": null,
"e": 969,
"s": 872,
"text": "Date Fri May 29 2020 22:00:00 GMT+0530 (India Standard Time) \nhas 1590769800 seconds till epoch."
},
{
"code": null,
"e": 985,
"s": 969,
"text": "javascript-date"
},
{
"code": null,
"e": 992,
"s": 985,
"text": "Picked"
},
{
"code": null,
"e": 1009,
"s": 992,
"text": "Web Technologies"
},
{
"code": null,
"e": 1036,
"s": 1009,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1134,
"s": 1036,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1196,
"s": 1134,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1229,
"s": 1196,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1290,
"s": 1229,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1340,
"s": 1290,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1383,
"s": 1340,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1416,
"s": 1383,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1466,
"s": 1416,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1506,
"s": 1466,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1566,
"s": 1506,
"text": "How to set the default value for an HTML <select> element ?"
}
]
|
cmd | Dir command | 21 Jun, 2022
Dir is a command found inside the windows command processor (cmd.exe) that is generally used for listing the directories and files within the current directory. The command by itself is really basic, but the presence of its extensive switches makes it quite a dynamic command that has several use cases. It is one of the most useful commands while navigating the command line, and is present in its different forms in several operating systems. In this article, we will take a look at the Dir command, and would learn several use cases for it.
Description of the command :
help dir
Output :
Displays a list of files and subdirectories in a directory.
DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]
[drive:][path][filename]
Specifies drive, directory, and/or files to list.
/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points O Offline files
- Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
.
.
Usage of the command : The command is mainly used for displaying the list of files and subdirectories in a directory. This could be done by executing the Dir command without any arguments.
Dir
which would produce an output similar to this. Output :
Volume in drive C has no label.
Volume Serial Number is 2C7D-7820
Directory of C:\Users
09/26/2020 11:34 AM <DIR> .
09/26/2020 11:34 AM <DIR> ..
09/02/2020 07:07 PM 1, 000 applese
09/24/2020 08:59 PM <DIR> Public
10/20/2020 06:39 PM <DIR> Soap
1 File(s) 1, 000 bytes
4 Dir(s) 13, 879, 459, 840 bytes free
This would serve the purpose for most users, but the command offers more functionality than this, By appending various switches we could modify the working of the command, to produce custom output. We would be looking over at some of the commonly used switches of the command. Displaying files/subdirectories having certain attributes : You can filter the output of dir by sending/A switch, followed by a specific attribute. What this will do is it will display only those files/folders which do have the provided attributes. The command would have the following syntax as follows.
Dir /A[attribute]
Where attribute will be a one/combination of one of the characters from the following list
D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points O Offline files
- Prefix meaning not
According to the above list, If you want to display a list of Directories only. You can use the given below command.
Dir /AD
Which will display a list of subdirectories (Junction Points & Directory Symlinks as well) within the current directory. Displaying file/subdirectories of a directory using its absolute/relative path : You can get the list of file/subdirectories of now only the current directory, but other directories as well. If you provide the full path to the directory you can execute the dir command on that directory. The syntax would be as follows :
Dir [Path to the Directory]
Where Path to the Directory is either Relative or a full path to the Directory that we are interested in. For getting the contents of “C:\Users\Public” directory, the command would be :
Dir "C:\Users\Public"
It should be noted, that if the path to a file is provided as an argument, then only information regarding that file would be displayed. Sorting the output of Dir command : You can sort the list of files/folders in the output of dir command using the /O switch. The switch takes one/combination of these characters to produce a sorted output.
N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
According to the above list, if you want the output to be sorted by the size of files (in descending order). The command syntax would be as follows.
Dir /O-S
Which would produce an output where the files having larger size would be at the top of the list, and smaller files/folder at the bottom. Note – In general, Directories would be at the bottom, as they aren’t as generally fixed size (existing as file table entry), as opposed to a file. Displaying output of Dir command in minimal format : The output of the dir command contains way too much information than what one may be interested in. In order to display the output of Dir command, in a bare format we can append /B switch to it. This will remove additional information such as Time of modification, Sizes, Types, etc. from the list of entries. The command syntax would be as follows.
Dir /B
Example – Consider if a directory has the following content. Then running the Dir command on the directory would produce the following output.
Volume in drive C has no label.
Volume Serial Number is 2C7D-7820
Directory of C:\Users\Sauleyayan\Pictures\Screenshots
10/21/2020 11:37 AM <DIR> .
10/21/2020 11:37 AM <DIR> ..
10/21/2020 11:12 AM 1, 240, 912 2020-10-21 11꞉12꞉23.png
10/21/2020 11:37 AM 1, 376, 105 2020-10-21 11꞉37꞉04.png
10/04/2020 10:10 AM <DIR> OLD SCREENSHOTS
10/19/2020 06:18 PM 287 UNUPLOADABLE_SCREENSHOTS.txt
3 File(s) 2, 617, 304 bytes
3 Dir(s) 12, 749, 389, 824 bytes free
While running the Dir command with /B switch would produce
2020-10-21 11꞉12꞉23.png
2020-10-21 11꞉37꞉04.png
OLD SCREENSHOTS
UNUPLOADABLE_SCREENSHOTS.txt
Which is easier to read for most users. Note –
There exists more switches for the command, which could be found out at the help page of the command.
If the path to a directory/file is provided for displaying its contents, switches should be added after the before providing the path. Creating a syntax such as –
Dir [switches] [Path to the Directory/File]
Dir is an internal command
surinderdawra388
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Allocation Methods
Memory Management in Operating System
Different approaches or Structures of Operating Systems
Logical and Physical Address in Operating System
Segmentation in Operating System
Structures of Directory in Operating System
Difference between Internal and External fragmentation
Process Table and Process Control Block (PCB)
Introduction of System Call
Deadlock Detection And Recovery | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 588,
"s": 28,
"text": "Dir is a command found inside the windows command processor (cmd.exe) that is generally used for listing the directories and files within the current directory. The command by itself is really basic, but the presence of its extensive switches makes it quite a dynamic command that has several use cases. It is one of the most useful commands while navigating the command line, and is present in its different forms in several operating systems. In this article, we will take a look at the Dir command, and would learn several use cases for it. "
},
{
"code": null,
"e": 617,
"s": 588,
"text": "Description of the command :"
},
{
"code": null,
"e": 626,
"s": 617,
"text": "help dir"
},
{
"code": null,
"e": 635,
"s": 626,
"text": "Output :"
},
{
"code": null,
"e": 1441,
"s": 635,
"text": "Displays a list of files and subdirectories in a directory.\n\nDIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]\n [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]\n\n [drive:][path][filename]\n Specifies drive, directory, and/or files to list.\n\n /A Displays files with specified attributes.\n attributes D Directories R Read-only files\n H Hidden files A Files ready for archiving\n S System files I Not content indexed files\n L Reparse Points O Offline files\n - Prefix meaning not\n /B Uses bare format (no heading information or summary).\n /C Display the thousand separator in file sizes. This is the\n .\n ."
},
{
"code": null,
"e": 1630,
"s": 1441,
"text": "Usage of the command : The command is mainly used for displaying the list of files and subdirectories in a directory. This could be done by executing the Dir command without any arguments."
},
{
"code": null,
"e": 1634,
"s": 1630,
"text": "Dir"
},
{
"code": null,
"e": 1690,
"s": 1634,
"text": "which would produce an output similar to this. Output :"
},
{
"code": null,
"e": 2100,
"s": 1690,
"text": "Volume in drive C has no label.\nVolume Serial Number is 2C7D-7820\n\nDirectory of C:\\Users\n\n09/26/2020 11:34 AM <DIR> .\n09/26/2020 11:34 AM <DIR> ..\n09/02/2020 07:07 PM 1, 000 applese\n09/24/2020 08:59 PM <DIR> Public\n10/20/2020 06:39 PM <DIR> Soap\n 1 File(s) 1, 000 bytes\n 4 Dir(s) 13, 879, 459, 840 bytes free"
},
{
"code": null,
"e": 2682,
"s": 2100,
"text": "This would serve the purpose for most users, but the command offers more functionality than this, By appending various switches we could modify the working of the command, to produce custom output. We would be looking over at some of the commonly used switches of the command. Displaying files/subdirectories having certain attributes : You can filter the output of dir by sending/A switch, followed by a specific attribute. What this will do is it will display only those files/folders which do have the provided attributes. The command would have the following syntax as follows."
},
{
"code": null,
"e": 2700,
"s": 2682,
"text": "Dir /A[attribute]"
},
{
"code": null,
"e": 2791,
"s": 2700,
"text": "Where attribute will be a one/combination of one of the characters from the following list"
},
{
"code": null,
"e": 3097,
"s": 2791,
"text": " D Directories R Read-only files\n H Hidden files A Files ready for archiving\n S System files I Not content indexed files\n L Reparse Points O Offline files\n - Prefix meaning not"
},
{
"code": null,
"e": 3214,
"s": 3097,
"text": "According to the above list, If you want to display a list of Directories only. You can use the given below command."
},
{
"code": null,
"e": 3222,
"s": 3214,
"text": "Dir /AD"
},
{
"code": null,
"e": 3664,
"s": 3222,
"text": "Which will display a list of subdirectories (Junction Points & Directory Symlinks as well) within the current directory. Displaying file/subdirectories of a directory using its absolute/relative path : You can get the list of file/subdirectories of now only the current directory, but other directories as well. If you provide the full path to the directory you can execute the dir command on that directory. The syntax would be as follows :"
},
{
"code": null,
"e": 3692,
"s": 3664,
"text": "Dir [Path to the Directory]"
},
{
"code": null,
"e": 3878,
"s": 3692,
"text": "Where Path to the Directory is either Relative or a full path to the Directory that we are interested in. For getting the contents of “C:\\Users\\Public” directory, the command would be :"
},
{
"code": null,
"e": 3900,
"s": 3878,
"text": "Dir \"C:\\Users\\Public\""
},
{
"code": null,
"e": 4243,
"s": 3900,
"text": "It should be noted, that if the path to a file is provided as an argument, then only information regarding that file would be displayed. Sorting the output of Dir command : You can sort the list of files/folders in the output of dir command using the /O switch. The switch takes one/combination of these characters to produce a sorted output."
},
{
"code": null,
"e": 4461,
"s": 4243,
"text": " N By name (alphabetic) S By size (smallest first)\n E By extension (alphabetic) D By date/time (oldest first)\n G Group directories first - Prefix to reverse order"
},
{
"code": null,
"e": 4610,
"s": 4461,
"text": "According to the above list, if you want the output to be sorted by the size of files (in descending order). The command syntax would be as follows."
},
{
"code": null,
"e": 4619,
"s": 4610,
"text": "Dir /O-S"
},
{
"code": null,
"e": 5308,
"s": 4619,
"text": "Which would produce an output where the files having larger size would be at the top of the list, and smaller files/folder at the bottom. Note – In general, Directories would be at the bottom, as they aren’t as generally fixed size (existing as file table entry), as opposed to a file. Displaying output of Dir command in minimal format : The output of the dir command contains way too much information than what one may be interested in. In order to display the output of Dir command, in a bare format we can append /B switch to it. This will remove additional information such as Time of modification, Sizes, Types, etc. from the list of entries. The command syntax would be as follows."
},
{
"code": null,
"e": 5315,
"s": 5308,
"text": "Dir /B"
},
{
"code": null,
"e": 5459,
"s": 5315,
"text": "Example – Consider if a directory has the following content. Then running the Dir command on the directory would produce the following output."
},
{
"code": null,
"e": 6017,
"s": 5459,
"text": "Volume in drive C has no label.\nVolume Serial Number is 2C7D-7820\n\nDirectory of C:\\Users\\Sauleyayan\\Pictures\\Screenshots\n\n10/21/2020 11:37 AM <DIR> .\n10/21/2020 11:37 AM <DIR> ..\n10/21/2020 11:12 AM 1, 240, 912 2020-10-21 11꞉12꞉23.png\n10/21/2020 11:37 AM 1, 376, 105 2020-10-21 11꞉37꞉04.png\n10/04/2020 10:10 AM <DIR> OLD SCREENSHOTS\n10/19/2020 06:18 PM 287 UNUPLOADABLE_SCREENSHOTS.txt\n 3 File(s) 2, 617, 304 bytes\n 3 Dir(s) 12, 749, 389, 824 bytes free"
},
{
"code": null,
"e": 6076,
"s": 6017,
"text": "While running the Dir command with /B switch would produce"
},
{
"code": null,
"e": 6169,
"s": 6076,
"text": "2020-10-21 11꞉12꞉23.png\n2020-10-21 11꞉37꞉04.png\nOLD SCREENSHOTS\nUNUPLOADABLE_SCREENSHOTS.txt"
},
{
"code": null,
"e": 6216,
"s": 6169,
"text": "Which is easier to read for most users. Note –"
},
{
"code": null,
"e": 6318,
"s": 6216,
"text": "There exists more switches for the command, which could be found out at the help page of the command."
},
{
"code": null,
"e": 6486,
"s": 6318,
"text": "If the path to a directory/file is provided for displaying its contents, switches should be added after the before providing the path. Creating a syntax such as –"
},
{
"code": null,
"e": 6530,
"s": 6486,
"text": "Dir [switches] [Path to the Directory/File]"
},
{
"code": null,
"e": 6557,
"s": 6530,
"text": "Dir is an internal command"
},
{
"code": null,
"e": 6574,
"s": 6557,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6592,
"s": 6574,
"text": "Operating Systems"
},
{
"code": null,
"e": 6610,
"s": 6592,
"text": "Operating Systems"
},
{
"code": null,
"e": 6708,
"s": 6610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6732,
"s": 6708,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 6770,
"s": 6732,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 6826,
"s": 6770,
"text": "Different approaches or Structures of Operating Systems"
},
{
"code": null,
"e": 6875,
"s": 6826,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 6908,
"s": 6875,
"text": "Segmentation in Operating System"
},
{
"code": null,
"e": 6952,
"s": 6908,
"text": "Structures of Directory in Operating System"
},
{
"code": null,
"e": 7007,
"s": 6952,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 7053,
"s": 7007,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 7081,
"s": 7053,
"text": "Introduction of System Call"
}
]
|
Methods of Ordered Dictionary in Python | 16 Feb, 2022
An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has characteristics of both into one. Like queue, it remembers the order and it also allows insertion and deletion at both ends. And like a dictionary, it also behaves like a hash map.
Note: From Python 3.6 onwards, the order is retained for keyword arguments passed to the OrderedDict constructor, refer to PEP-468.
Let’s look at various methods offered by the ordered dictionary.
popitem():
This method is used to delete a key from the beginning.
Syntax:
popitem(last = True)
If the last is False then this method would delete a key from the beginning of the dictionary. This serves as FIFO(First In First Out) in the queue otherwise it method would delete the key from the end of the dictionary.
Time Complexity: O(1).
For Better Understanding have a look at the code.
Python3
from collections import OrderedDict ord_dict = OrderedDict().fromkeys('GeeksForGeeks')print("Original Dictionary")print(ord_dict) # Pop the key from lastord_dict.popitem()print("\nAfter Deleting Last item :")print(ord_dict) # Pop the key from beginningord_dict.popitem(last = False)print("\nAfter Deleting Key from Beginning :")print(ord_dict)
Output:
Original Dictionary OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])After Deleting Last item : OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])After Deleting Key from Beginning : OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])
move_to_end():
This method is used to move an existing key of the dictionary either to the end or to the beginning. There are two versions of this function –
Syntax:
move_to_end(key, last = True)
If the last is True then this method would move an existing key of the dictionary in the end otherwise it would move an existing key of the dictionary in the beginning. If the key is moved at the beginning then it serves as FIFO ( First In First Out ) in a queue.
Time Complexity: O(1)
Python3
from collections import OrderedDict ord_dict = OrderedDict().fromkeys('GeeksForGeeks')print("Original Dictionary")print(ord_dict) # Move the key to endord_dict.move_to_end('G')print("\nAfter moving key 'G' to end of dictionary :")print(ord_dict) # Move the key to beginningord_dict.move_to_end('k', last = False)print("\nAfter moving Key in the Beginning :")print(ord_dict)
Output:
Original Dictionary OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])After moving key ‘G’ to end of dictionary : OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])After moving Key in the Beginning : OrderedDict([(‘k’, None), (‘e’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])
Working of move_to_end() function
Basically, this method looks up a link in a linked list in a dictionary self.__map and updates the previous and next pointers for the link and its neighbors. It deletes that element from its position and adds it to the end or beginning depending upon parameter value. Since all of the operations below take constant time, the complexity of OrderedDict.move_to_end() is constant as well.
arorakashish0911
kumaripunam984122
Python collections-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 579,
"s": 52,
"text": "An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has characteristics of both into one. Like queue, it remembers the order and it also allows insertion and deletion at both ends. And like a dictionary, it also behaves like a hash map. "
},
{
"code": null,
"e": 712,
"s": 579,
"text": "Note: From Python 3.6 onwards, the order is retained for keyword arguments passed to the OrderedDict constructor, refer to PEP-468. "
},
{
"code": null,
"e": 778,
"s": 712,
"text": "Let’s look at various methods offered by the ordered dictionary. "
},
{
"code": null,
"e": 789,
"s": 778,
"text": "popitem():"
},
{
"code": null,
"e": 845,
"s": 789,
"text": "This method is used to delete a key from the beginning."
},
{
"code": null,
"e": 853,
"s": 845,
"text": "Syntax:"
},
{
"code": null,
"e": 896,
"s": 853,
"text": "popitem(last = True) "
},
{
"code": null,
"e": 1117,
"s": 896,
"text": "If the last is False then this method would delete a key from the beginning of the dictionary. This serves as FIFO(First In First Out) in the queue otherwise it method would delete the key from the end of the dictionary."
},
{
"code": null,
"e": 1140,
"s": 1117,
"text": "Time Complexity: O(1)."
},
{
"code": null,
"e": 1190,
"s": 1140,
"text": "For Better Understanding have a look at the code."
},
{
"code": null,
"e": 1198,
"s": 1190,
"text": "Python3"
},
{
"code": "from collections import OrderedDict ord_dict = OrderedDict().fromkeys('GeeksForGeeks')print(\"Original Dictionary\")print(ord_dict) # Pop the key from lastord_dict.popitem()print(\"\\nAfter Deleting Last item :\")print(ord_dict) # Pop the key from beginningord_dict.popitem(last = False)print(\"\\nAfter Deleting Key from Beginning :\")print(ord_dict)",
"e": 1543,
"s": 1198,
"text": null
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Output:"
},
{
"code": null,
"e": 1908,
"s": 1551,
"text": "Original Dictionary OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])After Deleting Last item : OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])After Deleting Key from Beginning : OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])"
},
{
"code": null,
"e": 1923,
"s": 1908,
"text": "move_to_end():"
},
{
"code": null,
"e": 2067,
"s": 1923,
"text": "This method is used to move an existing key of the dictionary either to the end or to the beginning. There are two versions of this function – "
},
{
"code": null,
"e": 2075,
"s": 2067,
"text": "Syntax:"
},
{
"code": null,
"e": 2105,
"s": 2075,
"text": "move_to_end(key, last = True)"
},
{
"code": null,
"e": 2369,
"s": 2105,
"text": "If the last is True then this method would move an existing key of the dictionary in the end otherwise it would move an existing key of the dictionary in the beginning. If the key is moved at the beginning then it serves as FIFO ( First In First Out ) in a queue."
},
{
"code": null,
"e": 2392,
"s": 2369,
"text": "Time Complexity: O(1) "
},
{
"code": null,
"e": 2400,
"s": 2392,
"text": "Python3"
},
{
"code": "from collections import OrderedDict ord_dict = OrderedDict().fromkeys('GeeksForGeeks')print(\"Original Dictionary\")print(ord_dict) # Move the key to endord_dict.move_to_end('G')print(\"\\nAfter moving key 'G' to end of dictionary :\")print(ord_dict) # Move the key to beginningord_dict.move_to_end('k', last = False)print(\"\\nAfter moving Key in the Beginning :\")print(ord_dict)",
"e": 2776,
"s": 2400,
"text": null
},
{
"code": null,
"e": 2784,
"s": 2776,
"text": "Output:"
},
{
"code": null,
"e": 3197,
"s": 2784,
"text": "Original Dictionary OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])After moving key ‘G’ to end of dictionary : OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])After moving Key in the Beginning : OrderedDict([(‘k’, None), (‘e’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])"
},
{
"code": null,
"e": 3231,
"s": 3197,
"text": "Working of move_to_end() function"
},
{
"code": null,
"e": 3620,
"s": 3231,
"text": "Basically, this method looks up a link in a linked list in a dictionary self.__map and updates the previous and next pointers for the link and its neighbors. It deletes that element from its position and adds it to the end or beginning depending upon parameter value. Since all of the operations below take constant time, the complexity of OrderedDict.move_to_end() is constant as well. "
},
{
"code": null,
"e": 3637,
"s": 3620,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3655,
"s": 3637,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 3681,
"s": 3655,
"text": "Python collections-module"
},
{
"code": null,
"e": 3688,
"s": 3681,
"text": "Python"
}
]
|
robots.txt File | 04 Nov, 2018
What is robots.txt File?The web surface is an open place. Almost all the websites on the surface can be accessed by several search engines e.g. if we search something in Google, a vast number of results can be obtained from it. But, what if the web designers create something on their website and don’t want Google or other search engines to access it? This is where the robots.txt file comes into play. Robots.txt file is a text file created by the designer to prevent the search engines and bots to crawl up their sites. It contains the list of allowed and disallowed sites and whenever a bot wants to access the website, it checks the robots.txt file and accesses only those sites that are allowed. It doesn’t show up the disallowed sites in search results.
Need of robots.txt file: The most important reason for this is to keep the entire sections of a website private so that no robots can access it. It also helps to prevent search engines from indexing certain files. Moreover, it also specifies the location of the sitemap.
How to create robots.txt file?The robots.txt file is a simple text file placed on your web server which tells web crawlers like Google bot whether they should access a file or not. This file can be created in Notepad. The syntax is given by:
User-agent: {name of user without braces}
Disallow: {site disallowed by the owner, i.e this can't be indexed}
Sitemap: {the sitemap location of the website}
Description of component:
User-agent: *Disallow:The website is open to all search engines(asterisk) and none of its content is disallowed.
User-agent: GooglebotDisallow: /The Googlebot search engine is disallowed to index any of its contents.
User-agent: *Disallow: /file.htmlThis is partial access. All other contents except file.html can be accessed.
Visit-time: 0200-0300This bounds the time for the crawler. The contents can be indexed only between the time interval given.
Crawl-delay: 20Prohibits the crawlers from hitting the site frequently as it would make the site slow.
Once the file is complete and ready, save it with the name “robots.txt” (this is important, don’t use another name) and upload it to the root directory of the website. This will allow the robots.txt file to do its work.
Note: The robots.txt file is accessible by everyone on the internet. Everyone can see the name of allowed and disallowed user agents and files. Although no one can open the files, just the names of the files are shown.To check a website’s robots.txt file,
"website name" + "/robots.txt"
eg: https://www.geeksforgeeks.org/robot.txt
How does robots.txt file work?When search something on any search engine, the search bot (being the user-agent) finds the website to display the results. But before displaying it, or even indexing it, it searches for the robots.txt file of the website, if there’s any. If there is one, the search bot goes through it to check the allowed and disallowed sites on the website. It ignores all the disallowed sites sited on the file and goes on to show the allowed contents in the results. Thus, it can only see the allowed contents by the owner of the website.
Example:
User-agent: Googlebot
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-content/plugins/
Disallow: /wp-content/themes/
Crawl-delay: 20
Visit-time: 0200-0300
This means that Google bot is allowed to crawl each page at a delay of 20 ms except those URLs that are disallowed during the time interval of 0200 – 0300 UTC only.
Reason to use robots.txt file:People have different opinions on having a robots.txt file in their website.Reasons to have robots.txt file:
It blocks the contents from search engines.
It tune access to the site from reputable robots.
It is used in currently developing website, which need not to show in search engines.
It is used to make contents available to specific search engines.
Use of robots.txt file?The most important use of a robots.txt file is to maintain privacy from the internet. Not everything on our webpage should be showed to open world, thus it is a serious concern which is dealt easily with the robots.txt file.
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
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to create footer to stay at the bottom of a Web page?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
ReactJS | Router | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Nov, 2018"
},
{
"code": null,
"e": 813,
"s": 52,
"text": "What is robots.txt File?The web surface is an open place. Almost all the websites on the surface can be accessed by several search engines e.g. if we search something in Google, a vast number of results can be obtained from it. But, what if the web designers create something on their website and don’t want Google or other search engines to access it? This is where the robots.txt file comes into play. Robots.txt file is a text file created by the designer to prevent the search engines and bots to crawl up their sites. It contains the list of allowed and disallowed sites and whenever a bot wants to access the website, it checks the robots.txt file and accesses only those sites that are allowed. It doesn’t show up the disallowed sites in search results."
},
{
"code": null,
"e": 1084,
"s": 813,
"text": "Need of robots.txt file: The most important reason for this is to keep the entire sections of a website private so that no robots can access it. It also helps to prevent search engines from indexing certain files. Moreover, it also specifies the location of the sitemap."
},
{
"code": null,
"e": 1326,
"s": 1084,
"text": "How to create robots.txt file?The robots.txt file is a simple text file placed on your web server which tells web crawlers like Google bot whether they should access a file or not. This file can be created in Notepad. The syntax is given by:"
},
{
"code": null,
"e": 1484,
"s": 1326,
"text": "User-agent: {name of user without braces}\nDisallow: {site disallowed by the owner, i.e this can't be indexed}\nSitemap: {the sitemap location of the website}\n"
},
{
"code": null,
"e": 1510,
"s": 1484,
"text": "Description of component:"
},
{
"code": null,
"e": 1623,
"s": 1510,
"text": "User-agent: *Disallow:The website is open to all search engines(asterisk) and none of its content is disallowed."
},
{
"code": null,
"e": 1727,
"s": 1623,
"text": "User-agent: GooglebotDisallow: /The Googlebot search engine is disallowed to index any of its contents."
},
{
"code": null,
"e": 1837,
"s": 1727,
"text": "User-agent: *Disallow: /file.htmlThis is partial access. All other contents except file.html can be accessed."
},
{
"code": null,
"e": 1962,
"s": 1837,
"text": "Visit-time: 0200-0300This bounds the time for the crawler. The contents can be indexed only between the time interval given."
},
{
"code": null,
"e": 2065,
"s": 1962,
"text": "Crawl-delay: 20Prohibits the crawlers from hitting the site frequently as it would make the site slow."
},
{
"code": null,
"e": 2285,
"s": 2065,
"text": "Once the file is complete and ready, save it with the name “robots.txt” (this is important, don’t use another name) and upload it to the root directory of the website. This will allow the robots.txt file to do its work."
},
{
"code": null,
"e": 2541,
"s": 2285,
"text": "Note: The robots.txt file is accessible by everyone on the internet. Everyone can see the name of allowed and disallowed user agents and files. Although no one can open the files, just the names of the files are shown.To check a website’s robots.txt file,"
},
{
"code": null,
"e": 2619,
"s": 2541,
"text": "\"website name\" + \"/robots.txt\"\neg: https://www.geeksforgeeks.org/robot.txt\n\n\n"
},
{
"code": null,
"e": 3177,
"s": 2619,
"text": "How does robots.txt file work?When search something on any search engine, the search bot (being the user-agent) finds the website to display the results. But before displaying it, or even indexing it, it searches for the robots.txt file of the website, if there’s any. If there is one, the search bot goes through it to check the allowed and disallowed sites on the website. It ignores all the disallowed sites sited on the file and goes on to show the allowed contents in the results. Thus, it can only see the allowed contents by the owner of the website."
},
{
"code": null,
"e": 3186,
"s": 3177,
"text": "Example:"
},
{
"code": null,
"e": 3353,
"s": 3186,
"text": "User-agent: Googlebot\nDisallow: /wp-admin/\nDisallow: /wp-includes/\nDisallow: /wp-content/plugins/\nDisallow: /wp-content/themes/\nCrawl-delay: 20\nVisit-time: 0200-0300\n"
},
{
"code": null,
"e": 3518,
"s": 3353,
"text": "This means that Google bot is allowed to crawl each page at a delay of 20 ms except those URLs that are disallowed during the time interval of 0200 – 0300 UTC only."
},
{
"code": null,
"e": 3657,
"s": 3518,
"text": "Reason to use robots.txt file:People have different opinions on having a robots.txt file in their website.Reasons to have robots.txt file:"
},
{
"code": null,
"e": 3701,
"s": 3657,
"text": "It blocks the contents from search engines."
},
{
"code": null,
"e": 3751,
"s": 3701,
"text": "It tune access to the site from reputable robots."
},
{
"code": null,
"e": 3837,
"s": 3751,
"text": "It is used in currently developing website, which need not to show in search engines."
},
{
"code": null,
"e": 3903,
"s": 3837,
"text": "It is used to make contents available to specific search engines."
},
{
"code": null,
"e": 4151,
"s": 3903,
"text": "Use of robots.txt file?The most important use of a robots.txt file is to maintain privacy from the internet. Not everything on our webpage should be showed to open world, thus it is a serious concern which is dealt easily with the robots.txt file."
},
{
"code": null,
"e": 4168,
"s": 4151,
"text": "Web Technologies"
},
{
"code": null,
"e": 4266,
"s": 4168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4327,
"s": 4266,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4370,
"s": 4327,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 4442,
"s": 4370,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4482,
"s": 4442,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4506,
"s": 4482,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4539,
"s": 4506,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 4597,
"s": 4539,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 4638,
"s": 4597,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4684,
"s": 4638,
"text": "How to Open URL in New Tab using JavaScript ?"
}
]
|
How to get current date and time in firebase using ReactJS ? | 28 Jun, 2021
The following approach covers how to get the current date and time in firebase using react. We have used the firebase module to achieve so.
Creating React Application and Installing Module:
Step 1: Create a React-app using the following command:npx create-react-app myapp
Step 1: Create a React-app using the following command:
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command:cd myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command:
cd myapp
Step 3: After creating the ReactJS application, Install the firebase module using the following command:npm install [email protected] --save
Step 3: After creating the ReactJS application, Install the firebase module using the following command:
npm install [email protected] --save
Project structure: Our project structure will look like this.
Example: Now implement the time and date part. Here, We are going to use a method called Timestamp which helps us to get the current date and time.
App.js
import React from 'react';import firebase from 'firebase';import {useState} from 'react'; function App() { // Current state const [curr , setCurr] = useState(''); // Function to get time and date const getDate = () => { const a = firebase.firestore .Timestamp.now().toDate().toString(); setCurr(a); } return ( <div> <center> <h1>{curr}</h1> <button onClick={getDate}>Show Date</button> </center> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Firebase
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to do crud operations in ReactJS ?
How to install bootstrap in React.js ?
How to Use Bootstrap with React?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "The following approach covers how to get the current date and time in firebase using react. We have used the firebase module to achieve so."
},
{
"code": null,
"e": 218,
"s": 168,
"text": "Creating React Application and Installing Module:"
},
{
"code": null,
"e": 300,
"s": 218,
"text": "Step 1: Create a React-app using the following command:npx create-react-app myapp"
},
{
"code": null,
"e": 356,
"s": 300,
"text": "Step 1: Create a React-app using the following command:"
},
{
"code": null,
"e": 383,
"s": 356,
"text": "npx create-react-app myapp"
},
{
"code": null,
"e": 486,
"s": 383,
"text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:cd myapp"
},
{
"code": null,
"e": 581,
"s": 486,
"text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:"
},
{
"code": null,
"e": 590,
"s": 581,
"text": "cd myapp"
},
{
"code": null,
"e": 730,
"s": 592,
"text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:npm install [email protected] --save"
},
{
"code": null,
"e": 835,
"s": 730,
"text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:"
},
{
"code": null,
"e": 869,
"s": 835,
"text": "npm install [email protected] --save"
},
{
"code": null,
"e": 931,
"s": 869,
"text": "Project structure: Our project structure will look like this."
},
{
"code": null,
"e": 1079,
"s": 931,
"text": "Example: Now implement the time and date part. Here, We are going to use a method called Timestamp which helps us to get the current date and time."
},
{
"code": null,
"e": 1086,
"s": 1079,
"text": "App.js"
},
{
"code": "import React from 'react';import firebase from 'firebase';import {useState} from 'react'; function App() { // Current state const [curr , setCurr] = useState(''); // Function to get time and date const getDate = () => { const a = firebase.firestore .Timestamp.now().toDate().toString(); setCurr(a); } return ( <div> <center> <h1>{curr}</h1> <button onClick={getDate}>Show Date</button> </center> </div> );} export default App;",
"e": 1579,
"s": 1086,
"text": null
},
{
"code": null,
"e": 1692,
"s": 1579,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 1702,
"s": 1692,
"text": "npm start"
},
{
"code": null,
"e": 1801,
"s": 1702,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 1810,
"s": 1801,
"text": "Firebase"
},
{
"code": null,
"e": 1826,
"s": 1810,
"text": "React-Questions"
},
{
"code": null,
"e": 1834,
"s": 1826,
"text": "ReactJS"
},
{
"code": null,
"e": 1851,
"s": 1834,
"text": "Web Technologies"
},
{
"code": null,
"e": 1949,
"s": 1851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1987,
"s": 1949,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2014,
"s": 1987,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2053,
"s": 2014,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2092,
"s": 2053,
"text": "How to install bootstrap in React.js ?"
},
{
"code": null,
"e": 2125,
"s": 2092,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 2158,
"s": 2125,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2220,
"s": 2158,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2281,
"s": 2220,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2331,
"s": 2281,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
typing.NamedTuple – Improved Namedtuples | 02 Sep, 2020
The NamedTuple class of the typing module added in Python 3.6 is the younger sibling of the namedtuple class in the collections module. The main difference being an updated syntax for defining new record types and added support for type hints. Like dictionaries, NamedTuples contain keys that are hashed to a particular value. But on the contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack.
NamedTuple can be created using the following syntax:
class class_name(NamedTuple):
field1: datatype
field2: datatype
This is equivalent to:
class_name = collections.namedtuple('class_name', ['field1', 'field2'])
Example:
Python3
# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # displaying the NamedTupleprint(website1)
Output:
Website(name='GeeksforGeeks', url='geeksforgeeks.org', rating=5)
Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.Access by keyname: Access by key name is also allowed as in dictionaries.using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument.
Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.
Access by keyname: Access by key name is also allowed as in dictionaries.
using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument.
Example:
Python3
# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # accessing using indexprint("The name of the website is : ", end = "")print(website1[0]) # accessing using nameprint("The URL of the website is : ", end = "")print(website1.url) # accessing using getattr() print("The rating of the website is : ", end = "")print(getattr(website1, 'rating'))
Output:
The name of the website is : GeeksforGeeks
The URL of the website is : geeksforgeeks.org
The rating of the website is : 5
The fields are immutable. So if we try to change the values, we get the attribute error:
Python3
# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # changing the attribute valuewebsite1.name = "Google"
Output:
AttributeError: can't set attribute
Python-OOP
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Sep, 2020"
},
{
"code": null,
"e": 472,
"s": 28,
"text": "The NamedTuple class of the typing module added in Python 3.6 is the younger sibling of the namedtuple class in the collections module. The main difference being an updated syntax for defining new record types and added support for type hints. Like dictionaries, NamedTuples contain keys that are hashed to a particular value. But on the contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack."
},
{
"code": null,
"e": 526,
"s": 472,
"text": "NamedTuple can be created using the following syntax:"
},
{
"code": null,
"e": 598,
"s": 526,
"text": "class class_name(NamedTuple):\n field1: datatype\n field2: datatype"
},
{
"code": null,
"e": 621,
"s": 598,
"text": "This is equivalent to:"
},
{
"code": null,
"e": 693,
"s": 621,
"text": "class_name = collections.namedtuple('class_name', ['field1', 'field2'])"
},
{
"code": null,
"e": 702,
"s": 693,
"text": "Example:"
},
{
"code": null,
"e": 710,
"s": 702,
"text": "Python3"
},
{
"code": "# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # displaying the NamedTupleprint(website1)",
"e": 1012,
"s": 710,
"text": null
},
{
"code": null,
"e": 1020,
"s": 1012,
"text": "Output:"
},
{
"code": null,
"e": 1085,
"s": 1020,
"text": "Website(name='GeeksforGeeks', url='geeksforgeeks.org', rating=5)"
},
{
"code": null,
"e": 1434,
"s": 1085,
"text": "Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index.Access by keyname: Access by key name is also allowed as in dictionaries.using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument."
},
{
"code": null,
"e": 1598,
"s": 1434,
"text": "Access by index: The attribute values of namedtuple() are ordered and can be accessed using the index number, unlike dictionaries that are not accessible by index."
},
{
"code": null,
"e": 1672,
"s": 1598,
"text": "Access by keyname: Access by key name is also allowed as in dictionaries."
},
{
"code": null,
"e": 1785,
"s": 1672,
"text": "using getattr(): This is yet another way to access the value by giving namedtuple and key-value as its argument."
},
{
"code": null,
"e": 1794,
"s": 1785,
"text": "Example:"
},
{
"code": null,
"e": 1802,
"s": 1794,
"text": "Python3"
},
{
"code": "# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # accessing using indexprint(\"The name of the website is : \", end = \"\")print(website1[0]) # accessing using nameprint(\"The URL of the website is : \", end = \"\")print(website1.url) # accessing using getattr() print(\"The rating of the website is : \", end = \"\")print(getattr(website1, 'rating'))",
"e": 2357,
"s": 1802,
"text": null
},
{
"code": null,
"e": 2365,
"s": 2357,
"text": "Output:"
},
{
"code": null,
"e": 2487,
"s": 2365,
"text": "The name of the website is : GeeksforGeeks\nThe URL of the website is : geeksforgeeks.org\nThe rating of the website is : 5"
},
{
"code": null,
"e": 2576,
"s": 2487,
"text": "The fields are immutable. So if we try to change the values, we get the attribute error:"
},
{
"code": null,
"e": 2584,
"s": 2576,
"text": "Python3"
},
{
"code": "# importing the modulefrom typing import NamedTuple # creating a classclass Website(NamedTuple): name: str url: str rating: int # creating a NamedTuplewebsite1 = Website('GeeksforGeeks', 'geeksforgeeks.org', 5) # changing the attribute valuewebsite1.name = \"Google\"",
"e": 2898,
"s": 2584,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 2943,
"s": 2906,
"text": "AttributeError: can't set attribute\n"
},
{
"code": null,
"e": 2954,
"s": 2943,
"text": "Python-OOP"
},
{
"code": null,
"e": 2974,
"s": 2954,
"text": "python-oop-concepts"
},
{
"code": null,
"e": 2981,
"s": 2974,
"text": "Python"
},
{
"code": null,
"e": 3079,
"s": 2981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3111,
"s": 3079,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3138,
"s": 3111,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3169,
"s": 3138,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3190,
"s": 3169,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3246,
"s": 3190,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3269,
"s": 3246,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3311,
"s": 3269,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3353,
"s": 3311,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3392,
"s": 3353,
"text": "Python | datetime.timedelta() function"
}
]
|
jQuery UI Tooltips destroy() Method | 05 Feb, 2021
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tooltip widget helps us to add new themes and allows for customization. In this article, we will see how to use destroy option in jQuery UI tooltips. The destroy option is used to destroy the tooltips in jQuery UI.
Syntax:
$(".selector").tooltip("destroy");
Parameters: This method does not accept any parameters.
CDN Link: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example : The following example demonstrates the destroy option for the tooltip. Once the ‘click to destroy!’ option is clicked, it destroys the
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script src="https://code.jquery.com/jquery-1.10.2.js"> </script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <h1 style="color: green">GeeksforGeeks</h1> <h3>jQuery UI | Tooltip destroy method</h3> <script> $(function () { $("#gfgtt").tooltip({ track: true, }); $("#gfg").click(function () { $("#gfgtt").tooltip("destroy"); }); }); </script> </head> <body> <input id="gfg" type="submit" name="GeeksforGeeks" value="click to destroy!" /> <button id="gfgtt" title="GeeksforGeeks">Click here!</button> </body></html>
Output:
Reference: https://api.jqueryui.com/tooltip/#method-destroy
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 420,
"s": 28,
"text": "jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. jQuery UI tooltip widget helps us to add new themes and allows for customization. In this article, we will see how to use destroy option in jQuery UI tooltips. The destroy option is used to destroy the tooltips in jQuery UI."
},
{
"code": null,
"e": 428,
"s": 420,
"text": "Syntax:"
},
{
"code": null,
"e": 463,
"s": 428,
"text": "$(\".selector\").tooltip(\"destroy\");"
},
{
"code": null,
"e": 519,
"s": 463,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 583,
"s": 519,
"text": "CDN Link: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 824,
"s": 583,
"text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 970,
"s": 824,
"text": "Example : The following example demonstrates the destroy option for the tooltip. Once the ‘click to destroy!’ option is clicked, it destroys the "
},
{
"code": null,
"e": 975,
"s": 970,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\" /> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"> </script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <h1 style=\"color: green\">GeeksforGeeks</h1> <h3>jQuery UI | Tooltip destroy method</h3> <script> $(function () { $(\"#gfgtt\").tooltip({ track: true, }); $(\"#gfg\").click(function () { $(\"#gfgtt\").tooltip(\"destroy\"); }); }); </script> </head> <body> <input id=\"gfg\" type=\"submit\" name=\"GeeksforGeeks\" value=\"click to destroy!\" /> <button id=\"gfgtt\" title=\"GeeksforGeeks\">Click here!</button> </body></html>",
"e": 1820,
"s": 975,
"text": null
},
{
"code": null,
"e": 1828,
"s": 1820,
"text": "Output:"
},
{
"code": null,
"e": 1888,
"s": 1828,
"text": "Reference: https://api.jqueryui.com/tooltip/#method-destroy"
},
{
"code": null,
"e": 1898,
"s": 1888,
"text": "jQuery-UI"
},
{
"code": null,
"e": 1905,
"s": 1898,
"text": "JQuery"
},
{
"code": null,
"e": 1922,
"s": 1905,
"text": "Web Technologies"
},
{
"code": null,
"e": 2020,
"s": 1922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2066,
"s": 2020,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 2095,
"s": 2066,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2158,
"s": 2095,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2211,
"s": 2158,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 2245,
"s": 2211,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 2307,
"s": 2245,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2340,
"s": 2307,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2401,
"s": 2340,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2451,
"s": 2401,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
]
|
Tags vs Elements vs Attributes in HTML | 11 Jun, 2021
HTML Tags: Tags are the starting and ending parts of an HTML element. They begin with < symbol and end with > symbol. Whatever written inside < and > are called tags.Example:
html
<b> </b>
HTML elements: Elements enclose the contents in between the tags. They consist of some kind of structure or expression. It generally consists of a start tag, content and an end tag.Example:
html
<b>This is the content.</b>
This is the content.
Where, <b> is the starting tag and </b> is the ending tag.HTML Attributes: It is used to define the character of an HTML element. It always placed in the opening tag of an element. It generally provides additional styling (attribute) to the element.Example:
html
<p align="center">This is paragraph.</p>
This is paragraph.
What are Tags and Attributes?
Tags and attributes are the basis of HTML.
They work together but perform different functions – it is worth investing 2 minutes in differentiating the two.
What Are HTML Tags?
Tags are used to mark up the start of an HTML element and they are usually enclosed in angle brackets. An example of a tag is: <h1>.
Most tags must be opened <h1> and closed </h1> in order to function.
What are HTML Attributes?
Attributes contain additional pieces of information. Attributes take the form of an opening tag and additional info is placed inside.
An example of an attribute is:
<img src="mydog.jpg" alt="A photo of my dog.">
In this instance, the image source (src) and the alt text (alt) are attributes of the <img> tag.
Golden Rules To Remember
The vast majority of tags must be opened (<tag>) and closed (</tag>) with the element information such as a title or text resting between the tags.
When using multiple tags, the tags must be closed in the order in which they were opened. For example:
Example: <strong><em>This is really important!</em></strong>
rahulkumarmr360
HTML-Misc
HTML
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 230,
"s": 53,
"text": "HTML Tags: Tags are the starting and ending parts of an HTML element. They begin with < symbol and end with > symbol. Whatever written inside < and > are called tags.Example: "
},
{
"code": null,
"e": 235,
"s": 230,
"text": "html"
},
{
"code": "<b> </b>",
"e": 244,
"s": 235,
"text": null
},
{
"code": null,
"e": 436,
"s": 244,
"text": "HTML elements: Elements enclose the contents in between the tags. They consist of some kind of structure or expression. It generally consists of a start tag, content and an end tag.Example: "
},
{
"code": null,
"e": 441,
"s": 436,
"text": "html"
},
{
"code": "<b>This is the content.</b>",
"e": 469,
"s": 441,
"text": null
},
{
"code": null,
"e": 490,
"s": 469,
"text": "This is the content."
},
{
"code": null,
"e": 750,
"s": 490,
"text": "Where, <b> is the starting tag and </b> is the ending tag.HTML Attributes: It is used to define the character of an HTML element. It always placed in the opening tag of an element. It generally provides additional styling (attribute) to the element.Example: "
},
{
"code": null,
"e": 755,
"s": 750,
"text": "html"
},
{
"code": "<p align=\"center\">This is paragraph.</p>",
"e": 796,
"s": 755,
"text": null
},
{
"code": null,
"e": 815,
"s": 796,
"text": "This is paragraph."
},
{
"code": null,
"e": 845,
"s": 815,
"text": "What are Tags and Attributes?"
},
{
"code": null,
"e": 888,
"s": 845,
"text": "Tags and attributes are the basis of HTML."
},
{
"code": null,
"e": 1001,
"s": 888,
"text": "They work together but perform different functions – it is worth investing 2 minutes in differentiating the two."
},
{
"code": null,
"e": 1021,
"s": 1001,
"text": "What Are HTML Tags?"
},
{
"code": null,
"e": 1154,
"s": 1021,
"text": "Tags are used to mark up the start of an HTML element and they are usually enclosed in angle brackets. An example of a tag is: <h1>."
},
{
"code": null,
"e": 1223,
"s": 1154,
"text": "Most tags must be opened <h1> and closed </h1> in order to function."
},
{
"code": null,
"e": 1249,
"s": 1223,
"text": "What are HTML Attributes?"
},
{
"code": null,
"e": 1383,
"s": 1249,
"text": "Attributes contain additional pieces of information. Attributes take the form of an opening tag and additional info is placed inside."
},
{
"code": null,
"e": 1414,
"s": 1383,
"text": "An example of an attribute is:"
},
{
"code": null,
"e": 1461,
"s": 1414,
"text": "<img src=\"mydog.jpg\" alt=\"A photo of my dog.\">"
},
{
"code": null,
"e": 1558,
"s": 1461,
"text": "In this instance, the image source (src) and the alt text (alt) are attributes of the <img> tag."
},
{
"code": null,
"e": 1583,
"s": 1558,
"text": "Golden Rules To Remember"
},
{
"code": null,
"e": 1731,
"s": 1583,
"text": "The vast majority of tags must be opened (<tag>) and closed (</tag>) with the element information such as a title or text resting between the tags."
},
{
"code": null,
"e": 1834,
"s": 1731,
"text": "When using multiple tags, the tags must be closed in the order in which they were opened. For example:"
},
{
"code": null,
"e": 1906,
"s": 1834,
"text": " Example: <strong><em>This is really important!</em></strong>"
},
{
"code": null,
"e": 1922,
"s": 1906,
"text": "rahulkumarmr360"
},
{
"code": null,
"e": 1932,
"s": 1922,
"text": "HTML-Misc"
},
{
"code": null,
"e": 1937,
"s": 1932,
"text": "HTML"
},
{
"code": null,
"e": 1956,
"s": 1937,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1973,
"s": 1956,
"text": "Web Technologies"
},
{
"code": null,
"e": 2000,
"s": 1973,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2005,
"s": 2000,
"text": "HTML"
}
]
|
How to Update Data in API using Retrofit in Android? | 21 Dec, 2021
We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API.
We will be building a simple application in which we will be displaying a simple form and with that form, we will be updating our data and passing it to our API to update that data. We will be using PUT request along with the Retrofit library to update our data to API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
// below dependency for using retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<!--permissions for INTERNET--><uses-permission android:name="android.permission.INTERNET"/>
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <!--edit text for our user name--> <EditText android:id="@+id/idEdtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="10dp" android:layout_marginTop="30dp" android:layout_marginEnd="10dp" android:hint="User Name" /> <!--edit text for our job--> <EditText android:id="@+id/idEdtJob" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="Job" /> <!--button to update our data--> <Button android:id="@+id/idBtnUpdate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Update Data" android:textAllCaps="false" /> <!--progress bar for the purpose of loading--> <ProgressBar android:id="@+id/idPBLoading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" /> <!--text view to display our response after updating data--> <TextView android:id="@+id/idTVResponse" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:gravity="center_horizontal" android:text="Response" android:textAlignment="center" android:textColor="@color/black" android:textSize="15sp" /> </LinearLayout>
Step 5: Creating a modal class for storing our data
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as DataModal and add the below code to it. Comments are added in the code to get to know in more detail.
Java
package com.gtappdevelopers.gfg; public class DataModal { // string variables for name and job. private String name; private String job; public DataModal(String name, String job) { this.name = name; this.job = job; } // creating getter and setter methods. public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; }}
Step 6: Creating an Interface class for our API Call
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class select it as RetrofitAPI and add below code to it. Comments are added in the code to get to know in more detail.
Java
package com.gtappdevelopers.gfg; import retrofit2.Call;import retrofit2.http.Body;import retrofit2.http.PUT; public interface RetrofitAPI { // as we are making a put request to update a data // so we are annotating it with put // and along with that we are passing a parameter as users @PUT("api/users/2") // on below line we are creating a method to put our data. Call<DataModal> updateData(@Body DataModal dataModal);}
Step 7: Working with MainActivity.java file
Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail.
Java
package com.gtappdevelopers.gfg; import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { String url = "https://reqres.in/"; // creating our variables for our views such // as text view, button and progress // bar and response text view. private EditText userNameEdt, jobEdt; private Button updateBtn; private ProgressBar loadingPB; private TextView responseTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views with their ids. userNameEdt = findViewById(R.id.idEdtUserName); jobEdt = findViewById(R.id.idEdtJob); updateBtn = findViewById(R.id.idBtnUpdate); loadingPB = findViewById(R.id.idPBLoading); responseTV = findViewById(R.id.idTVResponse); // adding on click listener for our button. updateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the edit text is empty or not. if (TextUtils.isEmpty(userNameEdt.getText().toString()) && TextUtils.isEmpty(jobEdt.getText().toString())) { // displaying a toast message if the edit text is empty. Toast.makeText(MainActivity.this, "Please enter your data..", Toast.LENGTH_SHORT).show(); return; } // calling a method to update data in our API. callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void callPUTDataMethod(String userName, String job) { // below line is for displaying our progress bar. loadingPB.setVisibility(View.VISIBLE); // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) // as we are sending data in json format so // we have to add Gson converter factory .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below the line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); // passing data from our text fields to our modal class. DataModal modal = new DataModal(userName, job); // calling a method to create an update and passing our modal class. Call<DataModal> call = retrofitAPI.updateData(modal); // on below line we are executing our method. call.enqueue(new Callback<DataModal>() { @Override public void onResponse(Call<DataModal> call, Response<DataModal> response) { // this method is called when we get response from our api. Toast.makeText(MainActivity.this, "Data updated to API", Toast.LENGTH_SHORT).show(); // below line is for hiding our progress bar. loadingPB.setVisibility(View.GONE); // on below line we are setting empty // text to our both edit text. jobEdt.setText(""); userNameEdt.setText(""); // we are getting a response from our body and // passing it to our modal class. DataModal responseFromAPI = response.body(); // on below line we are getting our data from modal class // and adding it to our string. String responseString = "Response Code : " + response.code() + "\nName : " + responseFromAPI.getName() + "\n" + "Job : " + responseFromAPI.getJob(); // below line we are setting our string to our text view. responseTV.setText(responseString); } @Override public void onFailure(Call<DataModal> call, Throwable t) { // setting text to our text view when // we get error response from API. responseTV.setText("Error found is : " + t.getMessage()); } }); }}
Now run your app and see the output of the app.
Output:
kapoorsagar226
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Android SDK and it's Components
Broadcast Receiver in Android With Example
How to Communicate Between Fragments in Android?
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API. "
},
{
"code": null,
"e": 709,
"s": 272,
"text": "We will be building a simple application in which we will be displaying a simple form and with that form, we will be updating our data and passing it to our API to update that data. We will be using PUT request along with the Retrofit library to update our data to API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 738,
"s": 709,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 900,
"s": 738,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 959,
"s": 900,
"text": "Step 2: Add the below dependency in your build.gradle file"
},
{
"code": null,
"e": 1186,
"s": 959,
"text": "Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 1342,
"s": 1186,
"text": "// below dependency for using retrofit.\nimplementation 'com.squareup.retrofit2:retrofit:2.9.0'\nimplementation 'com.squareup.retrofit2:converter-gson:2.5.0'"
},
{
"code": null,
"e": 1442,
"s": 1342,
"text": "After adding this dependency sync your project and now move towards the AndroidManifest.xml part. "
},
{
"code": null,
"e": 1517,
"s": 1442,
"text": "Step 3: Adding permissions to the internet in the AndroidManifest.xml file"
},
{
"code": null,
"e": 1590,
"s": 1517,
"text": "Navigate to the app > AndroidManifest.xml and add the below code to it. "
},
{
"code": null,
"e": 1594,
"s": 1590,
"text": "XML"
},
{
"code": "<!--permissions for INTERNET--><uses-permission android:name=\"android.permission.INTERNET\"/>",
"e": 1687,
"s": 1594,
"text": null
},
{
"code": null,
"e": 1735,
"s": 1687,
"text": "Step 4: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1878,
"s": 1735,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1882,
"s": 1878,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--edit text for our user name--> <EditText android:id=\"@+id/idEdtUserName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"10dp\" android:layout_marginTop=\"30dp\" android:layout_marginEnd=\"10dp\" android:hint=\"User Name\" /> <!--edit text for our job--> <EditText android:id=\"@+id/idEdtJob\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:hint=\"Job\" /> <!--button to update our data--> <Button android:id=\"@+id/idBtnUpdate\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"20dp\" android:text=\"Update Data\" android:textAllCaps=\"false\" /> <!--progress bar for the purpose of loading--> <ProgressBar android:id=\"@+id/idPBLoading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:visibility=\"gone\" /> <!--text view to display our response after updating data--> <TextView android:id=\"@+id/idTVResponse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"10dp\" android:gravity=\"center_horizontal\" android:text=\"Response\" android:textAlignment=\"center\" android:textColor=\"@color/black\" android:textSize=\"15sp\" /> </LinearLayout>",
"e": 3806,
"s": 1882,
"text": null
},
{
"code": null,
"e": 3860,
"s": 3806,
"text": "Step 5: Creating a modal class for storing our data "
},
{
"code": null,
"e": 4071,
"s": 3860,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as DataModal and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 4076,
"s": 4071,
"text": "Java"
},
{
"code": "package com.gtappdevelopers.gfg; public class DataModal { // string variables for name and job. private String name; private String job; public DataModal(String name, String job) { this.name = name; this.job = job; } // creating getter and setter methods. public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; }}",
"e": 4615,
"s": 4076,
"text": null
},
{
"code": null,
"e": 4668,
"s": 4615,
"text": "Step 6: Creating an Interface class for our API Call"
},
{
"code": null,
"e": 4873,
"s": 4668,
"text": "Navigate to the app > java > your app’s package name > Right-click on it > New > Java class select it as RetrofitAPI and add below code to it. Comments are added in the code to get to know in more detail."
},
{
"code": null,
"e": 4878,
"s": 4873,
"text": "Java"
},
{
"code": "package com.gtappdevelopers.gfg; import retrofit2.Call;import retrofit2.http.Body;import retrofit2.http.PUT; public interface RetrofitAPI { // as we are making a put request to update a data // so we are annotating it with put // and along with that we are passing a parameter as users @PUT(\"api/users/2\") // on below line we are creating a method to put our data. Call<DataModal> updateData(@Body DataModal dataModal);}",
"e": 5328,
"s": 4878,
"text": null
},
{
"code": null,
"e": 5372,
"s": 5328,
"text": "Step 7: Working with MainActivity.java file"
},
{
"code": null,
"e": 5544,
"s": 5372,
"text": "Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 5549,
"s": 5544,
"text": "Java"
},
{
"code": "package com.gtappdevelopers.gfg; import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { String url = \"https://reqres.in/\"; // creating our variables for our views such // as text view, button and progress // bar and response text view. private EditText userNameEdt, jobEdt; private Button updateBtn; private ProgressBar loadingPB; private TextView responseTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our views with their ids. userNameEdt = findViewById(R.id.idEdtUserName); jobEdt = findViewById(R.id.idEdtJob); updateBtn = findViewById(R.id.idBtnUpdate); loadingPB = findViewById(R.id.idPBLoading); responseTV = findViewById(R.id.idTVResponse); // adding on click listener for our button. updateBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // checking if the edit text is empty or not. if (TextUtils.isEmpty(userNameEdt.getText().toString()) && TextUtils.isEmpty(jobEdt.getText().toString())) { // displaying a toast message if the edit text is empty. Toast.makeText(MainActivity.this, \"Please enter your data..\", Toast.LENGTH_SHORT).show(); return; } // calling a method to update data in our API. callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString()); } }); } private void callPUTDataMethod(String userName, String job) { // below line is for displaying our progress bar. loadingPB.setVisibility(View.VISIBLE); // on below line we are creating a retrofit // builder and passing our base url Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) // as we are sending data in json format so // we have to add Gson converter factory .addConverterFactory(GsonConverterFactory.create()) // at last we are building our retrofit builder. .build(); // below the line is to create an instance for our retrofit api class. RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class); // passing data from our text fields to our modal class. DataModal modal = new DataModal(userName, job); // calling a method to create an update and passing our modal class. Call<DataModal> call = retrofitAPI.updateData(modal); // on below line we are executing our method. call.enqueue(new Callback<DataModal>() { @Override public void onResponse(Call<DataModal> call, Response<DataModal> response) { // this method is called when we get response from our api. Toast.makeText(MainActivity.this, \"Data updated to API\", Toast.LENGTH_SHORT).show(); // below line is for hiding our progress bar. loadingPB.setVisibility(View.GONE); // on below line we are setting empty // text to our both edit text. jobEdt.setText(\"\"); userNameEdt.setText(\"\"); // we are getting a response from our body and // passing it to our modal class. DataModal responseFromAPI = response.body(); // on below line we are getting our data from modal class // and adding it to our string. String responseString = \"Response Code : \" + response.code() + \"\\nName : \" + responseFromAPI.getName() + \"\\n\" + \"Job : \" + responseFromAPI.getJob(); // below line we are setting our string to our text view. responseTV.setText(responseString); } @Override public void onFailure(Call<DataModal> call, Throwable t) { // setting text to our text view when // we get error response from API. responseTV.setText(\"Error found is : \" + t.getMessage()); } }); }}",
"e": 10463,
"s": 5549,
"text": null
},
{
"code": null,
"e": 10512,
"s": 10463,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 10520,
"s": 10512,
"text": "Output:"
},
{
"code": null,
"e": 10535,
"s": 10520,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 10543,
"s": 10535,
"text": "Android"
},
{
"code": null,
"e": 10548,
"s": 10543,
"text": "Java"
},
{
"code": null,
"e": 10553,
"s": 10548,
"text": "Java"
},
{
"code": null,
"e": 10561,
"s": 10553,
"text": "Android"
},
{
"code": null,
"e": 10659,
"s": 10561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10728,
"s": 10659,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 10759,
"s": 10728,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 10791,
"s": 10759,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 10834,
"s": 10791,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 10883,
"s": 10834,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 10919,
"s": 10883,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 10944,
"s": 10919,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10995,
"s": 10944,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 11017,
"s": 10995,
"text": "For-each loop in Java"
}
]
|
Properties getProperty(key) method in Java with Examples | 23 May, 2019
The getProperty(key) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns null.
Syntax:
public Object getProperty(String key)
Parameters: This method accepts a parameter key whose mapping is to be checked in this Properties object.
Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns null.
Below programs illustrate the getProperty(key) method:
Program 1:
// Java program to demonstrate// getProperty(key) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties: " + properties .toString()); // Getting the value of Pen System.out.println("Value of Pen: " + properties .getProperty("Pen")); // Getting the value of Phone System.out.println("Value of Phone: " + properties .getProperty("Phone")); }}
Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
Value of Pen: null
Value of Phone: null
Program 2:
// Java program to demonstrate// getProperty(key) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, "100RS"); properties.put(2, "500RS"); properties.put(3, "1000RS"); // Print Properties details System.out.println("Current Properties: " + properties .toString()); // Getting the value of 1 System.out.println("Value of 1: " + properties .getProperty("1")); // Getting the value of 5 System.out.println("Value of 5: " + properties .getProperty("5")); }}
Current Properties: {3=1000RS, 2=500RS, 1=100RS}
Value of 1: null
Value of 5: null
References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getProperty-java.lang.String-
nidhi_biet
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 311,
"s": 28,
"text": "The getProperty(key) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns null."
},
{
"code": null,
"e": 319,
"s": 311,
"text": "Syntax:"
},
{
"code": null,
"e": 357,
"s": 319,
"text": "public Object getProperty(String key)"
},
{
"code": null,
"e": 463,
"s": 357,
"text": "Parameters: This method accepts a parameter key whose mapping is to be checked in this Properties object."
},
{
"code": null,
"e": 600,
"s": 463,
"text": "Returns: This method returns the value fetched corresponding to this key, if present. If there is no such mapping, then it returns null."
},
{
"code": null,
"e": 655,
"s": 600,
"text": "Below programs illustrate the getProperty(key) method:"
},
{
"code": null,
"e": 666,
"s": 655,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// getProperty(key) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties .toString()); // Getting the value of Pen System.out.println(\"Value of Pen: \" + properties .getProperty(\"Pen\")); // Getting the value of Phone System.out.println(\"Value of Phone: \" + properties .getProperty(\"Phone\")); }}",
"e": 1602,
"s": 666,
"text": null
},
{
"code": null,
"e": 1700,
"s": 1602,
"text": "Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nValue of Pen: null\nValue of Phone: null\n"
},
{
"code": null,
"e": 1711,
"s": 1700,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// getProperty(key) method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(1, \"100RS\"); properties.put(2, \"500RS\"); properties.put(3, \"1000RS\"); // Print Properties details System.out.println(\"Current Properties: \" + properties .toString()); // Getting the value of 1 System.out.println(\"Value of 1: \" + properties .getProperty(\"1\")); // Getting the value of 5 System.out.println(\"Value of 5: \" + properties .getProperty(\"5\")); }}",
"e": 2597,
"s": 1711,
"text": null
},
{
"code": null,
"e": 2681,
"s": 2597,
"text": "Current Properties: {3=1000RS, 2=500RS, 1=100RS}\nValue of 1: null\nValue of 5: null\n"
},
{
"code": null,
"e": 2791,
"s": 2681,
"text": "References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#getProperty-java.lang.String-"
},
{
"code": null,
"e": 2802,
"s": 2791,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2822,
"s": 2802,
"text": "Java - util package"
},
{
"code": null,
"e": 2837,
"s": 2822,
"text": "Java-Functions"
},
{
"code": null,
"e": 2853,
"s": 2837,
"text": "Java-Properties"
},
{
"code": null,
"e": 2858,
"s": 2853,
"text": "Java"
},
{
"code": null,
"e": 2863,
"s": 2858,
"text": "Java"
},
{
"code": null,
"e": 2961,
"s": 2863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3012,
"s": 2961,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3043,
"s": 3012,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3062,
"s": 3043,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3092,
"s": 3062,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3110,
"s": 3092,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3125,
"s": 3110,
"text": "Stream In Java"
},
{
"code": null,
"e": 3145,
"s": 3125,
"text": "Collections in Java"
},
{
"code": null,
"e": 3177,
"s": 3145,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3201,
"s": 3177,
"text": "Singleton Class in Java"
}
]
|
Detect Mutation using Python | 12 Nov, 2020
Prerequisite: Random Numbers in Python
The following article depicts how Python can be used to detect a mutated DNA strand.
generateDNASequence(): This method generates a random DNA strand of length 40 characters using the list of DNA bases A,C,G,T. This method returns the generated DNA strand.applyGammaRadiation(): This method takes the DNA strand generated by the above method as input parameter and then alters the strand at a random position only if the probability of mutation, which is also generated randomly is above 50%. The DNA base at the chosen position must be different from the DNA base with which it is replaced. This method returns the altered DNA strand.detectMutation(): This method takes the original and altered DNA strand as input and checks if the two strings are altered. If the strings are altered it returns the position of the altered DNA base
generateDNASequence(): This method generates a random DNA strand of length 40 characters using the list of DNA bases A,C,G,T. This method returns the generated DNA strand.
applyGammaRadiation(): This method takes the DNA strand generated by the above method as input parameter and then alters the strand at a random position only if the probability of mutation, which is also generated randomly is above 50%. The DNA base at the chosen position must be different from the DNA base with which it is replaced. This method returns the altered DNA strand.
detectMutation(): This method takes the original and altered DNA strand as input and checks if the two strings are altered. If the strings are altered it returns the position of the altered DNA base
The following steps are followed in order to achieve our required functionality:
Import random library
The generateDNASequence() function is used to generate DNA strands. DNA strand is generated by randomly choosing characters from the list of available options. When the string length becomes 40 the loop is completed and the DNA strand is returned.
The applyGammaRadiation() function to alter DNA strands. The possibility of mutation is generated randomly. If the possibility of mutation generated randomly is greater than 50 then mutation occurs else mutation does not occur. If mutation were to occur, the position of mutation is chosen randomly.
Next, the characters in DNA strand is converted to list.
The character at the position of mutation is fetched. Since the fetched character should be different from the one replacing it, we remove the fetched character from the list of available choices for choosing another character in its place. The new character or DNA base is chosen from the list.
Original DNA strand characters are again appended to a new list. The new base/character is set in the mutated position.
The characters in the cl list is converted to string again using join(). This is the new mutated DNA string.
If no mutation occurs, original dna is same as mutated DNA.
Finally the mutated/unmutated DNA is returned.
Then detectMutation() function is used to detect mutation. In this function, x and y take each character in dna and cdna for character by character comparison. If the character at the same index match, then the count is increased. Incase of mismatch the loop is broken.
The count value points to the index before the position of mutation. If count=40 it means all the characters of the 2 strands match, hence no mutation If count is less than 40, it means mutation has occurred.
Below is the Implementation.
Python3
# import random libraryimport random # function to generate dna strandsdef generateDNASequence(): # list of available DNA bases l = ['C', 'A', 'G', 'T'] res = "" for i in range(0, 40): # creating the DNA strand by appending # random characters from the list res = res + random.choice(l) return res # function to alter dna strandsdef applyGammaRadiation(dna): # possibility of mutation is generated randomly pos = random.randint(1, 100) cdna = '' # list of available DNA bases l = ['C', 'A', 'G', 'T'] # if the possibility of mutation generated randomly # is >50 then mutation happens if(pos > 50): # the position where mutation will take place # is chosen randomly changepos = random.randint(0, 39) dl = [] # the characters in DNA strand is converted to list dl[:0] = dna # the character at the determined mutation position # is fetched. ch = "" + dl[changepos] # since the fetched character should be different from # the one replacing it we remove the fetched character # from the list of available choices for choosing another # character in its place l.remove(ch) # the new character or DNA base is chosen from the list ms = random.choice(l) cl = [] # DNA strand characters are again appended to a new list cl[:0] = dna # the new base in the mutated position is set cl[changepos] = ms # the characters in the cl list is converted to string again # this is the new mutated DNA string cdna = ''.join([str(e) for e in cl]) # if possibility of mutation is less than 50% then no # mutation happens else: # if no mutation occurs original dna is same as mutated dna cdna = dna return cdna # function to detect mutationdef detectMutation(dna, cdna): count = 0 # x and y take each character in dna and cdna # for character by character comparison for x, y in zip(dna, cdna): # if the character at the same index match # then the count is increased if x == y: count = count + 1 # incase of mismatch the loop is broken else: break # the count value points to the index before the # position of mutation return count dna = generateDNASequence()print(dna+" (Original DNA)")cdna = applyGammaRadiation(dna)print(cdna+" (DNA after radiation)")count = detectMutation(dna, cdna) # if count=40 it means all the characters of the 2 strands match# hence no mutationif count == 40: print("No Mutation detected") # if count is less than 40# it means mutation has occurredelse: # ^ denotes the position of mutation pos = "^" print(pos.rjust(count+1)) print("Mutation detected at pos = ", (count+1))
Output
Python-random
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 67,
"s": 28,
"text": "Prerequisite: Random Numbers in Python"
},
{
"code": null,
"e": 153,
"s": 67,
"text": "The following article depicts how Python can be used to detect a mutated DNA strand. "
},
{
"code": null,
"e": 902,
"s": 153,
"text": "generateDNASequence(): This method generates a random DNA strand of length 40 characters using the list of DNA bases A,C,G,T. This method returns the generated DNA strand.applyGammaRadiation(): This method takes the DNA strand generated by the above method as input parameter and then alters the strand at a random position only if the probability of mutation, which is also generated randomly is above 50%. The DNA base at the chosen position must be different from the DNA base with which it is replaced. This method returns the altered DNA strand.detectMutation(): This method takes the original and altered DNA strand as input and checks if the two strings are altered. If the strings are altered it returns the position of the altered DNA base"
},
{
"code": null,
"e": 1074,
"s": 902,
"text": "generateDNASequence(): This method generates a random DNA strand of length 40 characters using the list of DNA bases A,C,G,T. This method returns the generated DNA strand."
},
{
"code": null,
"e": 1454,
"s": 1074,
"text": "applyGammaRadiation(): This method takes the DNA strand generated by the above method as input parameter and then alters the strand at a random position only if the probability of mutation, which is also generated randomly is above 50%. The DNA base at the chosen position must be different from the DNA base with which it is replaced. This method returns the altered DNA strand."
},
{
"code": null,
"e": 1653,
"s": 1454,
"text": "detectMutation(): This method takes the original and altered DNA strand as input and checks if the two strings are altered. If the strings are altered it returns the position of the altered DNA base"
},
{
"code": null,
"e": 1734,
"s": 1653,
"text": "The following steps are followed in order to achieve our required functionality:"
},
{
"code": null,
"e": 1756,
"s": 1734,
"text": "Import random library"
},
{
"code": null,
"e": 2004,
"s": 1756,
"text": "The generateDNASequence() function is used to generate DNA strands. DNA strand is generated by randomly choosing characters from the list of available options. When the string length becomes 40 the loop is completed and the DNA strand is returned."
},
{
"code": null,
"e": 2304,
"s": 2004,
"text": "The applyGammaRadiation() function to alter DNA strands. The possibility of mutation is generated randomly. If the possibility of mutation generated randomly is greater than 50 then mutation occurs else mutation does not occur. If mutation were to occur, the position of mutation is chosen randomly."
},
{
"code": null,
"e": 2361,
"s": 2304,
"text": "Next, the characters in DNA strand is converted to list."
},
{
"code": null,
"e": 2657,
"s": 2361,
"text": "The character at the position of mutation is fetched. Since the fetched character should be different from the one replacing it, we remove the fetched character from the list of available choices for choosing another character in its place. The new character or DNA base is chosen from the list."
},
{
"code": null,
"e": 2777,
"s": 2657,
"text": "Original DNA strand characters are again appended to a new list. The new base/character is set in the mutated position."
},
{
"code": null,
"e": 2886,
"s": 2777,
"text": "The characters in the cl list is converted to string again using join(). This is the new mutated DNA string."
},
{
"code": null,
"e": 2946,
"s": 2886,
"text": "If no mutation occurs, original dna is same as mutated DNA."
},
{
"code": null,
"e": 2993,
"s": 2946,
"text": "Finally the mutated/unmutated DNA is returned."
},
{
"code": null,
"e": 3263,
"s": 2993,
"text": "Then detectMutation() function is used to detect mutation. In this function, x and y take each character in dna and cdna for character by character comparison. If the character at the same index match, then the count is increased. Incase of mismatch the loop is broken."
},
{
"code": null,
"e": 3472,
"s": 3263,
"text": "The count value points to the index before the position of mutation. If count=40 it means all the characters of the 2 strands match, hence no mutation If count is less than 40, it means mutation has occurred."
},
{
"code": null,
"e": 3501,
"s": 3472,
"text": "Below is the Implementation."
},
{
"code": null,
"e": 3509,
"s": 3501,
"text": "Python3"
},
{
"code": "# import random libraryimport random # function to generate dna strandsdef generateDNASequence(): # list of available DNA bases l = ['C', 'A', 'G', 'T'] res = \"\" for i in range(0, 40): # creating the DNA strand by appending # random characters from the list res = res + random.choice(l) return res # function to alter dna strandsdef applyGammaRadiation(dna): # possibility of mutation is generated randomly pos = random.randint(1, 100) cdna = '' # list of available DNA bases l = ['C', 'A', 'G', 'T'] # if the possibility of mutation generated randomly # is >50 then mutation happens if(pos > 50): # the position where mutation will take place # is chosen randomly changepos = random.randint(0, 39) dl = [] # the characters in DNA strand is converted to list dl[:0] = dna # the character at the determined mutation position # is fetched. ch = \"\" + dl[changepos] # since the fetched character should be different from # the one replacing it we remove the fetched character # from the list of available choices for choosing another # character in its place l.remove(ch) # the new character or DNA base is chosen from the list ms = random.choice(l) cl = [] # DNA strand characters are again appended to a new list cl[:0] = dna # the new base in the mutated position is set cl[changepos] = ms # the characters in the cl list is converted to string again # this is the new mutated DNA string cdna = ''.join([str(e) for e in cl]) # if possibility of mutation is less than 50% then no # mutation happens else: # if no mutation occurs original dna is same as mutated dna cdna = dna return cdna # function to detect mutationdef detectMutation(dna, cdna): count = 0 # x and y take each character in dna and cdna # for character by character comparison for x, y in zip(dna, cdna): # if the character at the same index match # then the count is increased if x == y: count = count + 1 # incase of mismatch the loop is broken else: break # the count value points to the index before the # position of mutation return count dna = generateDNASequence()print(dna+\" (Original DNA)\")cdna = applyGammaRadiation(dna)print(cdna+\" (DNA after radiation)\")count = detectMutation(dna, cdna) # if count=40 it means all the characters of the 2 strands match# hence no mutationif count == 40: print(\"No Mutation detected\") # if count is less than 40# it means mutation has occurredelse: # ^ denotes the position of mutation pos = \"^\" print(pos.rjust(count+1)) print(\"Mutation detected at pos = \", (count+1))",
"e": 6495,
"s": 3509,
"text": null
},
{
"code": null,
"e": 6502,
"s": 6495,
"text": "Output"
},
{
"code": null,
"e": 6518,
"s": 6504,
"text": "Python-random"
},
{
"code": null,
"e": 6533,
"s": 6518,
"text": "python-utility"
},
{
"code": null,
"e": 6540,
"s": 6533,
"text": "Python"
},
{
"code": null,
"e": 6638,
"s": 6540,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6683,
"s": 6638,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 6733,
"s": 6683,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 6749,
"s": 6733,
"text": "Deque in Python"
},
{
"code": null,
"e": 6765,
"s": 6749,
"text": "Queue in Python"
},
{
"code": null,
"e": 6787,
"s": 6765,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 6829,
"s": 6787,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6856,
"s": 6829,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6879,
"s": 6856,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 6898,
"s": 6879,
"text": "reduce() in Python"
}
]
|
DAX Filter - KEEPFILTERS function | Modifies how filters are applied while evaluating a CALCULATE or CALCULATETABLE function.
KEEPFILTERS (<expression>)
Expression
Any DAX expression.
DAX KEEPFILTERS function does not return any value.
You can use DAX KEEPFILTERS function within the context CALCULATE and CALCULATETABLE functions, to override the standard behavior of those functions.
When you use KEEPFILTERS, any existing filters in the current context are compared with the columns in the filter arguments, and the intersection of those arguments is used as the context for evaluating the expression.
The net effect over any one column is that both sets of arguments apply −
The filter arguments used in CALCULATE function.
The filters in the arguments of the KEEPFILTER function.
In other words, while CALCULATE filters replace the current context, KEEPFILTERS adds filters to the current context.
= SUMX (
CALCULATETABLE (East_Sales,
FILTER(East_Sales,East_Sales[Product] = [Product]), | [
{
"code": null,
"e": 2225,
"s": 2135,
"text": "Modifies how filters are applied while evaluating a CALCULATE or CALCULATETABLE function."
},
{
"code": null,
"e": 2254,
"s": 2225,
"text": "KEEPFILTERS (<expression>) \n"
},
{
"code": null,
"e": 2265,
"s": 2254,
"text": "Expression"
},
{
"code": null,
"e": 2285,
"s": 2265,
"text": "Any DAX expression."
},
{
"code": null,
"e": 2337,
"s": 2285,
"text": "DAX KEEPFILTERS function does not return any value."
},
{
"code": null,
"e": 2487,
"s": 2337,
"text": "You can use DAX KEEPFILTERS function within the context CALCULATE and CALCULATETABLE functions, to override the standard behavior of those functions."
},
{
"code": null,
"e": 2706,
"s": 2487,
"text": "When you use KEEPFILTERS, any existing filters in the current context are compared with the columns in the filter arguments, and the intersection of those arguments is used as the context for evaluating the expression."
},
{
"code": null,
"e": 2780,
"s": 2706,
"text": "The net effect over any one column is that both sets of arguments apply −"
},
{
"code": null,
"e": 2829,
"s": 2780,
"text": "The filter arguments used in CALCULATE function."
},
{
"code": null,
"e": 2886,
"s": 2829,
"text": "The filters in the arguments of the KEEPFILTER function."
},
{
"code": null,
"e": 3004,
"s": 2886,
"text": "In other words, while CALCULATE filters replace the current context, KEEPFILTERS adds filters to the current context."
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.