title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
C# | Convert.ToSingle(String, IFormatProvider) Method - GeeksforGeeks
|
19 Sep, 2021
This method is used to converts the specified string representation of a number to an equivalent single-precision floating-point number, using the specified culture-specific formatting information.Syntax:
public static float ToSingle (string value, IFormatProvider provider);
Parameters:
value: It is a string that contains the number to convert.
provider: It is an object that supplies culture-specific formatting information.
Return Value: This method returns a single-precision floating-point number that is equivalent to the number in value, or 0 (zero) if value is null.Exceptions:
FormatException: If the value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverFlowException: If the value represents a number that is less than MinValue or greater than MaxValue.
Below programs illustrate the use of Convert.ToSingle(String, IFormatProvider) Method: Example 1:
csharp
// C# program to demonstrate the// Convert.ToSingle() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"123.45", "+12.345", "-1234.5"}; // calling get() Method Console.Write("Converted float value" + " from a specified string "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified float float val = Convert.ToSingle(s, cultures); // display the converted float value Console.Write(" {0}, ", val);}}
Converted float value from a specified string 123.45, 12.345, -1234.5,
Example 2: For FormatException
csharp
// C# program to demonstrate the// Convert.ToSingle() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"12.345", "+1234.5", "-123.45"}; // calling get() Method Console.Write("Converted float value" + " of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine("\n"); string s = "123 456, 789"; Console.WriteLine("format of s is invalid "); // converting string to specified float float val = Convert.ToSingle(s, cultures); // display the converted float value Console.Write(" {0}, ", val); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified float value float val = Convert.ToSingle(s, cultures); // display the converted // float value Console.Write(" {0}, ", val);}}
Converted float value of specified strings: 12.345, 1234.5, -123.45,
format of s is invalid
Exception Thrown: System.FormatException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.convert.tosingle?view=netframework-4.7.2#System_Convert_ToSingle_System_String_System_IFormatProvider_
sweetyty
surinderdawra388
CSharp Convert Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 24473,
"s": 24445,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 24679,
"s": 24473,
"text": "This method is used to converts the specified string representation of a number to an equivalent single-precision floating-point number, using the specified culture-specific formatting information.Syntax: "
},
{
"code": null,
"e": 24750,
"s": 24679,
"text": "public static float ToSingle (string value, IFormatProvider provider);"
},
{
"code": null,
"e": 24764,
"s": 24750,
"text": "Parameters: "
},
{
"code": null,
"e": 24823,
"s": 24764,
"text": "value: It is a string that contains the number to convert."
},
{
"code": null,
"e": 24904,
"s": 24823,
"text": "provider: It is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 25065,
"s": 24904,
"text": "Return Value: This method returns a single-precision floating-point number that is equivalent to the number in value, or 0 (zero) if value is null.Exceptions: "
},
{
"code": null,
"e": 25180,
"s": 25065,
"text": "FormatException: If the value does not consist of an optional sign followed by a sequence of digits (0 through 9)."
},
{
"code": null,
"e": 25285,
"s": 25180,
"text": "OverFlowException: If the value represents a number that is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 25385,
"s": 25285,
"text": "Below programs illustrate the use of Convert.ToSingle(String, IFormatProvider) Method: Example 1: "
},
{
"code": null,
"e": 25392,
"s": 25385,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToSingle() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"123.45\", \"+12.345\", \"-1234.5\"}; // calling get() Method Console.Write(\"Converted float value\" + \" from a specified string \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified float float val = Convert.ToSingle(s, cultures); // display the converted float value Console.Write(\" {0}, \", val);}}",
"e": 26629,
"s": 25392,
"text": null
},
{
"code": null,
"e": 26704,
"s": 26629,
"text": "Converted float value from a specified string 123.45, 12.345, -1234.5, "
},
{
"code": null,
"e": 26735,
"s": 26704,
"text": "Example 2: For FormatException"
},
{
"code": null,
"e": 26742,
"s": 26735,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToSingle() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"12.345\", \"+1234.5\", \"-123.45\"}; // calling get() Method Console.Write(\"Converted float value\" + \" of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } Console.WriteLine(\"\\n\"); string s = \"123 456, 789\"; Console.WriteLine(\"format of s is invalid \"); // converting string to specified float float val = Convert.ToSingle(s, cultures); // display the converted float value Console.Write(\" {0}, \", val); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to // specified float value float val = Convert.ToSingle(s, cultures); // display the converted // float value Console.Write(\" {0}, \", val);}}",
"e": 28230,
"s": 26742,
"text": null
},
{
"code": null,
"e": 28369,
"s": 28230,
"text": "Converted float value of specified strings: 12.345, 1234.5, -123.45, \n\nformat of s is invalid \nException Thrown: System.FormatException"
},
{
"code": null,
"e": 28383,
"s": 28371,
"text": "Reference: "
},
{
"code": null,
"e": 28537,
"s": 28383,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.convert.tosingle?view=netframework-4.7.2#System_Convert_ToSingle_System_String_System_IFormatProvider_"
},
{
"code": null,
"e": 28546,
"s": 28537,
"text": "sweetyty"
},
{
"code": null,
"e": 28563,
"s": 28546,
"text": "surinderdawra388"
},
{
"code": null,
"e": 28584,
"s": 28563,
"text": "CSharp Convert Class"
},
{
"code": null,
"e": 28598,
"s": 28584,
"text": "CSharp-method"
},
{
"code": null,
"e": 28601,
"s": 28598,
"text": "C#"
},
{
"code": null,
"e": 28699,
"s": 28601,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28708,
"s": 28699,
"text": "Comments"
},
{
"code": null,
"e": 28721,
"s": 28708,
"text": "Old Comments"
},
{
"code": null,
"e": 28744,
"s": 28721,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28772,
"s": 28744,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28818,
"s": 28772,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28833,
"s": 28818,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28873,
"s": 28833,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28891,
"s": 28873,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28922,
"s": 28891,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28945,
"s": 28922,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28967,
"s": 28945,
"text": "C# | Class and Object"
}
] |
Synchronizing Threads
|
Thread synchronization may be defined as a method with the help of which we can be assured that two or more concurrent threads are not simultaneously accessing the program segment known as critical section. On the other hand, as we know that critical section is the part of the program where the shared resource is accessed. Hence we can say that synchronization is the process of making sure that two or more threads do not interface with each other by accessing the resources at the same time. The diagram below shows that four threads trying to access the critical section of a program at the same time.
To make it clearer, suppose two or more threads trying to add the object in the list at the same time. This act cannot lead to a successful end because either it will drop one or all the objects or it will completely corrupt the state of the list. Here the role of the synchronization is that only one thread at a time can access the list.
We might encounter issues while implementing concurrent programming or applying synchronizing primitives. In this section, we will discuss two major issues. The issues are β
Deadlock
Race condition
This is one of the major issues in concurrent programming. Concurrent access to shared resources can lead to race condition. A race condition may be defined as the occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes.
Consider this example to understand the concept of race condition β
Step 1 β In this step, we need to import threading module β
import threading
Step 2 β Now, define a global variable, say x, along with its value as 0 β
x = 0
Step 3 β Now, we need to define the increment_global() function, which will do the increment by 1 in this global function x β
def increment_global():
global x
x += 1
Step 4 β In this step, we will define the taskofThread() function, which will call the increment_global() function for a specified number of times; for our example it is 50000 times β
def taskofThread():
for _ in range(50000):
increment_global()
Step 5 β Now, define the main() function in which threads t1 and t2 are created. Both will be started with the help of the start() function and wait until they finish their jobs with the help of join() function.
def main():
global x
x = 0
t1 = threading.Thread(target= taskofThread)
t2 = threading.Thread(target= taskofThread)
t1.start()
t2.start()
t1.join()
t2.join()
Step 6 β Now, we need to give the range as in for how many iterations we want to call the main() function. Here, we are calling it for 5 times.
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
In the output shown below, we can see the effect of race condition as the value of x after each iteration is expected 100000. However, there is lots of variation in the value. This is due to the concurrent access of threads to the shared global variable x.
x = 100000 after Iteration 0
x = 54034 after Iteration 1
x = 80230 after Iteration 2
x = 93602 after Iteration 3
x = 93289 after Iteration 4
As we have seen the effect of race condition in the above program, we need a synchronization tool, which can deal with race condition between multiple threads. In Python, the <threading> module provides Lock class to deal with race condition. Further, the Lock class provides different methods with the help of which we can handle race condition between multiple threads. The methods are described below β
This method is used to acquire, i.e., blocking a lock. A lock can be blocking or non-blocking depending upon the following true or false value β
With value set to True β If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked.
With value set to True β If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked.
With value set to False β If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked.
With value set to False β If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked.
This method is used to release a lock. Following are a few important tasks related to this method β
If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked.
If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked.
It will raise a ThreadError if lock is already unlocked.
It will raise a ThreadError if lock is already unlocked.
Now, we can rewrite the above program with the lock class and its methods to avoid the race condition. We need to define the taskofThread() method with lock argument and then need to use the acquire() and release() methods for blocking and non-blocking of locks to avoid race condition.
Following is example of python program to understand the concept of locks for dealing with race condition β
import threading
x = 0
def increment_global():
global x
x += 1
def taskofThread(lock):
for _ in range(50000):
lock.acquire()
increment_global()
lock.release()
def main():
global x
x = 0
lock = threading.Lock()
t1 = threading.Thread(target = taskofThread, args = (lock,))
t2 = threading.Thread(target = taskofThread, args = (lock,))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
for i in range(5):
main()
print("x = {1} after Iteration {0}".format(i,x))
The following output shows that the effect of race condition is neglected; as the value of x, after each & every iteration, is now 100000, which is as per the expectation of this program.
x = 100000 after Iteration 0
x = 100000 after Iteration 1
x = 100000 after Iteration 2
x = 100000 after Iteration 3
x = 100000 after Iteration 4
Deadlock is a troublesome issue one can face while designing the concurrent systems. We can illustrate this issue with the help of the dining philosopher problem as follows β
Edsger Dijkstra originally introduced the dining philosopher problem, one of the famous illustrations of one of the biggest problem of concurrent system called deadlock.
In this problem, there are five famous philosophers sitting at a round table eating some food from their bowls. There are five forks that can be used by the five philosophers to eat their food. However, the philosophers decide to use two forks at the same time to eat their food.
Now, there are two main conditions for the philosophers. First, each of the philosophers can be either in eating or in thinking state and second, they must first obtain both the forks, i.e., left and right. The issue arises when each of the five philosophers manages to pick the left fork at the same time. Now they all are waiting for the right fork to be free but they will never relinquish their fork until they have eaten their food and the right fork would never be available. Hence, there would be a deadlock state at the dinner table.
Now if we see, the same issue can arise in our concurrent systems too. The forks in the above example would be the system resources and each philosopher can represent the process, which is competing to get the resources.
The solution of this problem can be found by splitting the philosophers into two types β greedy philosophers and generous philosophers. Mainly a greedy philosopher will try to pick up the left fork and wait until it is there. He will then wait for the right fork to be there, pick it up, eat and then put it down. On the other hand, a generous philosopher will try to pick up the left fork and if it is not there, he will wait and try again after some time. If they get the left fork then they will try to get the right one. If they will get the right fork too then they will eat and release both the forks. However, if they will not get the right fork then they will release the left fork.
The following Python program will help us find a solution to the dining philosopher problem β
import threading
import random
import time
class DiningPhilosopher(threading.Thread):
running = True
def __init__(self, xname, Leftfork, Rightfork):
threading.Thread.__init__(self)
self.name = xname
self.Leftfork = Leftfork
self.Rightfork = Rightfork
def run(self):
while(self.running):
time.sleep( random.uniform(3,13))
print ('%s is hungry.' % self.name)
self.dine()
def dine(self):
fork1, fork2 = self.Leftfork, self.Rightfork
while self.running:
fork1.acquire(True)
locked = fork2.acquire(False)
if locked: break
fork1.release()
print ('%s swaps forks' % self.name)
fork1, fork2 = fork2, fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print ('%s starts eating '% self.name)
time.sleep(random.uniform(1,10))
print ('%s finishes eating and now thinking.' % self.name)
def Dining_Philosophers():
forks = [threading.Lock() for n in range(5)]
philosopherNames = ('1st','2nd','3rd','4th', '5th')
philosophers= [DiningPhilosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
for i in range(5)]
random.seed()
DiningPhilosopher.running = True
for p in philosophers: p.start()
time.sleep(30)
DiningPhilosopher.running = False
print (" It is finishing.")
Dining_Philosophers()
The above program uses the concept of greedy and generous philosophers. The program has also used the acquire() and release() methods of the Lock class of the <threading> module. We can see the solution in the following output β
4th is hungry.
4th starts eating
1st is hungry.
1st starts eating
2nd is hungry.
5th is hungry.
3rd is hungry.
1st finishes eating and now thinking.3rd swaps forks
2nd starts eating
4th finishes eating and now thinking.
3rd swaps forks5th starts eating
5th finishes eating and now thinking.
4th is hungry.
4th starts eating
2nd finishes eating and now thinking.
3rd swaps forks
1st is hungry.
1st starts eating
4th finishes eating and now thinking.
3rd starts eating
5th is hungry.
5th swaps forks
1st finishes eating and now thinking.
5th starts eating
2nd is hungry.
2nd swaps forks
4th is hungry.
5th finishes eating and now thinking.
3rd finishes eating and now thinking.
2nd starts eating 4th starts eating
It is finishing.
57 Lectures
8 hours
Denis Tishkov
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2529,
"s": 1922,
"text": "Thread synchronization may be defined as a method with the help of which we can be assured that two or more concurrent threads are not simultaneously accessing the program segment known as critical section. On the other hand, as we know that critical section is the part of the program where the shared resource is accessed. Hence we can say that synchronization is the process of making sure that two or more threads do not interface with each other by accessing the resources at the same time. The diagram below shows that four threads trying to access the critical section of a program at the same time."
},
{
"code": null,
"e": 2869,
"s": 2529,
"text": "To make it clearer, suppose two or more threads trying to add the object in the list at the same time. This act cannot lead to a successful end because either it will drop one or all the objects or it will completely corrupt the state of the list. Here the role of the synchronization is that only one thread at a time can access the list."
},
{
"code": null,
"e": 3043,
"s": 2869,
"text": "We might encounter issues while implementing concurrent programming or applying synchronizing primitives. In this section, we will discuss two major issues. The issues are β"
},
{
"code": null,
"e": 3052,
"s": 3043,
"text": "Deadlock"
},
{
"code": null,
"e": 3067,
"s": 3052,
"text": "Race condition"
},
{
"code": null,
"e": 3485,
"s": 3067,
"text": "This is one of the major issues in concurrent programming. Concurrent access to shared resources can lead to race condition. A race condition may be defined as the occurring of a condition when two or more threads can access shared data and then try to change its value at the same time. Due to this, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes."
},
{
"code": null,
"e": 3553,
"s": 3485,
"text": "Consider this example to understand the concept of race condition β"
},
{
"code": null,
"e": 3613,
"s": 3553,
"text": "Step 1 β In this step, we need to import threading module β"
},
{
"code": null,
"e": 3630,
"s": 3613,
"text": "import threading"
},
{
"code": null,
"e": 3705,
"s": 3630,
"text": "Step 2 β Now, define a global variable, say x, along with its value as 0 β"
},
{
"code": null,
"e": 3711,
"s": 3705,
"text": "x = 0"
},
{
"code": null,
"e": 3837,
"s": 3711,
"text": "Step 3 β Now, we need to define the increment_global() function, which will do the increment by 1 in this global function x β"
},
{
"code": null,
"e": 3884,
"s": 3837,
"text": "def increment_global():\n\n global x\n x += 1"
},
{
"code": null,
"e": 4068,
"s": 3884,
"text": "Step 4 β In this step, we will define the taskofThread() function, which will call the increment_global() function for a specified number of times; for our example it is 50000 times β"
},
{
"code": null,
"e": 4140,
"s": 4068,
"text": "def taskofThread():\n\n for _ in range(50000):\n increment_global()"
},
{
"code": null,
"e": 4352,
"s": 4140,
"text": "Step 5 β Now, define the main() function in which threads t1 and t2 are created. Both will be started with the help of the start() function and wait until they finish their jobs with the help of join() function."
},
{
"code": null,
"e": 4539,
"s": 4352,
"text": "def main():\n global x\n x = 0\n \n t1 = threading.Thread(target= taskofThread)\n t2 = threading.Thread(target= taskofThread)\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()"
},
{
"code": null,
"e": 4683,
"s": 4539,
"text": "Step 6 β Now, we need to give the range as in for how many iterations we want to call the main() function. Here, we are calling it for 5 times."
},
{
"code": null,
"e": 4800,
"s": 4683,
"text": "if __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))"
},
{
"code": null,
"e": 5057,
"s": 4800,
"text": "In the output shown below, we can see the effect of race condition as the value of x after each iteration is expected 100000. However, there is lots of variation in the value. This is due to the concurrent access of threads to the shared global variable x."
},
{
"code": null,
"e": 5199,
"s": 5057,
"text": "x = 100000 after Iteration 0\nx = 54034 after Iteration 1\nx = 80230 after Iteration 2\nx = 93602 after Iteration 3\nx = 93289 after Iteration 4\n"
},
{
"code": null,
"e": 5605,
"s": 5199,
"text": "As we have seen the effect of race condition in the above program, we need a synchronization tool, which can deal with race condition between multiple threads. In Python, the <threading> module provides Lock class to deal with race condition. Further, the Lock class provides different methods with the help of which we can handle race condition between multiple threads. The methods are described below β"
},
{
"code": null,
"e": 5750,
"s": 5605,
"text": "This method is used to acquire, i.e., blocking a lock. A lock can be blocking or non-blocking depending upon the following true or false value β"
},
{
"code": null,
"e": 5917,
"s": 5750,
"text": "With value set to True β If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked."
},
{
"code": null,
"e": 6084,
"s": 5917,
"text": "With value set to True β If the acquire() method is invoked with True, which is the default argument, then the thread execution is blocked until the lock is unlocked."
},
{
"code": null,
"e": 6284,
"s": 6084,
"text": "With value set to False β If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked."
},
{
"code": null,
"e": 6484,
"s": 6284,
"text": "With value set to False β If the acquire() method is invoked with False, which is not the default argument, then the thread execution is not blocked until it is set to true, i.e., until it is locked."
},
{
"code": null,
"e": 6584,
"s": 6484,
"text": "This method is used to release a lock. Following are a few important tasks related to this method β"
},
{
"code": null,
"e": 6780,
"s": 6584,
"text": "If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked."
},
{
"code": null,
"e": 6976,
"s": 6780,
"text": "If a lock is locked, then the release() method would unlock it. Its job is to allow exactly one thread to proceed if more than one threads are blocked and waiting for the lock to become unlocked."
},
{
"code": null,
"e": 7033,
"s": 6976,
"text": "It will raise a ThreadError if lock is already unlocked."
},
{
"code": null,
"e": 7090,
"s": 7033,
"text": "It will raise a ThreadError if lock is already unlocked."
},
{
"code": null,
"e": 7377,
"s": 7090,
"text": "Now, we can rewrite the above program with the lock class and its methods to avoid the race condition. We need to define the taskofThread() method with lock argument and then need to use the acquire() and release() methods for blocking and non-blocking of locks to avoid race condition."
},
{
"code": null,
"e": 7485,
"s": 7377,
"text": "Following is example of python program to understand the concept of locks for dealing with race condition β"
},
{
"code": null,
"e": 8040,
"s": 7485,
"text": "import threading\n\nx = 0\n\ndef increment_global():\n\n global x\n x += 1\n\ndef taskofThread(lock):\n\n for _ in range(50000):\n lock.acquire()\n increment_global()\n lock.release()\n\ndef main():\n global x\n x = 0\n\n lock = threading.Lock()\n t1 = threading.Thread(target = taskofThread, args = (lock,))\n t2 = threading.Thread(target = taskofThread, args = (lock,))\n\n t1.start()\n t2.start()\n\n t1.join()\n t2.join()\n\nif __name__ == \"__main__\":\n for i in range(5):\n main()\n print(\"x = {1} after Iteration {0}\".format(i,x))"
},
{
"code": null,
"e": 8228,
"s": 8040,
"text": "The following output shows that the effect of race condition is neglected; as the value of x, after each & every iteration, is now 100000, which is as per the expectation of this program."
},
{
"code": null,
"e": 8374,
"s": 8228,
"text": "x = 100000 after Iteration 0\nx = 100000 after Iteration 1\nx = 100000 after Iteration 2\nx = 100000 after Iteration 3\nx = 100000 after Iteration 4\n"
},
{
"code": null,
"e": 8549,
"s": 8374,
"text": "Deadlock is a troublesome issue one can face while designing the concurrent systems. We can illustrate this issue with the help of the dining philosopher problem as follows β"
},
{
"code": null,
"e": 8719,
"s": 8549,
"text": "Edsger Dijkstra originally introduced the dining philosopher problem, one of the famous illustrations of one of the biggest problem of concurrent system called deadlock."
},
{
"code": null,
"e": 8999,
"s": 8719,
"text": "In this problem, there are five famous philosophers sitting at a round table eating some food from their bowls. There are five forks that can be used by the five philosophers to eat their food. However, the philosophers decide to use two forks at the same time to eat their food."
},
{
"code": null,
"e": 9541,
"s": 8999,
"text": "Now, there are two main conditions for the philosophers. First, each of the philosophers can be either in eating or in thinking state and second, they must first obtain both the forks, i.e., left and right. The issue arises when each of the five philosophers manages to pick the left fork at the same time. Now they all are waiting for the right fork to be free but they will never relinquish their fork until they have eaten their food and the right fork would never be available. Hence, there would be a deadlock state at the dinner table."
},
{
"code": null,
"e": 9762,
"s": 9541,
"text": "Now if we see, the same issue can arise in our concurrent systems too. The forks in the above example would be the system resources and each philosopher can represent the process, which is competing to get the resources."
},
{
"code": null,
"e": 10453,
"s": 9762,
"text": "The solution of this problem can be found by splitting the philosophers into two types β greedy philosophers and generous philosophers. Mainly a greedy philosopher will try to pick up the left fork and wait until it is there. He will then wait for the right fork to be there, pick it up, eat and then put it down. On the other hand, a generous philosopher will try to pick up the left fork and if it is not there, he will wait and try again after some time. If they get the left fork then they will try to get the right one. If they will get the right fork too then they will eat and release both the forks. However, if they will not get the right fork then they will release the left fork."
},
{
"code": null,
"e": 10547,
"s": 10453,
"text": "The following Python program will help us find a solution to the dining philosopher problem β"
},
{
"code": null,
"e": 11918,
"s": 10547,
"text": "import threading\nimport random\nimport time\n\nclass DiningPhilosopher(threading.Thread):\n\n running = True\n\n def __init__(self, xname, Leftfork, Rightfork):\n threading.Thread.__init__(self)\n self.name = xname\n self.Leftfork = Leftfork\n self.Rightfork = Rightfork\n\n def run(self):\n while(self.running):\n time.sleep( random.uniform(3,13))\n print ('%s is hungry.' % self.name)\n self.dine()\n\n def dine(self):\n fork1, fork2 = self.Leftfork, self.Rightfork\n\n while self.running:\n fork1.acquire(True)\n locked = fork2.acquire(False)\n\t if locked: break\n fork1.release()\n print ('%s swaps forks' % self.name)\n fork1, fork2 = fork2, fork1\n else:\n return\n\n self.dining()\n fork2.release()\n fork1.release()\n\n def dining(self):\n print ('%s starts eating '% self.name)\n time.sleep(random.uniform(1,10))\n print ('%s finishes eating and now thinking.' % self.name)\n\ndef Dining_Philosophers():\n forks = [threading.Lock() for n in range(5)]\n philosopherNames = ('1st','2nd','3rd','4th', '5th')\n\n philosophers= [DiningPhilosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \\\n for i in range(5)]\n\n random.seed()\n DiningPhilosopher.running = True\n for p in philosophers: p.start()\n time.sleep(30)\n DiningPhilosopher.running = False\n print (\" It is finishing.\")\n\nDining_Philosophers()"
},
{
"code": null,
"e": 12147,
"s": 11918,
"text": "The above program uses the concept of greedy and generous philosophers. The program has also used the acquire() and release() methods of the Lock class of the <threading> module. We can see the solution in the following output β"
},
{
"code": null,
"e": 12877,
"s": 12147,
"text": "4th is hungry.\n4th starts eating\n1st is hungry.\n1st starts eating\n2nd is hungry.\n5th is hungry.\n3rd is hungry.\n1st finishes eating and now thinking.3rd swaps forks\n2nd starts eating\n4th finishes eating and now thinking.\n3rd swaps forks5th starts eating\n5th finishes eating and now thinking.\n4th is hungry.\n4th starts eating\n2nd finishes eating and now thinking.\n3rd swaps forks\n1st is hungry.\n1st starts eating\n4th finishes eating and now thinking.\n3rd starts eating\n5th is hungry.\n5th swaps forks\n1st finishes eating and now thinking.\n5th starts eating\n2nd is hungry.\n2nd swaps forks\n4th is hungry.\n5th finishes eating and now thinking.\n3rd finishes eating and now thinking.\n2nd starts eating 4th starts eating\nIt is finishing.\n"
},
{
"code": null,
"e": 12910,
"s": 12877,
"text": "\n 57 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 12925,
"s": 12910,
"text": " Denis Tishkov"
},
{
"code": null,
"e": 12932,
"s": 12925,
"text": " Print"
},
{
"code": null,
"e": 12943,
"s": 12932,
"text": " Add Notes"
}
] |
XML DOM - Remove Node
|
In this chapter, we will study about the XML DOM Remove Node operation. The remove node operation removes the specified node from the document. This operation can be implemented to remove the nodes like text node, element node or an attribute node.
Following are the methods that are used for remove node operation β
removeChild()
removeChild()
removeAttribute()
removeAttribute()
The method removeChild() removes the child node indicated by oldChild from the list of children, and returns it. Removing a child node is equivalent to removing a text node. Hence, removing a child node removes the text node associated with it.
The syntax to use removeChild() is as follows β
Node removeChild(Node oldChild) throws DOMException
Where,
oldChild β is the node being removed.
oldChild β is the node being removed.
This method returns the node removed.
This method returns the node removed.
The following example (removecurrentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified node <ContactNo> from the parent node.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6 {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("/dom/node.xml");
document.write("<b>Before remove operation, total ContactNo elements: </b>");
document.write(xmlDoc.getElementsByTagName("ContactNo").length);
document.write("<br>");
x = xmlDoc.getElementsByTagName("ContactNo")[0];
x.parentNode.removeChild(x);
document.write("<b>After remove operation, total ContactNo elements: </b>");
document.write(xmlDoc.getElementsByTagName("ContactNo").length);
</script>
</body>
</html>
In the above example β
x = xmlDoc.getElementsByTagName("ContactNo")[0] gets the element <ContactNo> indexed at 0.
x = xmlDoc.getElementsByTagName("ContactNo")[0] gets the element <ContactNo> indexed at 0.
x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node.
x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node.
Save this file as removecurrentnode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β
Before remove operation, total ContactNo elements: 3
After remove operation, total ContactNo elements: 2
The following example (removetextNode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified child node <FirstName>.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6 {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("/dom/node.xml");
x = xmlDoc.getElementsByTagName("FirstName")[0];
document.write("<b>Text node of child node before removal is:</b> ");
document.write(x.childNodes.length);
document.write("<br>");
y = x.childNodes[0];
x.removeChild(y);
document.write("<b>Text node of child node after removal is:</b> ");
document.write(x.childNodes.length);
</script>
</body>
</html>
In the above example β
x = xmlDoc.getElementsByTagName("FirstName")[0]; β gets the first element <FirstName> to the x indexed at 0.
x = xmlDoc.getElementsByTagName("FirstName")[0]; β gets the first element <FirstName> to the x indexed at 0.
y = x.childNodes[0]; β in this line y holds the child node to be remove.
y = x.childNodes[0]; β in this line y holds the child node to be remove.
x.removeChild(y); β removes the specified child node.
x.removeChild(y); β removes the specified child node.
Save this file as removetextNode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β
Text node of child node before removal is: 1
Text node of child node after removal is: 0
The method removeAttribute() removes an attribute of an element by name.
Syntax to use removeAttribute() is as follows β
void removeAttribute(java.lang.String name) throws DOMException
Where,
name β is the name of the attribute to remove.
name β is the name of the attribute to remove.
The following example (removeelementattribute_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified attribute node.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6 {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("/dom/node.xml");
x = xmlDoc.getElementsByTagName('Employee');
document.write(x[1].getAttribute('category'));
document.write("<br>");
x[1].removeAttribute('category');
document.write(x[1].getAttribute('category'));
</script>
</body>
</html>
In the above example β
document.write(x[1].getAttribute('category')); β value of attribute category indexed at 1st position is invoked.
document.write(x[1].getAttribute('category')); β value of attribute category indexed at 1st position is invoked.
x[1].removeAttribute('category'); β removes the attribute value.
x[1].removeAttribute('category'); β removes the attribute value.
Save this file as removeelementattribute_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β
Non-Technical
null
41 Lectures
5 hours
Abhishek And Pukhraj
33 Lectures
3.5 hours
Abhishek And Pukhraj
15 Lectures
1 hours
Zach Miller
15 Lectures
4 hours
Prof. Paul Cline, Ed.D
13 Lectures
4 hours
Prof. Paul Cline, Ed.D
17 Lectures
2 hours
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2537,
"s": 2288,
"text": "In this chapter, we will study about the XML DOM Remove Node operation. The remove node operation removes the specified node from the document. This operation can be implemented to remove the nodes like text node, element node or an attribute node."
},
{
"code": null,
"e": 2605,
"s": 2537,
"text": "Following are the methods that are used for remove node operation β"
},
{
"code": null,
"e": 2619,
"s": 2605,
"text": "removeChild()"
},
{
"code": null,
"e": 2633,
"s": 2619,
"text": "removeChild()"
},
{
"code": null,
"e": 2651,
"s": 2633,
"text": "removeAttribute()"
},
{
"code": null,
"e": 2669,
"s": 2651,
"text": "removeAttribute()"
},
{
"code": null,
"e": 2914,
"s": 2669,
"text": "The method removeChild() removes the child node indicated by oldChild from the list of children, and returns it. Removing a child node is equivalent to removing a text node. Hence, removing a child node removes the text node associated with it."
},
{
"code": null,
"e": 2962,
"s": 2914,
"text": "The syntax to use removeChild() is as follows β"
},
{
"code": null,
"e": 3015,
"s": 2962,
"text": "Node removeChild(Node oldChild) throws DOMException\n"
},
{
"code": null,
"e": 3022,
"s": 3015,
"text": "Where,"
},
{
"code": null,
"e": 3060,
"s": 3022,
"text": "oldChild β is the node being removed."
},
{
"code": null,
"e": 3098,
"s": 3060,
"text": "oldChild β is the node being removed."
},
{
"code": null,
"e": 3136,
"s": 3098,
"text": "This method returns the node removed."
},
{
"code": null,
"e": 3174,
"s": 3136,
"text": "This method returns the node removed."
},
{
"code": null,
"e": 3350,
"s": 3174,
"text": "The following example (removecurrentnode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified node <ContactNo> from the parent node."
},
{
"code": null,
"e": 4355,
"s": 3350,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n document.write(\"<b>Before remove operation, total ContactNo elements: </b>\");\n document.write(xmlDoc.getElementsByTagName(\"ContactNo\").length);\n document.write(\"<br>\");\n\n x = xmlDoc.getElementsByTagName(\"ContactNo\")[0];\n x.parentNode.removeChild(x);\n\n document.write(\"<b>After remove operation, total ContactNo elements: </b>\");\n document.write(xmlDoc.getElementsByTagName(\"ContactNo\").length);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4378,
"s": 4355,
"text": "In the above example β"
},
{
"code": null,
"e": 4469,
"s": 4378,
"text": "x = xmlDoc.getElementsByTagName(\"ContactNo\")[0] gets the element <ContactNo> indexed at 0."
},
{
"code": null,
"e": 4560,
"s": 4469,
"text": "x = xmlDoc.getElementsByTagName(\"ContactNo\")[0] gets the element <ContactNo> indexed at 0."
},
{
"code": null,
"e": 4656,
"s": 4560,
"text": "x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node."
},
{
"code": null,
"e": 4752,
"s": 4656,
"text": "x.parentNode.removeChild(x); removes the element <ContactNo> indexed at 0 from the parent node."
},
{
"code": null,
"e": 4917,
"s": 4752,
"text": "Save this file as removecurrentnode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β"
},
{
"code": null,
"e": 5024,
"s": 4917,
"text": "Before remove operation, total ContactNo elements: 3\nAfter remove operation, total ContactNo elements: 2 \n"
},
{
"code": null,
"e": 5182,
"s": 5024,
"text": "The following example (removetextNode_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified child node <FirstName>."
},
{
"code": null,
"e": 6136,
"s": 5182,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"FirstName\")[0];\n\n document.write(\"<b>Text node of child node before removal is:</b> \");\n document.write(x.childNodes.length);\n document.write(\"<br>\");\n\n y = x.childNodes[0];\n x.removeChild(y);\n document.write(\"<b>Text node of child node after removal is:</b> \");\n document.write(x.childNodes.length);\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 6159,
"s": 6136,
"text": "In the above example β"
},
{
"code": null,
"e": 6268,
"s": 6159,
"text": "x = xmlDoc.getElementsByTagName(\"FirstName\")[0]; β gets the first element <FirstName> to the x indexed at 0."
},
{
"code": null,
"e": 6377,
"s": 6268,
"text": "x = xmlDoc.getElementsByTagName(\"FirstName\")[0]; β gets the first element <FirstName> to the x indexed at 0."
},
{
"code": null,
"e": 6450,
"s": 6377,
"text": "y = x.childNodes[0]; β in this line y holds the child node to be remove."
},
{
"code": null,
"e": 6523,
"s": 6450,
"text": "y = x.childNodes[0]; β in this line y holds the child node to be remove."
},
{
"code": null,
"e": 6577,
"s": 6523,
"text": "x.removeChild(y); β removes the specified child node."
},
{
"code": null,
"e": 6631,
"s": 6577,
"text": "x.removeChild(y); β removes the specified child node."
},
{
"code": null,
"e": 6793,
"s": 6631,
"text": "Save this file as removetextNode_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β"
},
{
"code": null,
"e": 6884,
"s": 6793,
"text": "Text node of child node before removal is: 1\nText node of child node after removal is: 0 \n"
},
{
"code": null,
"e": 6957,
"s": 6884,
"text": "The method removeAttribute() removes an attribute of an element by name."
},
{
"code": null,
"e": 7005,
"s": 6957,
"text": "Syntax to use removeAttribute() is as follows β"
},
{
"code": null,
"e": 7070,
"s": 7005,
"text": "void removeAttribute(java.lang.String name) throws DOMException\n"
},
{
"code": null,
"e": 7077,
"s": 7070,
"text": "Where,"
},
{
"code": null,
"e": 7124,
"s": 7077,
"text": "name β is the name of the attribute to remove."
},
{
"code": null,
"e": 7171,
"s": 7124,
"text": "name β is the name of the attribute to remove."
},
{
"code": null,
"e": 7329,
"s": 7171,
"text": "The following example (removeelementattribute_example.htm) parses an XML document (node.xml) into an XML DOM object and removes the specified attribute node."
},
{
"code": null,
"e": 8130,
"s": 7329,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName('Employee');\n\n document.write(x[1].getAttribute('category'));\n document.write(\"<br>\");\n\n x[1].removeAttribute('category');\n\n document.write(x[1].getAttribute('category'));\n\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 8153,
"s": 8130,
"text": "In the above example β"
},
{
"code": null,
"e": 8266,
"s": 8153,
"text": "document.write(x[1].getAttribute('category')); β value of attribute category indexed at 1st position is invoked."
},
{
"code": null,
"e": 8379,
"s": 8266,
"text": "document.write(x[1].getAttribute('category')); β value of attribute category indexed at 1st position is invoked."
},
{
"code": null,
"e": 8444,
"s": 8379,
"text": "x[1].removeAttribute('category'); β removes the attribute value."
},
{
"code": null,
"e": 8509,
"s": 8444,
"text": "x[1].removeAttribute('category'); β removes the attribute value."
},
{
"code": null,
"e": 8679,
"s": 8509,
"text": "Save this file as removeelementattribute_example.htm on the server path (this file and node.xml should be on the same path in your server). We get the following result β"
},
{
"code": null,
"e": 8699,
"s": 8679,
"text": "Non-Technical\nnull\n"
},
{
"code": null,
"e": 8732,
"s": 8699,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 8754,
"s": 8732,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 8789,
"s": 8754,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8811,
"s": 8789,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 8844,
"s": 8811,
"text": "\n 15 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8857,
"s": 8844,
"text": " Zach Miller"
},
{
"code": null,
"e": 8890,
"s": 8857,
"text": "\n 15 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8914,
"s": 8890,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 8947,
"s": 8914,
"text": "\n 13 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8971,
"s": 8947,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 9004,
"s": 8971,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9021,
"s": 9004,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 9028,
"s": 9021,
"text": " Print"
},
{
"code": null,
"e": 9039,
"s": 9028,
"text": " Add Notes"
}
] |
How to Create a Weather Alert System in Python | by Ng Wai Foong | Towards Data Science
|
By reading this piece, you will learn to create a weather alert system in Python that will send an email notification to multiple recipients when it forecasts that the sky will rain/snow in the next few hours. The email notification contains additional information such as the forecast-ed temperature and humidity.
There are 4 sections in this tutorial:
SetupImplementationResultConclusion
Setup
Implementation
Result
Conclusion
Letβs proceed to the next section.
I am going to use ClimaCellβs weather API in getting the forecasted weather data. It provides quite a number of useful and accurate data depends on your needs.
At the time of this writing, it covers historical station data up to 4 weeks back as well as daily forecast data up to 15 days ahead. Besides, you can easily implement it as the official documentation provides references for 4 different computer languages:
JavaScript
Ruby
Node
Python
Once you have signed up for it, you will be placed under free tier which allow you to make 1000 call per day and 100 per hour. It should be more than enough for our use case.
Head over to the sign up and and register a new account. Once you are done, you should see the following dashboard which outlines the plan details and your call activity.
Take note of the API key as we are going to use it in our code later on.
I am going to use a personal Gmail account to send the email to myself via SMTP. In order to use it, you need to change the configuration in the account setting and turn on the Less secure app access.
Head over to the account setting and click on the security menu.
Turn on the Less secure app access as follow
Once you are done, create a new file called config.ini in the root directory of your project. It will be used as the configuration files for our project. Append the following code inside it.
[email]email=your_email@gmail.comhost=smtp.gmail.comport=587password=your_password
email β Name of your email account
host β Host name for the smtp server. Modify this based on the smtp server for your email
port β Port for the smtp server. Modify this based on the smtp server for your email
password β Password to your email account. Make sure not to disclose this file or information to other people.
Creating a virtual environment is highly recommended for this project. Run the following command in the terminal to install configparser module. It is extremely useful in loading the configuration setting from a file.
pip install configparser
Letβs move on to the section section and start writing Python code.
Create a new file called weather_email.py in the same directory as config.ini. This file serve as the email module for our application.
Add the following import declaration at the top of the file
try: import configparserexcept: from six.moves import configparserimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport requests
Next, create a dictionary that represent the messages that we are going to send when there is rain or snow. You can create your own mapping or custom messages based on your use case.
weather_dict = {'freezing_rain_heavy': 'Heavy rain and snow', 'freezing_rain': 'Rain and snow', 'freezing_rain_light': 'Light rain and snow', 'freezing_drizzle': 'Light drizzle and snow', 'ice_pellets_heavy': 'Heavy ice pellets', 'ice_pellets': 'Normal ice pellets', 'ice_pellets_light': 'Light ice pellets', 'snow_heavy': 'Heavy snow', 'snow': 'Normal snow', 'snow_light': 'Light snow', 'tstorm': 'Thunder storm', 'rain_heavy': 'Heavy rain', 'rain': 'Normal rain', 'rain_light': 'Light rain'}
Initialize the following variables which are required when we call the weather API.
url = "https://api.climacell.co/v3/weather/nowcast"querystring = {"lat":"1.29027","lon":"103.851959","unit_system":"si","timestep":"60","start_time":"now","fields":"temp,humidity,weather_code","apikey":"xxxx"}
We are going to call the nowcast API which has the following parameters that can be modified:
lat β Latitude, -87 to 89
lot β Longitude, -180 to 180
unit_system β Unit system, βsiβ or βusβ
timestep β Time step in minutes, 1 to 60. Setting start_time to now and timestep of 60 will return 7 datapoints. (Now, 60 minutes later, 120 minutes later, ...)
start_time β You can set your own time or just initialize it to now
end_time β Optional argument to restrict the end time. By default, it will return the data up to 6 hours from the current timestamp.
fields β Selected fields from the data layers provided (such as βprecipitationβ or βwind_gustβ). I am using temp, humidity and weather_code for this tutorial.
apikey β The API key from the dashboard of Climacell Weather API.
We are going to create a new class called EmailSender and initialize it as follow. We utilize the configparser module to read the data from config.ini and assign it to the respective variables.
def __init__(self): self.cf = configparser.ConfigParser() self.cf.read('./config.ini') self.sec = 'email' self.email = self.cf.get(self.sec, 'email') self.host = self.cf.get(self.sec, 'host') self.port = self.cf.get(self.sec, 'port') self.password = self.cf.get(self.sec, 'password')
Create another function inside the class called SendEmail which accepts a recipient parameter. It accepts a list instead of string. This allows us to send the same email notifications to multiple email addresses.
def SendEmail(self, recipient):
Inside the function, initialize a new MIMEMultipart object with the following
title = "Home Sweet Home"msg = MIMEMultipart()msg['Subject'] = '[Weather Notification]'msg['From'] = self.emailmsg['To'] = ', '.join(recipient)
The next step is to call the API via requests module which will return the result as json.
response = requests.request("GET", url, params=querystring)result = ""json_data = response.json()
You can make full use of the result and map it to the dictionary that we have specified above in order to create the desired notification message. Then, initialize a MIMEText object with it and attach it to the MIMEMultipart object. Wrap it up by calling the smtplib.SMTP context manager to send the email.
msgText = MIMEText('<b>%s</b><p>%s</p>' % (title, result), 'html')msg.attach(msgText)with smtplib.SMTP(self.host, self.port) as smtpObj: smtpObj.ehlo() smtpObj.starttls() smtpObj.login(self.email, self.password) smtpObj.sendmail(self.email, recipient, msg.as_string())
Check out the following gist for the complete code.
You should have the following files in your root directory.
config.ini
weather_email.py
You can easily trigger the email alert functionality in any of your Python application as long as both files reside in the same directory as the Python file that you called. Simply modify the import statement based on your use case. The following example outlines the code that will send an email notification to two recipients if it is going to rain or snow in the next 6 hours.
import weather_emailemail_obj = weather_email.EmailSender()email_obj.SendEmail(["email@gmail.com", "email2@gmail.com"])
Letβs have a look at the following result when I ran the test. I got a notification informing me that it is raining lightly at my house.
I ran the same code once the rain stopped and it forecasted that it will rain again in 6 hoursβ time. Perhaps I should head back and collect all my clothes off the drying rack before it rains.
Letβs recap what we have learned today.
We started off with signing up to get the apikey for access to weather data and changing the security setting in Gmail to allow Less secure app access for our tutorial. Besides, we have created a simple configuration files which stored the email authentication data.
Next, we implemented a Python module which will call the weather API and send an email notification whenever there is snow or rain in the next 6 hours.
By now, you should be able to create your own weather alert system based on the use case that you have. Thanks for reading this piece and hope to see you again in the next article!
How to Create A Weather ChatbotTips and Tricks for Handling Configuration Files in Python
How to Create A Weather Chatbot
Tips and Tricks for Handling Configuration Files in Python
|
[
{
"code": null,
"e": 487,
"s": 172,
"text": "By reading this piece, you will learn to create a weather alert system in Python that will send an email notification to multiple recipients when it forecasts that the sky will rain/snow in the next few hours. The email notification contains additional information such as the forecast-ed temperature and humidity."
},
{
"code": null,
"e": 526,
"s": 487,
"text": "There are 4 sections in this tutorial:"
},
{
"code": null,
"e": 562,
"s": 526,
"text": "SetupImplementationResultConclusion"
},
{
"code": null,
"e": 568,
"s": 562,
"text": "Setup"
},
{
"code": null,
"e": 583,
"s": 568,
"text": "Implementation"
},
{
"code": null,
"e": 590,
"s": 583,
"text": "Result"
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Conclusion"
},
{
"code": null,
"e": 636,
"s": 601,
"text": "Letβs proceed to the next section."
},
{
"code": null,
"e": 796,
"s": 636,
"text": "I am going to use ClimaCellβs weather API in getting the forecasted weather data. It provides quite a number of useful and accurate data depends on your needs."
},
{
"code": null,
"e": 1053,
"s": 796,
"text": "At the time of this writing, it covers historical station data up to 4 weeks back as well as daily forecast data up to 15 days ahead. Besides, you can easily implement it as the official documentation provides references for 4 different computer languages:"
},
{
"code": null,
"e": 1064,
"s": 1053,
"text": "JavaScript"
},
{
"code": null,
"e": 1069,
"s": 1064,
"text": "Ruby"
},
{
"code": null,
"e": 1074,
"s": 1069,
"text": "Node"
},
{
"code": null,
"e": 1081,
"s": 1074,
"text": "Python"
},
{
"code": null,
"e": 1256,
"s": 1081,
"text": "Once you have signed up for it, you will be placed under free tier which allow you to make 1000 call per day and 100 per hour. It should be more than enough for our use case."
},
{
"code": null,
"e": 1427,
"s": 1256,
"text": "Head over to the sign up and and register a new account. Once you are done, you should see the following dashboard which outlines the plan details and your call activity."
},
{
"code": null,
"e": 1500,
"s": 1427,
"text": "Take note of the API key as we are going to use it in our code later on."
},
{
"code": null,
"e": 1701,
"s": 1500,
"text": "I am going to use a personal Gmail account to send the email to myself via SMTP. In order to use it, you need to change the configuration in the account setting and turn on the Less secure app access."
},
{
"code": null,
"e": 1766,
"s": 1701,
"text": "Head over to the account setting and click on the security menu."
},
{
"code": null,
"e": 1811,
"s": 1766,
"text": "Turn on the Less secure app access as follow"
},
{
"code": null,
"e": 2002,
"s": 1811,
"text": "Once you are done, create a new file called config.ini in the root directory of your project. It will be used as the configuration files for our project. Append the following code inside it."
},
{
"code": null,
"e": 2085,
"s": 2002,
"text": "[email]email=your_email@gmail.comhost=smtp.gmail.comport=587password=your_password"
},
{
"code": null,
"e": 2120,
"s": 2085,
"text": "email β Name of your email account"
},
{
"code": null,
"e": 2210,
"s": 2120,
"text": "host β Host name for the smtp server. Modify this based on the smtp server for your email"
},
{
"code": null,
"e": 2295,
"s": 2210,
"text": "port β Port for the smtp server. Modify this based on the smtp server for your email"
},
{
"code": null,
"e": 2406,
"s": 2295,
"text": "password β Password to your email account. Make sure not to disclose this file or information to other people."
},
{
"code": null,
"e": 2624,
"s": 2406,
"text": "Creating a virtual environment is highly recommended for this project. Run the following command in the terminal to install configparser module. It is extremely useful in loading the configuration setting from a file."
},
{
"code": null,
"e": 2649,
"s": 2624,
"text": "pip install configparser"
},
{
"code": null,
"e": 2717,
"s": 2649,
"text": "Letβs move on to the section section and start writing Python code."
},
{
"code": null,
"e": 2853,
"s": 2717,
"text": "Create a new file called weather_email.py in the same directory as config.ini. This file serve as the email module for our application."
},
{
"code": null,
"e": 2913,
"s": 2853,
"text": "Add the following import declaration at the top of the file"
},
{
"code": null,
"e": 3097,
"s": 2913,
"text": "try: import configparserexcept: from six.moves import configparserimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport requests"
},
{
"code": null,
"e": 3280,
"s": 3097,
"text": "Next, create a dictionary that represent the messages that we are going to send when there is rain or snow. You can create your own mapping or custom messages based on your use case."
},
{
"code": null,
"e": 3774,
"s": 3280,
"text": "weather_dict = {'freezing_rain_heavy': 'Heavy rain and snow', 'freezing_rain': 'Rain and snow', 'freezing_rain_light': 'Light rain and snow', 'freezing_drizzle': 'Light drizzle and snow', 'ice_pellets_heavy': 'Heavy ice pellets', 'ice_pellets': 'Normal ice pellets', 'ice_pellets_light': 'Light ice pellets', 'snow_heavy': 'Heavy snow', 'snow': 'Normal snow', 'snow_light': 'Light snow', 'tstorm': 'Thunder storm', 'rain_heavy': 'Heavy rain', 'rain': 'Normal rain', 'rain_light': 'Light rain'}"
},
{
"code": null,
"e": 3858,
"s": 3774,
"text": "Initialize the following variables which are required when we call the weather API."
},
{
"code": null,
"e": 4068,
"s": 3858,
"text": "url = \"https://api.climacell.co/v3/weather/nowcast\"querystring = {\"lat\":\"1.29027\",\"lon\":\"103.851959\",\"unit_system\":\"si\",\"timestep\":\"60\",\"start_time\":\"now\",\"fields\":\"temp,humidity,weather_code\",\"apikey\":\"xxxx\"}"
},
{
"code": null,
"e": 4162,
"s": 4068,
"text": "We are going to call the nowcast API which has the following parameters that can be modified:"
},
{
"code": null,
"e": 4188,
"s": 4162,
"text": "lat β Latitude, -87 to 89"
},
{
"code": null,
"e": 4217,
"s": 4188,
"text": "lot β Longitude, -180 to 180"
},
{
"code": null,
"e": 4257,
"s": 4217,
"text": "unit_system β Unit system, βsiβ or βusβ"
},
{
"code": null,
"e": 4418,
"s": 4257,
"text": "timestep β Time step in minutes, 1 to 60. Setting start_time to now and timestep of 60 will return 7 datapoints. (Now, 60 minutes later, 120 minutes later, ...)"
},
{
"code": null,
"e": 4486,
"s": 4418,
"text": "start_time β You can set your own time or just initialize it to now"
},
{
"code": null,
"e": 4619,
"s": 4486,
"text": "end_time β Optional argument to restrict the end time. By default, it will return the data up to 6 hours from the current timestamp."
},
{
"code": null,
"e": 4778,
"s": 4619,
"text": "fields β Selected fields from the data layers provided (such as βprecipitationβ or βwind_gustβ). I am using temp, humidity and weather_code for this tutorial."
},
{
"code": null,
"e": 4844,
"s": 4778,
"text": "apikey β The API key from the dashboard of Climacell Weather API."
},
{
"code": null,
"e": 5038,
"s": 4844,
"text": "We are going to create a new class called EmailSender and initialize it as follow. We utilize the configparser module to read the data from config.ini and assign it to the respective variables."
},
{
"code": null,
"e": 5343,
"s": 5038,
"text": "def __init__(self): self.cf = configparser.ConfigParser() self.cf.read('./config.ini') self.sec = 'email' self.email = self.cf.get(self.sec, 'email') self.host = self.cf.get(self.sec, 'host') self.port = self.cf.get(self.sec, 'port') self.password = self.cf.get(self.sec, 'password')"
},
{
"code": null,
"e": 5556,
"s": 5343,
"text": "Create another function inside the class called SendEmail which accepts a recipient parameter. It accepts a list instead of string. This allows us to send the same email notifications to multiple email addresses."
},
{
"code": null,
"e": 5588,
"s": 5556,
"text": "def SendEmail(self, recipient):"
},
{
"code": null,
"e": 5666,
"s": 5588,
"text": "Inside the function, initialize a new MIMEMultipart object with the following"
},
{
"code": null,
"e": 5810,
"s": 5666,
"text": "title = \"Home Sweet Home\"msg = MIMEMultipart()msg['Subject'] = '[Weather Notification]'msg['From'] = self.emailmsg['To'] = ', '.join(recipient)"
},
{
"code": null,
"e": 5901,
"s": 5810,
"text": "The next step is to call the API via requests module which will return the result as json."
},
{
"code": null,
"e": 5999,
"s": 5901,
"text": "response = requests.request(\"GET\", url, params=querystring)result = \"\"json_data = response.json()"
},
{
"code": null,
"e": 6306,
"s": 5999,
"text": "You can make full use of the result and map it to the dictionary that we have specified above in order to create the desired notification message. Then, initialize a MIMEText object with it and attach it to the MIMEMultipart object. Wrap it up by calling the smtplib.SMTP context manager to send the email."
},
{
"code": null,
"e": 6587,
"s": 6306,
"text": "msgText = MIMEText('<b>%s</b><p>%s</p>' % (title, result), 'html')msg.attach(msgText)with smtplib.SMTP(self.host, self.port) as smtpObj: smtpObj.ehlo() smtpObj.starttls() smtpObj.login(self.email, self.password) smtpObj.sendmail(self.email, recipient, msg.as_string())"
},
{
"code": null,
"e": 6639,
"s": 6587,
"text": "Check out the following gist for the complete code."
},
{
"code": null,
"e": 6699,
"s": 6639,
"text": "You should have the following files in your root directory."
},
{
"code": null,
"e": 6710,
"s": 6699,
"text": "config.ini"
},
{
"code": null,
"e": 6727,
"s": 6710,
"text": "weather_email.py"
},
{
"code": null,
"e": 7107,
"s": 6727,
"text": "You can easily trigger the email alert functionality in any of your Python application as long as both files reside in the same directory as the Python file that you called. Simply modify the import statement based on your use case. The following example outlines the code that will send an email notification to two recipients if it is going to rain or snow in the next 6 hours."
},
{
"code": null,
"e": 7227,
"s": 7107,
"text": "import weather_emailemail_obj = weather_email.EmailSender()email_obj.SendEmail([\"email@gmail.com\", \"email2@gmail.com\"])"
},
{
"code": null,
"e": 7364,
"s": 7227,
"text": "Letβs have a look at the following result when I ran the test. I got a notification informing me that it is raining lightly at my house."
},
{
"code": null,
"e": 7557,
"s": 7364,
"text": "I ran the same code once the rain stopped and it forecasted that it will rain again in 6 hoursβ time. Perhaps I should head back and collect all my clothes off the drying rack before it rains."
},
{
"code": null,
"e": 7597,
"s": 7557,
"text": "Letβs recap what we have learned today."
},
{
"code": null,
"e": 7864,
"s": 7597,
"text": "We started off with signing up to get the apikey for access to weather data and changing the security setting in Gmail to allow Less secure app access for our tutorial. Besides, we have created a simple configuration files which stored the email authentication data."
},
{
"code": null,
"e": 8016,
"s": 7864,
"text": "Next, we implemented a Python module which will call the weather API and send an email notification whenever there is snow or rain in the next 6 hours."
},
{
"code": null,
"e": 8197,
"s": 8016,
"text": "By now, you should be able to create your own weather alert system based on the use case that you have. Thanks for reading this piece and hope to see you again in the next article!"
},
{
"code": null,
"e": 8287,
"s": 8197,
"text": "How to Create A Weather ChatbotTips and Tricks for Handling Configuration Files in Python"
},
{
"code": null,
"e": 8319,
"s": 8287,
"text": "How to Create A Weather Chatbot"
}
] |
Batch Script - String length - GeeksforGeeks
|
04 Jan, 2022
In this article , we are going to learn how to find length of any String using Batch Script.
@echo off
set str=Geeks For Geeks
call :strLen str strlen
echo String is %strlen% characters long
pause
exit /b
:strLen
setlocal enabledelayedexpansion
:strLen_Loop
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof
In Batch Scripting there no function for checking length of string ,So we will create a function to find length of string.
By using β set β we are getting our input string whose length is to calculated.
In above code we are creating a Function βstrLenβ , which we can use to find our string length.
From β:strLenβ our function is started , then we will initialize our Loop with βstrLen_Loopβ.
(β!%1:~%len%!β) this statement is checking that our string is ended or not by using (==ββ).
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
During execution of our βifβ statement its checking if (β!%1:~%len%!β==ββ) this argument is True then it will Break the Loop and if its False , it will be continued.
Now if our argument is False then we will set our βlenβ variable as βlen=len+1β (also written as len+=1).
By using βgoto :strLen_Loopβ we are continuing our Loop.
Now , again it will check whether our string is ended or not by using command (β!%1:~%len%!β==ββ) and increase βlenβ by 1 if argument is False.
Now letβs assume when our argument is True , loop will break and our string length is set in βstrlenβ.
When βstrlenβ is called it will print our string length.
Output:
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
Docker - COPY Instruction
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 25761,
"s": 25733,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25854,
"s": 25761,
"text": "In this article , we are going to learn how to find length of any String using Batch Script."
},
{
"code": null,
"e": 26119,
"s": 25854,
"text": "@echo off\nset str=Geeks For Geeks\ncall :strLen str strlen\necho String is %strlen% characters long\npause\nexit /b\n\n:strLen\nsetlocal enabledelayedexpansion\n\n:strLen_Loop\n if not \"!%1:~%len%!\"==\"\" set /A len+=1 & goto :strLen_Loop\n(endlocal & set %2=%len%)\ngoto :eof"
},
{
"code": null,
"e": 26242,
"s": 26119,
"text": "In Batch Scripting there no function for checking length of string ,So we will create a function to find length of string."
},
{
"code": null,
"e": 26322,
"s": 26242,
"text": "By using β set β we are getting our input string whose length is to calculated."
},
{
"code": null,
"e": 26418,
"s": 26322,
"text": "In above code we are creating a Function βstrLenβ , which we can use to find our string length."
},
{
"code": null,
"e": 26512,
"s": 26418,
"text": "From β:strLenβ our function is started , then we will initialize our Loop with βstrLen_Loopβ."
},
{
"code": null,
"e": 26604,
"s": 26512,
"text": "(β!%1:~%len%!β) this statement is checking that our string is ended or not by using (==ββ)."
},
{
"code": null,
"e": 26663,
"s": 26604,
"text": "if not \"!%1:~%len%!\"==\"\" set /A len+=1 & goto :strLen_Loop"
},
{
"code": null,
"e": 26829,
"s": 26663,
"text": "During execution of our βifβ statement its checking if (β!%1:~%len%!β==ββ) this argument is True then it will Break the Loop and if its False , it will be continued."
},
{
"code": null,
"e": 26935,
"s": 26829,
"text": "Now if our argument is False then we will set our βlenβ variable as βlen=len+1β (also written as len+=1)."
},
{
"code": null,
"e": 26992,
"s": 26935,
"text": "By using βgoto :strLen_Loopβ we are continuing our Loop."
},
{
"code": null,
"e": 27136,
"s": 26992,
"text": "Now , again it will check whether our string is ended or not by using command (β!%1:~%len%!β==ββ) and increase βlenβ by 1 if argument is False."
},
{
"code": null,
"e": 27239,
"s": 27136,
"text": "Now letβs assume when our argument is True , loop will break and our string length is set in βstrlenβ."
},
{
"code": null,
"e": 27296,
"s": 27239,
"text": "When βstrlenβ is called it will print our string length."
},
{
"code": null,
"e": 27304,
"s": 27296,
"text": "Output:"
},
{
"code": null,
"e": 27317,
"s": 27304,
"text": "Batch-script"
},
{
"code": null,
"e": 27324,
"s": 27317,
"text": "Picked"
},
{
"code": null,
"e": 27335,
"s": 27324,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27433,
"s": 27335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27468,
"s": 27433,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 27497,
"s": 27468,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 27531,
"s": 27497,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 27557,
"s": 27531,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 27594,
"s": 27557,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 27631,
"s": 27594,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 27673,
"s": 27631,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 27699,
"s": 27673,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 27735,
"s": 27699,
"text": "uniq Command in LINUX with examples"
}
] |
Session State for Streamlit. You can now store information across... | by abhi saini | Towards Data Science
|
Soon after Streamlit launched in 2019, the community started asking for ways to add statefulness to their apps. Hacks for Session State have been around since October 2019, but we wanted to build an elegant solution that you could intuitively weave into apps in a few lines of code. Today weβre excited to release it!
You can now use Session State to store variables across reruns, create events on input widgets and use callback functions to handle events. This powerful functionality helps create apps which can:
Perform data/image annotation
Support Pagination
Add widgets that depend on other widgets
Build simple stateful games like Battleship, Tic Tac Toe, etc.
And much more β all of this with the simplicity of writing apps that are Python scripts!
π‘ If you want to jump right in, check out our demo to see some of the above apps in action or head to the docs for more detailed info on getting started.
In Streamlit, interacting with a widget triggers a rerun and variables defined in the code get reinitialized after each rerun. But with Session State, itβs possible to have values persist across reruns for those instances when you donβt want your variables reinitialized.
For example, hereβs a simple counter that maintains a count value across multiple presses of an increment button. Each button press triggers a rerun but the count value is preserved and incremented (or decremented) across the rerun:
π‘ To continue building on this example, follow along in our Topic Guide: Add State to your App π€
The above shows a basic example of how values can persist over reruns, but letβs move on to something a little more complex!
As part of this release, weβre launching Callbacks in Streamlit. Callbacks can be passed as arguments to widgets like st.button or st.slider using the on_change argument.
π‘ Curious what a callback is? Wikipedia phrases it well: β a callback, also known as a βcall-afterβ function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. β Hereβs a link if youβd like to read more.
With Session State, events associated with changes to a widget or click events associated with button presses can be handled by callback functions. Itβs important to remember the following order of execution:
Order of Execution: If a callback function is associated with a widget then a change in the widget triggers the following sequence: First the callback function is executed and then the app executes from top to bottom.
Hereβs an example:
In the above, we showcase the use of callbacks and session state. We also showcase an advanced concept, where session state can be associated with widget state using the key parameter.
To read more on this, check out the Advanced Concepts section in the Session State docs and to check out the API in detail visit the State API documentation.
Thatβs it for the intro to Session State, but we hope this isnβt the end of the conversation! Weβre excited to see how youβll use these new capabilities, and all the new functionalities state will unlock for the community.
To get started, upgrade to the latest release to use st.session_state and callbacks in your apps:
pip install --upgrade streamlit
If you have any questions about these (or about Streamlit in general) let us know below in the comments or on the forum. And make sure to come by the forum or Twitter to share all the cool things you make! π
Session State Topic Guide
Session State API Reference
Session State Demo App
Github
Forum
Originally published at https://blog.streamlit.io on July 1, 2021.
|
[
{
"code": null,
"e": 489,
"s": 171,
"text": "Soon after Streamlit launched in 2019, the community started asking for ways to add statefulness to their apps. Hacks for Session State have been around since October 2019, but we wanted to build an elegant solution that you could intuitively weave into apps in a few lines of code. Today weβre excited to release it!"
},
{
"code": null,
"e": 686,
"s": 489,
"text": "You can now use Session State to store variables across reruns, create events on input widgets and use callback functions to handle events. This powerful functionality helps create apps which can:"
},
{
"code": null,
"e": 716,
"s": 686,
"text": "Perform data/image annotation"
},
{
"code": null,
"e": 735,
"s": 716,
"text": "Support Pagination"
},
{
"code": null,
"e": 776,
"s": 735,
"text": "Add widgets that depend on other widgets"
},
{
"code": null,
"e": 839,
"s": 776,
"text": "Build simple stateful games like Battleship, Tic Tac Toe, etc."
},
{
"code": null,
"e": 928,
"s": 839,
"text": "And much more β all of this with the simplicity of writing apps that are Python scripts!"
},
{
"code": null,
"e": 1082,
"s": 928,
"text": "π‘ If you want to jump right in, check out our demo to see some of the above apps in action or head to the docs for more detailed info on getting started."
},
{
"code": null,
"e": 1354,
"s": 1082,
"text": "In Streamlit, interacting with a widget triggers a rerun and variables defined in the code get reinitialized after each rerun. But with Session State, itβs possible to have values persist across reruns for those instances when you donβt want your variables reinitialized."
},
{
"code": null,
"e": 1587,
"s": 1354,
"text": "For example, hereβs a simple counter that maintains a count value across multiple presses of an increment button. Each button press triggers a rerun but the count value is preserved and incremented (or decremented) across the rerun:"
},
{
"code": null,
"e": 1684,
"s": 1587,
"text": "π‘ To continue building on this example, follow along in our Topic Guide: Add State to your App π€"
},
{
"code": null,
"e": 1809,
"s": 1684,
"text": "The above shows a basic example of how values can persist over reruns, but letβs move on to something a little more complex!"
},
{
"code": null,
"e": 1980,
"s": 1809,
"text": "As part of this release, weβre launching Callbacks in Streamlit. Callbacks can be passed as arguments to widgets like st.button or st.slider using the on_change argument."
},
{
"code": null,
"e": 2283,
"s": 1980,
"text": "π‘ Curious what a callback is? Wikipedia phrases it well: β a callback, also known as a βcall-afterβ function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. β Hereβs a link if youβd like to read more."
},
{
"code": null,
"e": 2492,
"s": 2283,
"text": "With Session State, events associated with changes to a widget or click events associated with button presses can be handled by callback functions. Itβs important to remember the following order of execution:"
},
{
"code": null,
"e": 2710,
"s": 2492,
"text": "Order of Execution: If a callback function is associated with a widget then a change in the widget triggers the following sequence: First the callback function is executed and then the app executes from top to bottom."
},
{
"code": null,
"e": 2729,
"s": 2710,
"text": "Hereβs an example:"
},
{
"code": null,
"e": 2914,
"s": 2729,
"text": "In the above, we showcase the use of callbacks and session state. We also showcase an advanced concept, where session state can be associated with widget state using the key parameter."
},
{
"code": null,
"e": 3072,
"s": 2914,
"text": "To read more on this, check out the Advanced Concepts section in the Session State docs and to check out the API in detail visit the State API documentation."
},
{
"code": null,
"e": 3295,
"s": 3072,
"text": "Thatβs it for the intro to Session State, but we hope this isnβt the end of the conversation! Weβre excited to see how youβll use these new capabilities, and all the new functionalities state will unlock for the community."
},
{
"code": null,
"e": 3393,
"s": 3295,
"text": "To get started, upgrade to the latest release to use st.session_state and callbacks in your apps:"
},
{
"code": null,
"e": 3425,
"s": 3393,
"text": "pip install --upgrade streamlit"
},
{
"code": null,
"e": 3633,
"s": 3425,
"text": "If you have any questions about these (or about Streamlit in general) let us know below in the comments or on the forum. And make sure to come by the forum or Twitter to share all the cool things you make! π"
},
{
"code": null,
"e": 3659,
"s": 3633,
"text": "Session State Topic Guide"
},
{
"code": null,
"e": 3687,
"s": 3659,
"text": "Session State API Reference"
},
{
"code": null,
"e": 3710,
"s": 3687,
"text": "Session State Demo App"
},
{
"code": null,
"e": 3717,
"s": 3710,
"text": "Github"
},
{
"code": null,
"e": 3723,
"s": 3717,
"text": "Forum"
}
] |
Exploratory Data Analysis on Iris Dataset - GeeksforGeeks
|
17 Feb, 2022
In this article, we will discuss how to perform Exploratory Data Analysis on the Iris dataset. Before continuing with this article, we have used two terns i.e. EDA and Iris Dataset. Letβs see a brief about these datasets.
Exploratory Data Analysis (EDA) is a technique to analyze data using some visual Techniques. With this technique, we can get detailed information about the statistical summary of the data. We will also be able to deal with the duplicates values, outliers, and also see some trends or patterns present in the dataset.
Now letβs see a brief about the Iris dataset.
If you are from a data science background you all must be familiar with the Iris Dataset. If you are not then donβt worry we will discuss this here.
Iris Dataset is considered as the Hello World for data science. It contains five columns namely β Petal Length, Petal Width, Sepal Length, Sepal Width, and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded them digitally.
Note: This dataset can be downloaded from here.
You can download the Iris.csv file from the above link. Now we will use the Pandas library to load this CSV file, and we will convert it into the dataframe. read_csv() method is used to read CSV files.
Example:
Python3
import pandas as pd # Reading the CSV filedf = pd.read_csv("Iris.csv") # Printing top 5 rowsdf.head()
Output:
We will use the shape parameter to get the shape of the dataset.
Example:
Python3
df.shape
Output:
(150, 6)
We can see that the dataframe contains 6 columns and 150 rows.
Now, letβs also the columns and their data types. For this, we will use the info() method.
Example:
Python3
df.info()
Output:
We can see that only one column has categorical data and all the other columns are of the numeric type with non-Null entries.
Letβs get a quick statistical summary of the dataset using the describe() method. The describe() function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation, etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of the distribution of data.
Example:
Python3
df.describe()
Output:
We can see the count of each column along with their mean value, standard deviation, minimum and maximum values.
We will check if our data contains any missing values or not. Missing values can occur when no information is provided for one or more items or for a whole unit. We will use the isnull() method.
Example:
Python3
df.isnull().sum()
Output:
We can see that no column as any missing value.
Note: For more information, refer Working with Missing Data in Pandas.
Letβs see if our dataset contains any duplicates or not. Pandas drop_duplicates() method helps in removing duplicates from the data frame.
Example:
Python3
data = df.drop_duplicates(subset ="Species",)data
Output:
We can see that there are only three unique species. Letβs see if the dataset is balanced or not i.e. all the species contain equal amounts of rows or not. We will use the Series.value_counts() function. This function returns a Series containing counts of unique values.
Example:
Python3
df.value_counts("Species")
Output:
We can see that all the species contain an equal amount of rows, so we should not delete any entries.
Our target column will be the Species column because at the end we will need the result according to the species only. Letβs see a countplot for species.
Note: We will use Matplotlib and Seaborn library for the data visualization. If you want to know about these modules refer to the articles β
Matplotlib Tutorial
Python Seaborn Tutorial
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.countplot(x='Species', data=df, )plt.show()
Output:
We will see the relationship between the sepal length and sepal width and also between petal length and petal width.
Example 1: Comparing Sepal Length and Sepal Width
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='SepalLengthCm', y='SepalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()
Output:
From the above plot, we can infer that β
Species Setosa has smaller sepal lengths but larger sepal widths.
Versicolor Species lies in the middle of the other two species in terms of sepal length and width
Species Virginica has larger sepal lengths but smaller sepal widths.
Example 2: Comparing Petal Length and Petal Width
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='PetalLengthCm', y='PetalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()
Output:
From the above plot, we can infer that β
Species Setosa has smaller petal lengths and widths.
Versicolor Species lies in the middle of the other two species in terms of petal length and width
Species Virginica has the largest of petal lengths and widths.
Letβs plot all the columnβs relationships using a pairplot. It can be used for multivariate analysis.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.pairplot(df.drop(['Id'], axis = 1), hue='Species', height=2)
Output:
We can see many types of relationships from this plot such as the species Seotsa has the smallest of petals widths and lengths. It also has the smallest sepal length but larger sepal widths. Such information can be gathered about any other species.
Histograms allow seeing the distribution of data for various columns. It can be used for uni as well as bi-variate analysis.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2, figsize=(10,10)) axes[0,0].set_title("Sepal Length")axes[0,0].hist(df['SepalLengthCm'], bins=7) axes[0,1].set_title("Sepal Width")axes[0,1].hist(df['SepalWidthCm'], bins=5); axes[1,0].set_title("Petal Length")axes[1,0].hist(df['PetalLengthCm'], bins=6); axes[1,1].set_title("Petal Width")axes[1,1].hist(df['PetalWidthCm'], bins=6);
Output:
From the above plot, we can see that β
The highest frequency of the sepal length is between 30 and 35 which is between 5.5 and 6
The highest frequency of the sepal Width is around 70 which is between 3.0 and 3.5
The highest frequency of the petal length is around 50 which is between 1 and 2
The highest frequency of the petal width is between 40 and 50 which is between 0.0 and 0.5
Distplot is used basically for the univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt plot = sns.FacetGrid(df, hue="Species")plot.map(sns.distplot, "SepalLengthCm").add_legend() plot = sns.FacetGrid(df, hue="Species")plot.map(sns.distplot, "SepalWidthCm").add_legend() plot = sns.FacetGrid(df, hue="Species")plot.map(sns.distplot, "PetalLengthCm").add_legend() plot = sns.FacetGrid(df, hue="Species")plot.map(sns.distplot, "PetalWidthCm").add_legend() plt.show()
Output:
From the above plots, we can see that β
In the case of Sepal Length, there is a huge amount of overlapping.
In the case of Sepal Width also, there is a huge amount of overlapping.
In the case of Petal Length, there is a very little amount of overlapping.
In the case of Petal Width also, there is a very little amount of overlapping.
So we can use Petal Length and Petal Width as the classification feature.
Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any NA values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored.
Example:
Python3
data.corr(method='pearson')
Output:
The heatmap is a data visualization technique that is used to analyze the dataset as colors in two dimensions. Basically, it shows a correlation between all numerical variables in the dataset. In simpler terms, we can plot the above-found correlation using the heatmaps.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.heatmap(df.corr(method='pearson').drop( ['Id'], axis=1).drop(['Id'], axis=0), annot = True); plt.show()
Output:
From the above graph, we can see that β
Petal width and petal length have high correlations.
Petal length and sepal width have good correlations.
Petal Width and Sepal length have good correlations.
We can use boxplots to see how the categorical value os distributed with other numerical values.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt def graph(y): sns.boxplot(x="Species", y=y, data=df) plt.figure(figsize=(10,10)) # Adding the subplot at the specified# grid positionplt.subplot(221)graph('SepalLengthCm') plt.subplot(222)graph('SepalWidthCm') plt.subplot(223)graph('PetalLengthCm') plt.subplot(224)graph('PetalWidthCm') plt.show()
Output:
From the above graph, we can see that β
Species Setosa has the smallest features and less distributed with some outliers.
Species Versicolor has the average features.
Species Virginica has the highest features
An Outlier is a data-item/object that deviates significantly from the rest of the (so-called normal)objects. They can be caused by measurement or execution errors. The analysis for outlier detection is referred to as outlier mining. There are many ways to detect the outliers, and the removal process is the data frame same as removing a data item from the pandaβs dataframe.
Letβs consider the iris dataset and letβs plot the boxplot for the SepalWidthCm column.
Example:
Python3
# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # Load the datasetdf = pd.read_csv('Iris.csv') sns.boxplot(x='SepalWidthCm', data=df)
Output:
In the above graph, the values above 4 and below 2 are acting as outliers.
For removing the outlier, one must follow the same process of removing an entry from the dataset using its exact position in the dataset because in all the above methods of detecting the outliers end result is the list of all those data items that satisfy the outlier definition according to the method used.
Example: We will detect the outliers using IQR and then we will remove them. We will also draw the boxplot to see if the outliers are removed or not.
Python3
# Importingimport sklearnfrom sklearn.datasets import load_bostonimport pandas as pdimport seaborn as sns # Load the datasetdf = pd.read_csv('Iris.csv') # IQRQ1 = np.percentile(df['SepalWidthCm'], 25, interpolation = 'midpoint') Q3 = np.percentile(df['SepalWidthCm'], 75, interpolation = 'midpoint')IQR = Q3 - Q1 print("Old Shape: ", df.shape) # Upper boundupper = np.where(df['SepalWidthCm'] >= (Q3+1.5*IQR)) # Lower boundlower = np.where(df['SepalWidthCm'] <= (Q1-1.5*IQR)) # Removing the Outliersdf.drop(upper[0], inplace = True)df.drop(lower[0], inplace = True) print("New Shape: ", df.shape) sns.boxplot(x='SepalWidthCm', data=df)
Output:
Note: for more information, refer Detect and Remove the Outliers using Python
sagar0719kumar
ML-EDA
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Informed and Uninformed Search in AI
Deploy Machine Learning Model using Flask
Support Vector Machine Algorithm
Types of Environments in AI
k-nearest neighbor algorithm in Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 23953,
"s": 23925,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 24175,
"s": 23953,
"text": "In this article, we will discuss how to perform Exploratory Data Analysis on the Iris dataset. Before continuing with this article, we have used two terns i.e. EDA and Iris Dataset. Letβs see a brief about these datasets."
},
{
"code": null,
"e": 24492,
"s": 24175,
"text": "Exploratory Data Analysis (EDA) is a technique to analyze data using some visual Techniques. With this technique, we can get detailed information about the statistical summary of the data. We will also be able to deal with the duplicates values, outliers, and also see some trends or patterns present in the dataset."
},
{
"code": null,
"e": 24538,
"s": 24492,
"text": "Now letβs see a brief about the Iris dataset."
},
{
"code": null,
"e": 24687,
"s": 24538,
"text": "If you are from a data science background you all must be familiar with the Iris Dataset. If you are not then donβt worry we will discuss this here."
},
{
"code": null,
"e": 24990,
"s": 24687,
"text": "Iris Dataset is considered as the Hello World for data science. It contains five columns namely β Petal Length, Petal Width, Sepal Length, Sepal Width, and Species Type. Iris is a flowering plant, the researchers have measured various features of the different iris flowers and recorded them digitally."
},
{
"code": null,
"e": 25038,
"s": 24990,
"text": "Note: This dataset can be downloaded from here."
},
{
"code": null,
"e": 25240,
"s": 25038,
"text": "You can download the Iris.csv file from the above link. Now we will use the Pandas library to load this CSV file, and we will convert it into the dataframe. read_csv() method is used to read CSV files."
},
{
"code": null,
"e": 25249,
"s": 25240,
"text": "Example:"
},
{
"code": null,
"e": 25257,
"s": 25249,
"text": "Python3"
},
{
"code": "import pandas as pd # Reading the CSV filedf = pd.read_csv(\"Iris.csv\") # Printing top 5 rowsdf.head()",
"e": 25361,
"s": 25257,
"text": null
},
{
"code": null,
"e": 25369,
"s": 25361,
"text": "Output:"
},
{
"code": null,
"e": 25434,
"s": 25369,
"text": "We will use the shape parameter to get the shape of the dataset."
},
{
"code": null,
"e": 25443,
"s": 25434,
"text": "Example:"
},
{
"code": null,
"e": 25451,
"s": 25443,
"text": "Python3"
},
{
"code": "df.shape",
"e": 25460,
"s": 25451,
"text": null
},
{
"code": null,
"e": 25468,
"s": 25460,
"text": "Output:"
},
{
"code": null,
"e": 25477,
"s": 25468,
"text": "(150, 6)"
},
{
"code": null,
"e": 25540,
"s": 25477,
"text": "We can see that the dataframe contains 6 columns and 150 rows."
},
{
"code": null,
"e": 25631,
"s": 25540,
"text": "Now, letβs also the columns and their data types. For this, we will use the info() method."
},
{
"code": null,
"e": 25640,
"s": 25631,
"text": "Example:"
},
{
"code": null,
"e": 25648,
"s": 25640,
"text": "Python3"
},
{
"code": "df.info()",
"e": 25658,
"s": 25648,
"text": null
},
{
"code": null,
"e": 25666,
"s": 25658,
"text": "Output:"
},
{
"code": null,
"e": 25792,
"s": 25666,
"text": "We can see that only one column has categorical data and all the other columns are of the numeric type with non-Null entries."
},
{
"code": null,
"e": 26146,
"s": 25792,
"text": "Letβs get a quick statistical summary of the dataset using the describe() method. The describe() function applies basic statistical computations on the dataset like extreme values, count of data points standard deviation, etc. Any missing value or NaN value is automatically skipped. describe() function gives a good picture of the distribution of data."
},
{
"code": null,
"e": 26155,
"s": 26146,
"text": "Example:"
},
{
"code": null,
"e": 26163,
"s": 26155,
"text": "Python3"
},
{
"code": "df.describe()",
"e": 26177,
"s": 26163,
"text": null
},
{
"code": null,
"e": 26185,
"s": 26177,
"text": "Output:"
},
{
"code": null,
"e": 26298,
"s": 26185,
"text": "We can see the count of each column along with their mean value, standard deviation, minimum and maximum values."
},
{
"code": null,
"e": 26493,
"s": 26298,
"text": "We will check if our data contains any missing values or not. Missing values can occur when no information is provided for one or more items or for a whole unit. We will use the isnull() method."
},
{
"code": null,
"e": 26502,
"s": 26493,
"text": "Example:"
},
{
"code": null,
"e": 26510,
"s": 26502,
"text": "Python3"
},
{
"code": "df.isnull().sum()",
"e": 26528,
"s": 26510,
"text": null
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Output:"
},
{
"code": null,
"e": 26584,
"s": 26536,
"text": "We can see that no column as any missing value."
},
{
"code": null,
"e": 26655,
"s": 26584,
"text": "Note: For more information, refer Working with Missing Data in Pandas."
},
{
"code": null,
"e": 26794,
"s": 26655,
"text": "Letβs see if our dataset contains any duplicates or not. Pandas drop_duplicates() method helps in removing duplicates from the data frame."
},
{
"code": null,
"e": 26803,
"s": 26794,
"text": "Example:"
},
{
"code": null,
"e": 26811,
"s": 26803,
"text": "Python3"
},
{
"code": "data = df.drop_duplicates(subset =\"Species\",)data",
"e": 26861,
"s": 26811,
"text": null
},
{
"code": null,
"e": 26869,
"s": 26861,
"text": "Output:"
},
{
"code": null,
"e": 27141,
"s": 26869,
"text": "We can see that there are only three unique species. Letβs see if the dataset is balanced or not i.e. all the species contain equal amounts of rows or not. We will use the Series.value_counts() function. This function returns a Series containing counts of unique values. "
},
{
"code": null,
"e": 27150,
"s": 27141,
"text": "Example:"
},
{
"code": null,
"e": 27158,
"s": 27150,
"text": "Python3"
},
{
"code": "df.value_counts(\"Species\")",
"e": 27185,
"s": 27158,
"text": null
},
{
"code": null,
"e": 27193,
"s": 27185,
"text": "Output:"
},
{
"code": null,
"e": 27295,
"s": 27193,
"text": "We can see that all the species contain an equal amount of rows, so we should not delete any entries."
},
{
"code": null,
"e": 27449,
"s": 27295,
"text": "Our target column will be the Species column because at the end we will need the result according to the species only. Letβs see a countplot for species."
},
{
"code": null,
"e": 27591,
"s": 27449,
"text": "Note: We will use Matplotlib and Seaborn library for the data visualization. If you want to know about these modules refer to the articles β "
},
{
"code": null,
"e": 27611,
"s": 27591,
"text": "Matplotlib Tutorial"
},
{
"code": null,
"e": 27635,
"s": 27611,
"text": "Python Seaborn Tutorial"
},
{
"code": null,
"e": 27644,
"s": 27635,
"text": "Example:"
},
{
"code": null,
"e": 27652,
"s": 27644,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.countplot(x='Species', data=df, )plt.show()",
"e": 27776,
"s": 27652,
"text": null
},
{
"code": null,
"e": 27784,
"s": 27776,
"text": "Output:"
},
{
"code": null,
"e": 27901,
"s": 27784,
"text": "We will see the relationship between the sepal length and sepal width and also between petal length and petal width."
},
{
"code": null,
"e": 27951,
"s": 27901,
"text": "Example 1: Comparing Sepal Length and Sepal Width"
},
{
"code": null,
"e": 27959,
"s": 27951,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='SepalLengthCm', y='SepalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()",
"e": 28218,
"s": 27959,
"text": null
},
{
"code": null,
"e": 28226,
"s": 28218,
"text": "Output:"
},
{
"code": null,
"e": 28268,
"s": 28226,
"text": "From the above plot, we can infer that β "
},
{
"code": null,
"e": 28334,
"s": 28268,
"text": "Species Setosa has smaller sepal lengths but larger sepal widths."
},
{
"code": null,
"e": 28432,
"s": 28334,
"text": "Versicolor Species lies in the middle of the other two species in terms of sepal length and width"
},
{
"code": null,
"e": 28501,
"s": 28432,
"text": "Species Virginica has larger sepal lengths but smaller sepal widths."
},
{
"code": null,
"e": 28551,
"s": 28501,
"text": "Example 2: Comparing Petal Length and Petal Width"
},
{
"code": null,
"e": 28559,
"s": 28551,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.scatterplot(x='PetalLengthCm', y='PetalWidthCm', hue='Species', data=df, ) # Placing Legend outside the Figureplt.legend(bbox_to_anchor=(1, 1), loc=2) plt.show()",
"e": 28818,
"s": 28559,
"text": null
},
{
"code": null,
"e": 28826,
"s": 28818,
"text": "Output:"
},
{
"code": null,
"e": 28868,
"s": 28826,
"text": "From the above plot, we can infer that β "
},
{
"code": null,
"e": 28921,
"s": 28868,
"text": "Species Setosa has smaller petal lengths and widths."
},
{
"code": null,
"e": 29019,
"s": 28921,
"text": "Versicolor Species lies in the middle of the other two species in terms of petal length and width"
},
{
"code": null,
"e": 29082,
"s": 29019,
"text": "Species Virginica has the largest of petal lengths and widths."
},
{
"code": null,
"e": 29184,
"s": 29082,
"text": "Letβs plot all the columnβs relationships using a pairplot. It can be used for multivariate analysis."
},
{
"code": null,
"e": 29193,
"s": 29184,
"text": "Example:"
},
{
"code": null,
"e": 29201,
"s": 29193,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.pairplot(df.drop(['Id'], axis = 1), hue='Species', height=2)",
"e": 29355,
"s": 29201,
"text": null
},
{
"code": null,
"e": 29363,
"s": 29355,
"text": "Output:"
},
{
"code": null,
"e": 29612,
"s": 29363,
"text": "We can see many types of relationships from this plot such as the species Seotsa has the smallest of petals widths and lengths. It also has the smallest sepal length but larger sepal widths. Such information can be gathered about any other species."
},
{
"code": null,
"e": 29737,
"s": 29612,
"text": "Histograms allow seeing the distribution of data for various columns. It can be used for uni as well as bi-variate analysis."
},
{
"code": null,
"e": 29746,
"s": 29737,
"text": "Example:"
},
{
"code": null,
"e": 29754,
"s": 29746,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt fig, axes = plt.subplots(2, 2, figsize=(10,10)) axes[0,0].set_title(\"Sepal Length\")axes[0,0].hist(df['SepalLengthCm'], bins=7) axes[0,1].set_title(\"Sepal Width\")axes[0,1].hist(df['SepalWidthCm'], bins=5); axes[1,0].set_title(\"Petal Length\")axes[1,0].hist(df['PetalLengthCm'], bins=6); axes[1,1].set_title(\"Petal Width\")axes[1,1].hist(df['PetalWidthCm'], bins=6);",
"e": 30197,
"s": 29754,
"text": null
},
{
"code": null,
"e": 30205,
"s": 30197,
"text": "Output:"
},
{
"code": null,
"e": 30245,
"s": 30205,
"text": "From the above plot, we can see that β "
},
{
"code": null,
"e": 30335,
"s": 30245,
"text": "The highest frequency of the sepal length is between 30 and 35 which is between 5.5 and 6"
},
{
"code": null,
"e": 30418,
"s": 30335,
"text": "The highest frequency of the sepal Width is around 70 which is between 3.0 and 3.5"
},
{
"code": null,
"e": 30498,
"s": 30418,
"text": "The highest frequency of the petal length is around 50 which is between 1 and 2"
},
{
"code": null,
"e": 30589,
"s": 30498,
"text": "The highest frequency of the petal width is between 40 and 50 which is between 0.0 and 0.5"
},
{
"code": null,
"e": 30777,
"s": 30589,
"text": "Distplot is used basically for the univariant set of observations and visualizes it through a histogram i.e. only one observation and hence we choose one particular column of the dataset."
},
{
"code": null,
"e": 30786,
"s": 30777,
"text": "Example:"
},
{
"code": null,
"e": 30794,
"s": 30786,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt plot = sns.FacetGrid(df, hue=\"Species\")plot.map(sns.distplot, \"SepalLengthCm\").add_legend() plot = sns.FacetGrid(df, hue=\"Species\")plot.map(sns.distplot, \"SepalWidthCm\").add_legend() plot = sns.FacetGrid(df, hue=\"Species\")plot.map(sns.distplot, \"PetalLengthCm\").add_legend() plot = sns.FacetGrid(df, hue=\"Species\")plot.map(sns.distplot, \"PetalWidthCm\").add_legend() plt.show()",
"e": 31249,
"s": 30794,
"text": null
},
{
"code": null,
"e": 31257,
"s": 31249,
"text": "Output:"
},
{
"code": null,
"e": 31298,
"s": 31257,
"text": "From the above plots, we can see that β "
},
{
"code": null,
"e": 31366,
"s": 31298,
"text": "In the case of Sepal Length, there is a huge amount of overlapping."
},
{
"code": null,
"e": 31438,
"s": 31366,
"text": "In the case of Sepal Width also, there is a huge amount of overlapping."
},
{
"code": null,
"e": 31513,
"s": 31438,
"text": "In the case of Petal Length, there is a very little amount of overlapping."
},
{
"code": null,
"e": 31592,
"s": 31513,
"text": "In the case of Petal Width also, there is a very little amount of overlapping."
},
{
"code": null,
"e": 31666,
"s": 31592,
"text": "So we can use Petal Length and Petal Width as the classification feature."
},
{
"code": null,
"e": 31876,
"s": 31666,
"text": "Pandas dataframe.corr() is used to find the pairwise correlation of all columns in the dataframe. Any NA values are automatically excluded. For any non-numeric data type columns in the dataframe it is ignored."
},
{
"code": null,
"e": 31885,
"s": 31876,
"text": "Example:"
},
{
"code": null,
"e": 31893,
"s": 31885,
"text": "Python3"
},
{
"code": "data.corr(method='pearson')",
"e": 31921,
"s": 31893,
"text": null
},
{
"code": null,
"e": 31929,
"s": 31921,
"text": "Output:"
},
{
"code": null,
"e": 32200,
"s": 31929,
"text": "The heatmap is a data visualization technique that is used to analyze the dataset as colors in two dimensions. Basically, it shows a correlation between all numerical variables in the dataset. In simpler terms, we can plot the above-found correlation using the heatmaps."
},
{
"code": null,
"e": 32209,
"s": 32200,
"text": "Example:"
},
{
"code": null,
"e": 32217,
"s": 32209,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt sns.heatmap(df.corr(method='pearson').drop( ['Id'], axis=1).drop(['Id'], axis=0), annot = True); plt.show()",
"e": 32414,
"s": 32217,
"text": null
},
{
"code": null,
"e": 32422,
"s": 32414,
"text": "Output:"
},
{
"code": null,
"e": 32462,
"s": 32422,
"text": "From the above graph, we can see that β"
},
{
"code": null,
"e": 32516,
"s": 32462,
"text": "Petal width and petal length have high correlations. "
},
{
"code": null,
"e": 32569,
"s": 32516,
"text": "Petal length and sepal width have good correlations."
},
{
"code": null,
"e": 32622,
"s": 32569,
"text": "Petal Width and Sepal length have good correlations."
},
{
"code": null,
"e": 32719,
"s": 32622,
"text": "We can use boxplots to see how the categorical value os distributed with other numerical values."
},
{
"code": null,
"e": 32728,
"s": 32719,
"text": "Example:"
},
{
"code": null,
"e": 32736,
"s": 32728,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt def graph(y): sns.boxplot(x=\"Species\", y=y, data=df) plt.figure(figsize=(10,10)) # Adding the subplot at the specified# grid positionplt.subplot(221)graph('SepalLengthCm') plt.subplot(222)graph('SepalWidthCm') plt.subplot(223)graph('PetalLengthCm') plt.subplot(224)graph('PetalWidthCm') plt.show()",
"e": 33121,
"s": 32736,
"text": null
},
{
"code": null,
"e": 33129,
"s": 33121,
"text": "Output:"
},
{
"code": null,
"e": 33170,
"s": 33129,
"text": "From the above graph, we can see that β "
},
{
"code": null,
"e": 33252,
"s": 33170,
"text": "Species Setosa has the smallest features and less distributed with some outliers."
},
{
"code": null,
"e": 33297,
"s": 33252,
"text": "Species Versicolor has the average features."
},
{
"code": null,
"e": 33340,
"s": 33297,
"text": "Species Virginica has the highest features"
},
{
"code": null,
"e": 33716,
"s": 33340,
"text": "An Outlier is a data-item/object that deviates significantly from the rest of the (so-called normal)objects. They can be caused by measurement or execution errors. The analysis for outlier detection is referred to as outlier mining. There are many ways to detect the outliers, and the removal process is the data frame same as removing a data item from the pandaβs dataframe."
},
{
"code": null,
"e": 33804,
"s": 33716,
"text": "Letβs consider the iris dataset and letβs plot the boxplot for the SepalWidthCm column."
},
{
"code": null,
"e": 33813,
"s": 33804,
"text": "Example:"
},
{
"code": null,
"e": 33821,
"s": 33813,
"text": "Python3"
},
{
"code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # Load the datasetdf = pd.read_csv('Iris.csv') sns.boxplot(x='SepalWidthCm', data=df)",
"e": 33982,
"s": 33821,
"text": null
},
{
"code": null,
"e": 33990,
"s": 33982,
"text": "Output:"
},
{
"code": null,
"e": 34065,
"s": 33990,
"text": "In the above graph, the values above 4 and below 2 are acting as outliers."
},
{
"code": null,
"e": 34374,
"s": 34065,
"text": "For removing the outlier, one must follow the same process of removing an entry from the dataset using its exact position in the dataset because in all the above methods of detecting the outliers end result is the list of all those data items that satisfy the outlier definition according to the method used."
},
{
"code": null,
"e": 34524,
"s": 34374,
"text": "Example: We will detect the outliers using IQR and then we will remove them. We will also draw the boxplot to see if the outliers are removed or not."
},
{
"code": null,
"e": 34532,
"s": 34524,
"text": "Python3"
},
{
"code": "# Importingimport sklearnfrom sklearn.datasets import load_bostonimport pandas as pdimport seaborn as sns # Load the datasetdf = pd.read_csv('Iris.csv') # IQRQ1 = np.percentile(df['SepalWidthCm'], 25, interpolation = 'midpoint') Q3 = np.percentile(df['SepalWidthCm'], 75, interpolation = 'midpoint')IQR = Q3 - Q1 print(\"Old Shape: \", df.shape) # Upper boundupper = np.where(df['SepalWidthCm'] >= (Q3+1.5*IQR)) # Lower boundlower = np.where(df['SepalWidthCm'] <= (Q1-1.5*IQR)) # Removing the Outliersdf.drop(upper[0], inplace = True)df.drop(lower[0], inplace = True) print(\"New Shape: \", df.shape) sns.boxplot(x='SepalWidthCm', data=df)",
"e": 35207,
"s": 34532,
"text": null
},
{
"code": null,
"e": 35215,
"s": 35207,
"text": "Output:"
},
{
"code": null,
"e": 35293,
"s": 35215,
"text": "Note: for more information, refer Detect and Remove the Outliers using Python"
},
{
"code": null,
"e": 35308,
"s": 35293,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 35315,
"s": 35308,
"text": "ML-EDA"
},
{
"code": null,
"e": 35332,
"s": 35315,
"text": "Machine Learning"
},
{
"code": null,
"e": 35339,
"s": 35332,
"text": "Python"
},
{
"code": null,
"e": 35356,
"s": 35339,
"text": "Machine Learning"
},
{
"code": null,
"e": 35454,
"s": 35356,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35463,
"s": 35454,
"text": "Comments"
},
{
"code": null,
"e": 35476,
"s": 35463,
"text": "Old Comments"
},
{
"code": null,
"e": 35532,
"s": 35476,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 35574,
"s": 35532,
"text": "Deploy Machine Learning Model using Flask"
},
{
"code": null,
"e": 35607,
"s": 35574,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 35635,
"s": 35607,
"text": "Types of Environments in AI"
},
{
"code": null,
"e": 35674,
"s": 35635,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 35702,
"s": 35674,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 35752,
"s": 35702,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 35774,
"s": 35752,
"text": "Python map() function"
}
] |
C Program for Radix Sort
|
A sorting algorithm is an algorithm that puts components of a listing in a certain order. The most-used orders are numerical order and lexicographic order.
The Radix sort is a non-comparative sorting algorithm. The Radix sort algorithm is the most preferred algorithm for the unsorted list.
It sorts the elements by initially grouping the individual digits of the same place value. The idea of Radix Sort is to do digit by digit sort starting from least significant digit(LSD) to the most significant digit(MSD), according to their increasing/decreasing order. Radix sort is a small method that is used several times when alphabetizing an oversized list of names. Specifically, the list of names is initially sorted according to the first letter of every name, that is, the names are organized in twenty-six categories.
Let us review the following illustration to understand clearly about the working of the radix sort algorithm. Clearly, the number of pass/iteration depends on the size of the highest individual number.
In the above example, the primary column is input. The remaining columns show
the list after successive sorts on increasingly significant digits position.
Complexity Analysis of Radix Sort O(m.n).
However, if we glance at these 2 values, the size of the keys is comparatively small in comparison to the number of keys. as an example, if we've six-digit keys, we might have 1,000,000 totally different records.
Here, we tend to see that the size of the keys isn't important, and this algorithm is of linear quality O(n)
Radix_sort (list, n)
shift = 1
for loop = 1 to keysize do
for entry = 1 to n do
bucketnumber = (list[entry].key / shift) mod 10
append (bucket[bucketnumber], list[entry])
list = combinebuckets()
shift = shift * 10
This is a C Program to implement Radix Sort.
Live Demo
#include<stdio.h>
int get_max (int a[], int n){
int max = a[0];
for (int i = 1; i < n; i++)
if (a[i] > max)
max = a[i];
return max;
}
void radix_sort (int a[], int n){
int bucket[10][10], bucket_cnt[10];
int i, j, k, r, NOP = 0, divisor = 1, lar, pass;
lar = get_max (a, n);
while (lar > 0){
NOP++;
lar /= 10;
}
for (pass = 0; pass < NOP; pass++){
for (i = 0; i < 10; i++){
bucket_cnt[i] = 0;
}
for (i = 0; i < n; i++){
r = (a[i] / divisor) % 10;
bucket[r][bucket_cnt[r]] = a[i];
bucket_cnt[r] += 1;
}
i = 0;
for (k = 0; k < 10; k++){
for (j = 0; j < bucket_cnt[k]; j++){
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
printf ("After pass %d : ", pass + 1);
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
}
}
int main (){
int i, n, a[10];
printf ("Enter the number of items to be sorted: ");
scanf ("%d", &n);
printf ("Enter items: ");
for (i = 0; i < n; i++){
scanf ("%d", &a[i]);
}
radix_sort (a, n);
printf ("Sorted items : ");
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
return 0;
}
Enter number of items to be sorted 6
Enter items:567 789 121 212 563 562
After pass 1 : 121 212 562 563 567 789
After pass 2 : 212 121 562 563 567 789
After pass 3 : 121 212 562 563 567 789
Sorted items : 121 212 562 563 567 789
|
[
{
"code": null,
"e": 1218,
"s": 1062,
"text": "A sorting algorithm is an algorithm that puts components of a listing in a certain order. The most-used orders are numerical order and lexicographic order."
},
{
"code": null,
"e": 1353,
"s": 1218,
"text": "The Radix sort is a non-comparative sorting algorithm. The Radix sort algorithm is the most preferred algorithm for the unsorted list."
},
{
"code": null,
"e": 1882,
"s": 1353,
"text": "It sorts the elements by initially grouping the individual digits of the same place value. The idea of Radix Sort is to do digit by digit sort starting from least significant digit(LSD) to the most significant digit(MSD), according to their increasing/decreasing order. Radix sort is a small method that is used several times when alphabetizing an oversized list of names. Specifically, the list of names is initially sorted according to the first letter of every name, that is, the names are organized in twenty-six categories."
},
{
"code": null,
"e": 2084,
"s": 1882,
"text": "Let us review the following illustration to understand clearly about the working of the radix sort algorithm. Clearly, the number of pass/iteration depends on the size of the highest individual number."
},
{
"code": null,
"e": 2239,
"s": 2084,
"text": "In the above example, the primary column is input. The remaining columns show\nthe list after successive sorts on increasingly significant digits position."
},
{
"code": null,
"e": 2281,
"s": 2239,
"text": "Complexity Analysis of Radix Sort O(m.n)."
},
{
"code": null,
"e": 2494,
"s": 2281,
"text": "However, if we glance at these 2 values, the size of the keys is comparatively small in comparison to the number of keys. as an example, if we've six-digit keys, we might have 1,000,000 totally different records."
},
{
"code": null,
"e": 2603,
"s": 2494,
"text": "Here, we tend to see that the size of the keys isn't important, and this algorithm is of linear quality O(n)"
},
{
"code": null,
"e": 2826,
"s": 2603,
"text": "Radix_sort (list, n)\nshift = 1\nfor loop = 1 to keysize do\n for entry = 1 to n do\n bucketnumber = (list[entry].key / shift) mod 10\n append (bucket[bucketnumber], list[entry])\nlist = combinebuckets()\nshift = shift * 10"
},
{
"code": null,
"e": 2871,
"s": 2826,
"text": "This is a C Program to implement Radix Sort."
},
{
"code": null,
"e": 2882,
"s": 2871,
"text": " Live Demo"
},
{
"code": null,
"e": 4153,
"s": 2882,
"text": "#include<stdio.h>\nint get_max (int a[], int n){\n int max = a[0];\n for (int i = 1; i < n; i++)\n if (a[i] > max)\n max = a[i];\n return max;\n}\nvoid radix_sort (int a[], int n){\n int bucket[10][10], bucket_cnt[10];\n int i, j, k, r, NOP = 0, divisor = 1, lar, pass;\n lar = get_max (a, n);\n while (lar > 0){\n NOP++;\n lar /= 10;\n }\n for (pass = 0; pass < NOP; pass++){\n for (i = 0; i < 10; i++){\n bucket_cnt[i] = 0;\n }\n for (i = 0; i < n; i++){\n r = (a[i] / divisor) % 10;\n bucket[r][bucket_cnt[r]] = a[i];\n bucket_cnt[r] += 1;\n }\n i = 0;\n for (k = 0; k < 10; k++){\n for (j = 0; j < bucket_cnt[k]; j++){\n a[i] = bucket[k][j];\n i++;\n }\n }\n divisor *= 10;\n printf (\"After pass %d : \", pass + 1);\n for (i = 0; i < n; i++)\n printf (\"%d \", a[i]);\n printf (\"\\n\");\n }\n}\nint main (){\n int i, n, a[10];\n printf (\"Enter the number of items to be sorted: \");\n scanf (\"%d\", &n);\n printf (\"Enter items: \");\n for (i = 0; i < n; i++){\n scanf (\"%d\", &a[i]);\n }\n radix_sort (a, n);\n printf (\"Sorted items : \");\n for (i = 0; i < n; i++)\n printf (\"%d \", a[i]);\n printf (\"\\n\");\n return 0;\n}"
},
{
"code": null,
"e": 4382,
"s": 4153,
"text": "Enter number of items to be sorted 6\nEnter items:567 789 121 212 563 562\nAfter pass 1 : 121 212 562 563 567 789\nAfter pass 2 : 212 121 562 563 567 789\nAfter pass 3 : 121 212 562 563 567 789\nSorted items : 121 212 562 563 567 789"
}
] |
Bootstrap .tooltip("hide") method
|
Use the tooltip(βhideβ) method in Bootstrap to hide the tooltip. The tooltip hides on button click as shown below β
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('hide');
});
Above the data-toggle attribute can be seen which we set before on <a> element. Now the toggle will generate from the link when the button is clicked β
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">
Tooltip will be visible here
</a>
You can try to run the following code to implement the tooltip(βhideβ) method β
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Demo</h3>
<a href="#" data-toggle="tooltip" title="Tooltip is visible!">Tooltip will be visible here</a>
<div>
<button type="button" class="btn btn-primary">Show Tooltip</button>
<button type="button" class="btn btn-default">Hide Tooltip</button>
</div>
</div>
<script>
$(document).ready(function(){
$(".btn-primary").click(function(){
$("[data-toggle='tooltip']").tooltip('show');
});
$(".btn-default").click(function(){
$("[data-toggle='tooltip']").tooltip('hide');
});
});
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1178,
"s": 1062,
"text": "Use the tooltip(βhideβ) method in Bootstrap to hide the tooltip. The tooltip hides on button click as shown below β"
},
{
"code": null,
"e": 1266,
"s": 1178,
"text": "$(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('hide');\n});"
},
{
"code": null,
"e": 1418,
"s": 1266,
"text": "Above the data-toggle attribute can be seen which we set before on <a> element. Now the toggle will generate from the link when the button is clicked β"
},
{
"code": null,
"e": 1517,
"s": 1418,
"text": "<a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">\n Tooltip will be visible here\n</a>"
},
{
"code": null,
"e": 1597,
"s": 1517,
"text": "You can try to run the following code to implement the tooltip(βhideβ) method β"
},
{
"code": null,
"e": 1607,
"s": 1597,
"text": "Live Demo"
},
{
"code": null,
"e": 2694,
"s": 1607,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/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/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container\">\n <h3>Demo</h3>\n <a href=\"#\" data-toggle=\"tooltip\" title=\"Tooltip is visible!\">Tooltip will be visible here</a>\n <div>\n <button type=\"button\" class=\"btn btn-primary\">Show Tooltip</button>\n <button type=\"button\" class=\"btn btn-default\">Hide Tooltip</button>\n </div> \n</div>\n\n<script>\n $(document).ready(function(){\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('show');\n });\n $(\".btn-default\").click(function(){\n $(\"[data-toggle='tooltip']\").tooltip('hide');\n });\n });\n</script>\n\n</body>\n</html>"
}
] |
Pandas Sidetable Just Announced. An informative and insightful overview... | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
|
Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of data science projects. It provides numerous functions and methods that are quite useful in data analysis.
Although the built-in functions of Pandas are capable of performing efficient data analysis, custom made functions or libraries add value to Pandas. In this post, we will explore one of these add-ons.
Yesterday, Chris Moffitt announced a new pandas utility library called sidetable. Here is the github repo of sidetable. I find it quite useful and plan to apply in my daily analyses. Thatβs why I wanted to share and spread the word by working through some examples.
Sidetable creates a frequency table based on selected columns. Consider we have a dataset that contains some measurements on a categorical variable (e.g. model). We have many different models and each model has many observations (rows). By using sidetable, we get an overview that shows how much each model occupies in the dataset. This can also be achieved using value_counts function of pandas but sidetable is more informative as we will see in the examples.
We first need to install it with pip or !pip if you use a jupyter notebook:
!pip install sidetable
Then import it:
import pandas as pdimport sidetable
We can now use stb as an accessor on dataframes. I will use US cars dataset available here on kaggle. It contains data on used cars that are sold at auctions.
df = pd.read_csv("/content/USA_cars_datasets.csv")#drop redundant columnsdf.drop(['Unnamed: 0','vin','lot'], axis=1, inplace=True)df.head()
We may want to see what the dominating brands are. One way is to use value_counts function. Top 10 brands in terms of the number of occurrences in the dataset:
df.brand.value_counts()[:10]ford 1235 dodge 432 nissan 312 chevrolet 297 gmc 42 jeep 30 chrysler 18 bmw 17 hyundai 15 kia 13 Name: brand, dtype: int64
We can get the frequency ratios by using normalize parameter:
df.brand.value_counts(normalize=True)[:10]ford 0.494198 dodge 0.172869 nissan 0.124850 chevrolet 0.118848 gmc 0.016807 jeep 0.012005 chrysler 0.007203 bmw 0.006803 hyundai 0.006002 kia 0.005202 Name: brand, dtype: float64
Almost 50% of the cars in the dataset are Ford. It is more informative than seeing just the counts. Sidetable takes it one step further.
df.stb.freq(['brand'])[:10]
Sidetable returns both count and percent for each brand as well as cumulative values. It is definitely more informative than value_counts. We get more insight in terms of the distribution in the dataset. One extra feature that comes with cumulative values is that we can set a threshold on cumulative percent. Then, the categories after threshold is reached are marked as βothersβ. We can also specify a label for βotherβ using other_label parameter. For instance, we may want to see the brands that constitutes 90% of the dataset.
df.stb.freq(['brand'], thresh=.9, other_label='other brands')
We can also pass multiple columns and see more specific distribution. Letβs see the top brand-year combinations in the dataset.
df.stb.freq(['brand','year'], thresh=.5)
Ford dominates the dataset by having a share of 50%. Most of the ford cars are 2019 model which contains 19% of the entire dataset. Please note that 19% indicates the ratio in the entire dataset, not only in the ford brand. To get the distribution within the ford brand, we can apply a filter to the dataframe.
df[df.brand == 'ford'].stb.freq(['year'], thresh=.9)
As we can see, 2019 model ford cars are 38% of all the ford brand cars. Recall from the previous example, 2019 model ford cars occupied 19% of the entire dataset.
Another useful feature of sidetable is that it provides distribution based on a value. For instance, we can check the total price of the cars in each brand. The column to be aggreated is passed to the value parameter.
df.stb.freq(['brand'], value='price', thresh=.95)
The total price of the ford cars in the dataset is more 26 million which is 57% of the total price of all cars. Recall from previous examples that 49% of all the cars in the dataset is ford brand. In terms of total price, the rate goes up to 57% which indicates the average price of ford cars is more than the average price of other brands. There are, of course, other features that have an effect on the price such as year, mileage, title status and so on. But, it provides a general insight.
If the format of the values does not seem appealing, it can be changed using style parameter.
df.stb.freq(['brand'], value='price', thresh=.95, style=True)
I think the success and prevalence of Pandas come from the versatile, powerful and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. The custom made utility libraries added on Pandas optimize certain operations and bring more value to Pandas. Thanks again to Chris Moffitt for this valuable tool.
Since a big portion of time spent on a data science project is spent during data cleaning and preprocessing steps, Pandas is a valuable asset to have in your arsenal.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 388,
"s": 171,
"text": "Pandas is a very powerful and versatile Python data analysis library that expedites the preprocessing steps of data science projects. It provides numerous functions and methods that are quite useful in data analysis."
},
{
"code": null,
"e": 589,
"s": 388,
"text": "Although the built-in functions of Pandas are capable of performing efficient data analysis, custom made functions or libraries add value to Pandas. In this post, we will explore one of these add-ons."
},
{
"code": null,
"e": 855,
"s": 589,
"text": "Yesterday, Chris Moffitt announced a new pandas utility library called sidetable. Here is the github repo of sidetable. I find it quite useful and plan to apply in my daily analyses. Thatβs why I wanted to share and spread the word by working through some examples."
},
{
"code": null,
"e": 1317,
"s": 855,
"text": "Sidetable creates a frequency table based on selected columns. Consider we have a dataset that contains some measurements on a categorical variable (e.g. model). We have many different models and each model has many observations (rows). By using sidetable, we get an overview that shows how much each model occupies in the dataset. This can also be achieved using value_counts function of pandas but sidetable is more informative as we will see in the examples."
},
{
"code": null,
"e": 1393,
"s": 1317,
"text": "We first need to install it with pip or !pip if you use a jupyter notebook:"
},
{
"code": null,
"e": 1416,
"s": 1393,
"text": "!pip install sidetable"
},
{
"code": null,
"e": 1432,
"s": 1416,
"text": "Then import it:"
},
{
"code": null,
"e": 1468,
"s": 1432,
"text": "import pandas as pdimport sidetable"
},
{
"code": null,
"e": 1627,
"s": 1468,
"text": "We can now use stb as an accessor on dataframes. I will use US cars dataset available here on kaggle. It contains data on used cars that are sold at auctions."
},
{
"code": null,
"e": 1767,
"s": 1627,
"text": "df = pd.read_csv(\"/content/USA_cars_datasets.csv\")#drop redundant columnsdf.drop(['Unnamed: 0','vin','lot'], axis=1, inplace=True)df.head()"
},
{
"code": null,
"e": 1927,
"s": 1767,
"text": "We may want to see what the dominating brands are. One way is to use value_counts function. Top 10 brands in terms of the number of occurrences in the dataset:"
},
{
"code": null,
"e": 2161,
"s": 1927,
"text": "df.brand.value_counts()[:10]ford 1235 dodge 432 nissan 312 chevrolet 297 gmc 42 jeep 30 chrysler 18 bmw 17 hyundai 15 kia 13 Name: brand, dtype: int64"
},
{
"code": null,
"e": 2223,
"s": 2161,
"text": "We can get the frequency ratios by using normalize parameter:"
},
{
"code": null,
"e": 2513,
"s": 2223,
"text": "df.brand.value_counts(normalize=True)[:10]ford 0.494198 dodge 0.172869 nissan 0.124850 chevrolet 0.118848 gmc 0.016807 jeep 0.012005 chrysler 0.007203 bmw 0.006803 hyundai 0.006002 kia 0.005202 Name: brand, dtype: float64"
},
{
"code": null,
"e": 2650,
"s": 2513,
"text": "Almost 50% of the cars in the dataset are Ford. It is more informative than seeing just the counts. Sidetable takes it one step further."
},
{
"code": null,
"e": 2678,
"s": 2650,
"text": "df.stb.freq(['brand'])[:10]"
},
{
"code": null,
"e": 3210,
"s": 2678,
"text": "Sidetable returns both count and percent for each brand as well as cumulative values. It is definitely more informative than value_counts. We get more insight in terms of the distribution in the dataset. One extra feature that comes with cumulative values is that we can set a threshold on cumulative percent. Then, the categories after threshold is reached are marked as βothersβ. We can also specify a label for βotherβ using other_label parameter. For instance, we may want to see the brands that constitutes 90% of the dataset."
},
{
"code": null,
"e": 3272,
"s": 3210,
"text": "df.stb.freq(['brand'], thresh=.9, other_label='other brands')"
},
{
"code": null,
"e": 3400,
"s": 3272,
"text": "We can also pass multiple columns and see more specific distribution. Letβs see the top brand-year combinations in the dataset."
},
{
"code": null,
"e": 3441,
"s": 3400,
"text": "df.stb.freq(['brand','year'], thresh=.5)"
},
{
"code": null,
"e": 3752,
"s": 3441,
"text": "Ford dominates the dataset by having a share of 50%. Most of the ford cars are 2019 model which contains 19% of the entire dataset. Please note that 19% indicates the ratio in the entire dataset, not only in the ford brand. To get the distribution within the ford brand, we can apply a filter to the dataframe."
},
{
"code": null,
"e": 3805,
"s": 3752,
"text": "df[df.brand == 'ford'].stb.freq(['year'], thresh=.9)"
},
{
"code": null,
"e": 3968,
"s": 3805,
"text": "As we can see, 2019 model ford cars are 38% of all the ford brand cars. Recall from the previous example, 2019 model ford cars occupied 19% of the entire dataset."
},
{
"code": null,
"e": 4186,
"s": 3968,
"text": "Another useful feature of sidetable is that it provides distribution based on a value. For instance, we can check the total price of the cars in each brand. The column to be aggreated is passed to the value parameter."
},
{
"code": null,
"e": 4236,
"s": 4186,
"text": "df.stb.freq(['brand'], value='price', thresh=.95)"
},
{
"code": null,
"e": 4730,
"s": 4236,
"text": "The total price of the ford cars in the dataset is more 26 million which is 57% of the total price of all cars. Recall from previous examples that 49% of all the cars in the dataset is ford brand. In terms of total price, the rate goes up to 57% which indicates the average price of ford cars is more than the average price of other brands. There are, of course, other features that have an effect on the price such as year, mileage, title status and so on. But, it provides a general insight."
},
{
"code": null,
"e": 4824,
"s": 4730,
"text": "If the format of the values does not seem appealing, it can be changed using style parameter."
},
{
"code": null,
"e": 4886,
"s": 4824,
"text": "df.stb.freq(['brand'], value='price', thresh=.95, style=True)"
},
{
"code": null,
"e": 5251,
"s": 4886,
"text": "I think the success and prevalence of Pandas come from the versatile, powerful and easy-to-use functions to manipulate and analyze data. There are almost always multiple ways to do a task with Pandas. The custom made utility libraries added on Pandas optimize certain operations and bring more value to Pandas. Thanks again to Chris Moffitt for this valuable tool."
},
{
"code": null,
"e": 5418,
"s": 5251,
"text": "Since a big portion of time spent on a data science project is spent during data cleaning and preprocessing steps, Pandas is a valuable asset to have in your arsenal."
}
] |
Web Scraping with Beautiful Soup β A Use Case | by Bety Rodriguez-Milla | Towards Data Science
|
In this post, I will give a brief introduction to obtaining data from a webpage, i.e., web scraping, using Python and libraries such as Requests to get the data and Beautiful Soup to parse it. Web scraping becomes necessary when a website does not have an API, or one that suits your needs.
As an example, I use a webpage that has a consistent HTML structure, but this approach can be generalized. While there are some frameworks, such as Scrapy, that can provide such service, I decided to this as a learning experience.
A not-for-profit organization wants to reach out to the Community Foundations of Canada (CFC) sites across the nation. They asked me to find each contact person and their mailing address, and put all the information in a special format in a spreadsheet.
Doing this task manually, by copy-pasting each required field into the spreadsheet, would mean doing this 195 (foundations) * 11 (fields) = 2145 times! So my next thought was to automate the procedure by scraping the CFC website.
Fortunately, all the CFC information is included in their website in a straightforward schema.
According to Ryan Mitchellβs book, Web Scraping with Python (OβReilly), it is the practice of gathering data through any means other than API. One can write a program that queries web servers, requests and retrieves data, parses it to extract information, and stores it to be analyzed later.
The first step into web scraping is to take a deep look at the page you are trying to scrape, you will need to open βShow/View Page Sourceβ in the developer menu of the web browser of your choice. As Mitchell says, if you can see it in your browser, you can access it via a Python script. And, if you can access it, you can store it in a database to retrieve and analyze.
While inspecting the CFC webpage, few things become relevant. The CFC siteβs provinces are enclosed in <h2> HTML headings, while the links and names of the foundations are in <h3> headings. Also, the links include the text βcfc_locationsβ, which will help distinguish them from any other link.
How about each of those links? Letβs inspect one:
Neatly packaged, with consistent HTML structure, the information comes in a <div> container. The address is in a paragraph whose CSS class includes the keyword βlocationβ and the contactβs name and title are in the βmeta-line contactβ class. While the province is not included here, one could obtain it from the previous page.
For these tasks, I chose to use the Requests: HTTP for Humans library:
session = requests.Session()
However, this will send the following header,
>>> session.headers['User-Agent']'python-requests/2.19.1'
We are basically telling their website that someone is scraping their site using Python. Some websites actually block these types of requests. In general, one wants to make the request to look and behave as humanly as possible. One way to do that is to change the headers sent with the request.
If you are wondering what headers your browser is sending, you may want to take a look at https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending. In my case, I changed the headers to
my_headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", "Accept":"text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,image/apng,*/*;q=0.8"}
Another important thing to do is to check the siteβs robots.txt file to make sure you are not violating their policies. The file indicates which areas of the website should not be processed or scanned by all or certain user agents. In our case, robots.txt only disallows scraping /wp-admin/.
The next step is to retrieve the information with the Requests library,
url = 'https://communityfoundations.ca/find-a-community-foundation/'response = session.get(url, headers=my_headers)
Everything contained in that webpage is now in the response object.
How about parsing the information we just obtained? This is where the Beautiful Soup (BS4) library comes in. BS4 is a Python library for parsing HTML and XML documents β even for pages with malformed markup or poorly designed. It provides simple methods to navigate, search, and modify parse trees. So letβs create a soup!
html_soup = BeautifulSoup(response.text, 'html.parser')
We can now navigate and search the html_soup. For this, BS4 has some very useful functions, among those, it is the function find_all( ), in which one can make use of regular expressions and lambda functions. One can also refer to attributes to access the search results, such as, .name and .text:
container = html_soup.find_all(["h2", "h3"], class_=lambda x: x != 'hidden')for lines in container: if lines.name == 'h2': province = lines.text print('In', province, "\n") if lines.name == 'h3': foundation = lines.text print('Foundation name:', foundation) print('Foundation url:', lines.find_all("a", href=re.compile("cfc_locations"))[0].get('href'), "\n")
The next step is query and retrieve the data for each of the foundationβs URLs. We have to keep in mind two things. One, we need to query the server only once, since the data will be then stored locally. And two, we need to be polite, we do not want to overload the server with requests that can break it or that can time out. And this is where the time.sleep( ) function comes up. In this case, I added 10 seconds between requests.
subresponse = []for lines in container: if lines.name == 'h3': url_fou = lines.find_all("a", href=re.compile("cfc_locations"))[0].get('href') subresponse.append(session.get(url_fou, headers=my_headers)) time.sleep(10)
We can now parse the data with BS4 and proceed to extract the rest of the information, such as the address, which in the case of the CFC format, one can use regular expressions to split it by the vertical lines included in the text.
html_subsoup = []for counter in range(1, len(subresponse)): html_subsoup.append(BeautifulSoup(subresponse[counter].text, 'html.parser')) c_location = html_subsoup[counter].find_all('p', class_='meta-line location') address_array = re.split(r' \| ', c_location[0].text) print(address_array)
Similarly, we proceed with the personβs name, title, etc.
The other Python library used here is Genderize, as the title prefixing the contactβs name is also required (Mr. or Ms.) This library is a client for the Genderize.io web service, its API is free, but limited at 1000 names/day. So one should not debug the code with it!
Genderize will return βmaleβ or βfemaleβ given the name, so I create a dictionary to return the prefix.
>>> genderDict = {"male": 'Mr.', "female": 'Ms.'}>>> gen = Genderize().get(['John'])[0]['gender']>>> print(genderDict.get(gen, "None"))Mr.
After working with all the data (the full code can be found here), the last step is to write the information into a pandas dataframe and write it to a CSV file.
df = pd.DataFrame({'Organization': organization, 'Title': gender_title, 'Addressee': person, 'Addressee Job Title': person_title, 'Civic Address 1 (Street Address)': street, 'Civic Address 2 (PO Box)': pobox, 'Municipality': municipality, 'Province or Territory': provinces, 'Postal Code': postalCode, 'Phone': phone, 'Website': org_url })cols = ['Organization', 'Title', {add in here the others}]df.to_csv('data/cfcMailingAddresses.csv', encoding='utf-8', index=False, columns=cols)
Here is a snapshot of the CSV file:
While there is room for improvement, such as names that were not found in the genderize database, or addressing Quebecers by M. or Mme, the script served its general purpose. One can further refine the code by adding assertions and throwing exceptions.
As part of this learning experience, I decided to try two Natural Language Processing (NLP) libraries, NLTK and spaCy, to parse the address. Here are the results.
NLTK did not give the proper tags for an address. Most of the tokens were identified as nouns, including a place such as Banff.
def preprocess_without_stopwords(sent): sent = nltk.word_tokenize(sent) sent = [word for word in sent if word not in en_stop] sent = nltk.pos_tag(sent) return sentpreprocessed_address = preprocess_without_stopwords(address_test)
spaCy did not give the proper tags for an address either. While it did better than NLTK by identifying Banff Avenue as a place, Banff was identified as person.
addr = nlp(address_test)sentences = [x for x in addr.sents]displacy.render(nlp(str(sentences[0])), jupyter=True, style='ent')
Training a model on geographical data could be another very interesting project on its own!
Full jupyter notebook on GitHub: https://github.com/brodriguezmilla/WebScrapingCFCBS4
|
[
{
"code": null,
"e": 463,
"s": 172,
"text": "In this post, I will give a brief introduction to obtaining data from a webpage, i.e., web scraping, using Python and libraries such as Requests to get the data and Beautiful Soup to parse it. Web scraping becomes necessary when a website does not have an API, or one that suits your needs."
},
{
"code": null,
"e": 694,
"s": 463,
"text": "As an example, I use a webpage that has a consistent HTML structure, but this approach can be generalized. While there are some frameworks, such as Scrapy, that can provide such service, I decided to this as a learning experience."
},
{
"code": null,
"e": 948,
"s": 694,
"text": "A not-for-profit organization wants to reach out to the Community Foundations of Canada (CFC) sites across the nation. They asked me to find each contact person and their mailing address, and put all the information in a special format in a spreadsheet."
},
{
"code": null,
"e": 1178,
"s": 948,
"text": "Doing this task manually, by copy-pasting each required field into the spreadsheet, would mean doing this 195 (foundations) * 11 (fields) = 2145 times! So my next thought was to automate the procedure by scraping the CFC website."
},
{
"code": null,
"e": 1273,
"s": 1178,
"text": "Fortunately, all the CFC information is included in their website in a straightforward schema."
},
{
"code": null,
"e": 1565,
"s": 1273,
"text": "According to Ryan Mitchellβs book, Web Scraping with Python (OβReilly), it is the practice of gathering data through any means other than API. One can write a program that queries web servers, requests and retrieves data, parses it to extract information, and stores it to be analyzed later."
},
{
"code": null,
"e": 1937,
"s": 1565,
"text": "The first step into web scraping is to take a deep look at the page you are trying to scrape, you will need to open βShow/View Page Sourceβ in the developer menu of the web browser of your choice. As Mitchell says, if you can see it in your browser, you can access it via a Python script. And, if you can access it, you can store it in a database to retrieve and analyze."
},
{
"code": null,
"e": 2231,
"s": 1937,
"text": "While inspecting the CFC webpage, few things become relevant. The CFC siteβs provinces are enclosed in <h2> HTML headings, while the links and names of the foundations are in <h3> headings. Also, the links include the text βcfc_locationsβ, which will help distinguish them from any other link."
},
{
"code": null,
"e": 2281,
"s": 2231,
"text": "How about each of those links? Letβs inspect one:"
},
{
"code": null,
"e": 2608,
"s": 2281,
"text": "Neatly packaged, with consistent HTML structure, the information comes in a <div> container. The address is in a paragraph whose CSS class includes the keyword βlocationβ and the contactβs name and title are in the βmeta-line contactβ class. While the province is not included here, one could obtain it from the previous page."
},
{
"code": null,
"e": 2679,
"s": 2608,
"text": "For these tasks, I chose to use the Requests: HTTP for Humans library:"
},
{
"code": null,
"e": 2708,
"s": 2679,
"text": "session = requests.Session()"
},
{
"code": null,
"e": 2754,
"s": 2708,
"text": "However, this will send the following header,"
},
{
"code": null,
"e": 2812,
"s": 2754,
"text": ">>> session.headers['User-Agent']'python-requests/2.19.1'"
},
{
"code": null,
"e": 3107,
"s": 2812,
"text": "We are basically telling their website that someone is scraping their site using Python. Some websites actually block these types of requests. In general, one wants to make the request to look and behave as humanly as possible. One way to do that is to change the headers sent with the request."
},
{
"code": null,
"e": 3314,
"s": 3107,
"text": "If you are wondering what headers your browser is sending, you may want to take a look at https://www.whatismybrowser.com/detect/what-http-headers-is-my-browser-sending. In my case, I changed the headers to"
},
{
"code": null,
"e": 3601,
"s": 3314,
"text": "my_headers = {\"User-Agent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\", \"Accept\":\"text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,image/apng,*/*;q=0.8\"}"
},
{
"code": null,
"e": 3893,
"s": 3601,
"text": "Another important thing to do is to check the siteβs robots.txt file to make sure you are not violating their policies. The file indicates which areas of the website should not be processed or scanned by all or certain user agents. In our case, robots.txt only disallows scraping /wp-admin/."
},
{
"code": null,
"e": 3965,
"s": 3893,
"text": "The next step is to retrieve the information with the Requests library,"
},
{
"code": null,
"e": 4081,
"s": 3965,
"text": "url = 'https://communityfoundations.ca/find-a-community-foundation/'response = session.get(url, headers=my_headers)"
},
{
"code": null,
"e": 4149,
"s": 4081,
"text": "Everything contained in that webpage is now in the response object."
},
{
"code": null,
"e": 4472,
"s": 4149,
"text": "How about parsing the information we just obtained? This is where the Beautiful Soup (BS4) library comes in. BS4 is a Python library for parsing HTML and XML documents β even for pages with malformed markup or poorly designed. It provides simple methods to navigate, search, and modify parse trees. So letβs create a soup!"
},
{
"code": null,
"e": 4528,
"s": 4472,
"text": "html_soup = BeautifulSoup(response.text, 'html.parser')"
},
{
"code": null,
"e": 4825,
"s": 4528,
"text": "We can now navigate and search the html_soup. For this, BS4 has some very useful functions, among those, it is the function find_all( ), in which one can make use of regular expressions and lambda functions. One can also refer to attributes to access the search results, such as, .name and .text:"
},
{
"code": null,
"e": 5272,
"s": 4825,
"text": "container = html_soup.find_all([\"h2\", \"h3\"], class_=lambda x: x != 'hidden')for lines in container: if lines.name == 'h2': province = lines.text print('In', province, \"\\n\") if lines.name == 'h3': foundation = lines.text print('Foundation name:', foundation) print('Foundation url:', lines.find_all(\"a\", href=re.compile(\"cfc_locations\"))[0].get('href'), \"\\n\")"
},
{
"code": null,
"e": 5705,
"s": 5272,
"text": "The next step is query and retrieve the data for each of the foundationβs URLs. We have to keep in mind two things. One, we need to query the server only once, since the data will be then stored locally. And two, we need to be polite, we do not want to overload the server with requests that can break it or that can time out. And this is where the time.sleep( ) function comes up. In this case, I added 10 seconds between requests."
},
{
"code": null,
"e": 6004,
"s": 5705,
"text": "subresponse = []for lines in container: if lines.name == 'h3': url_fou = lines.find_all(\"a\", href=re.compile(\"cfc_locations\"))[0].get('href') subresponse.append(session.get(url_fou, headers=my_headers)) time.sleep(10)"
},
{
"code": null,
"e": 6237,
"s": 6004,
"text": "We can now parse the data with BS4 and proceed to extract the rest of the information, such as the address, which in the case of the CFC format, one can use regular expressions to split it by the vertical lines included in the text."
},
{
"code": null,
"e": 6619,
"s": 6237,
"text": "html_subsoup = []for counter in range(1, len(subresponse)): html_subsoup.append(BeautifulSoup(subresponse[counter].text, 'html.parser')) c_location = html_subsoup[counter].find_all('p', class_='meta-line location') address_array = re.split(r' \\| ', c_location[0].text) print(address_array)"
},
{
"code": null,
"e": 6677,
"s": 6619,
"text": "Similarly, we proceed with the personβs name, title, etc."
},
{
"code": null,
"e": 6947,
"s": 6677,
"text": "The other Python library used here is Genderize, as the title prefixing the contactβs name is also required (Mr. or Ms.) This library is a client for the Genderize.io web service, its API is free, but limited at 1000 names/day. So one should not debug the code with it!"
},
{
"code": null,
"e": 7051,
"s": 6947,
"text": "Genderize will return βmaleβ or βfemaleβ given the name, so I create a dictionary to return the prefix."
},
{
"code": null,
"e": 7207,
"s": 7051,
"text": ">>> genderDict = {\"male\": 'Mr.', \"female\": 'Ms.'}>>> gen = Genderize().get(['John'])[0]['gender']>>> print(genderDict.get(gen, \"None\"))Mr."
},
{
"code": null,
"e": 7368,
"s": 7207,
"text": "After working with all the data (the full code can be found here), the last step is to write the information into a pandas dataframe and write it to a CSV file."
},
{
"code": null,
"e": 8060,
"s": 7368,
"text": "df = pd.DataFrame({'Organization': organization, 'Title': gender_title, 'Addressee': person, 'Addressee Job Title': person_title, 'Civic Address 1 (Street Address)': street, 'Civic Address 2 (PO Box)': pobox, 'Municipality': municipality, 'Province or Territory': provinces, 'Postal Code': postalCode, 'Phone': phone, 'Website': org_url })cols = ['Organization', 'Title', {add in here the others}]df.to_csv('data/cfcMailingAddresses.csv', encoding='utf-8', index=False, columns=cols)"
},
{
"code": null,
"e": 8096,
"s": 8060,
"text": "Here is a snapshot of the CSV file:"
},
{
"code": null,
"e": 8349,
"s": 8096,
"text": "While there is room for improvement, such as names that were not found in the genderize database, or addressing Quebecers by M. or Mme, the script served its general purpose. One can further refine the code by adding assertions and throwing exceptions."
},
{
"code": null,
"e": 8512,
"s": 8349,
"text": "As part of this learning experience, I decided to try two Natural Language Processing (NLP) libraries, NLTK and spaCy, to parse the address. Here are the results."
},
{
"code": null,
"e": 8640,
"s": 8512,
"text": "NLTK did not give the proper tags for an address. Most of the tokens were identified as nouns, including a place such as Banff."
},
{
"code": null,
"e": 8881,
"s": 8640,
"text": "def preprocess_without_stopwords(sent): sent = nltk.word_tokenize(sent) sent = [word for word in sent if word not in en_stop] sent = nltk.pos_tag(sent) return sentpreprocessed_address = preprocess_without_stopwords(address_test)"
},
{
"code": null,
"e": 9041,
"s": 8881,
"text": "spaCy did not give the proper tags for an address either. While it did better than NLTK by identifying Banff Avenue as a place, Banff was identified as person."
},
{
"code": null,
"e": 9167,
"s": 9041,
"text": "addr = nlp(address_test)sentences = [x for x in addr.sents]displacy.render(nlp(str(sentences[0])), jupyter=True, style='ent')"
},
{
"code": null,
"e": 9259,
"s": 9167,
"text": "Training a model on geographical data could be another very interesting project on its own!"
}
] |
Java Data Types
|
As explained in the previous chapter, a variable in Java must be a specified data type:
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Try it Yourself Β»
Data types are divided into two groups:
Primitive data types - includes byte, short, int, long,
float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)
A primitive data type specifies the size and type of variable values, and it has no
additional methods.
There are eight primitive data types in Java:
Add the correct data type for the following variables:
myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A';
myBool = false;
myText = "Hello World";
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 88,
"s": 0,
"text": "As explained in the previous chapter, a variable in Java must be a specified data type:"
},
{
"code": null,
"e": 319,
"s": 88,
"text": "int myNum = 5; // Integer (whole number)\nfloat myFloatNum = 5.99f; // Floating point number\nchar myLetter = 'D'; // Character\nboolean myBool = true; // Boolean\nString myText = \"Hello\"; // String\n"
},
{
"code": null,
"e": 339,
"s": 319,
"text": "\nTry it Yourself Β»\n"
},
{
"code": null,
"e": 379,
"s": 339,
"text": "Data types are divided into two groups:"
},
{
"code": null,
"e": 469,
"s": 379,
"text": "Primitive data types - includes byte, short, int, long, \n float, double, boolean and char"
},
{
"code": null,
"e": 585,
"s": 469,
"text": "Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a later chapter)"
},
{
"code": null,
"e": 690,
"s": 585,
"text": "A primitive data type specifies the size and type of variable values, and it has no \nadditional methods."
},
{
"code": null,
"e": 736,
"s": 690,
"text": "There are eight primitive data types in Java:"
},
{
"code": null,
"e": 791,
"s": 736,
"text": "Add the correct data type for the following variables:"
},
{
"code": null,
"e": 884,
"s": 791,
"text": " myNum = 9;\n myFloatNum = 8.99f;\n myLetter = 'A';\n myBool = false;\n myText = \"Hello World\";\n"
},
{
"code": null,
"e": 903,
"s": 884,
"text": "Start the Exercise"
},
{
"code": null,
"e": 936,
"s": 903,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 978,
"s": 936,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1085,
"s": 978,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 1104,
"s": 1085,
"text": "help@w3schools.com"
}
] |
Searching Algorithms for 2D Arrays (Matrix)
|
27 Dec, 2021
Linear Search in 2D Array
Linear search is a simple and sequential searching algorithm. It is used to find a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed and In this way, any element is searched in a 2D array.
Below is the implementation for linear search in 2D arrays
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std;vector<int> linearSearch(vector<vector<int>> arr, int target){ for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < arr[i].size(); j++) { if (arr[i][j] == target) { return {i, j}; } } } return {-1, -1};} // Driver codeint main(){ vector<vector<int>> arr = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; vector<int> ans = linearSearch(arr, target); cout << "Element found at index: [" << ans[0] << " " <<ans[1] <<"]"; return 0;} // This code is contributed by Potta Lokesh
// Linear Search in 2D arraysimport java.util.Arrays; public class GFG { public static void main(String[] args) { int arr[][] = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; int ans[] = linearSearch(arr, target); System.out.println("Element found at index: " + Arrays.toString(ans)); } static int[] linearSearch(int[][] arr, int target) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; }}
# Python code for the above approachdef linearSearch (arr, target): for i in range(len(arr)): for j in range(len(arr[i])): if (arr[i][j] == target): return [i, j] return [-1, -1] # Driver codearr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]target = 89ans = linearSearch(arr, target)print(f"Element found at index: [{ans[0]} {ans[1]}]") # This code is contributed by Saurabh Jaiswal
// Linear Search in 2D arraysusing System; public class GFG { public static void Main(string[] args) { int[, ] arr = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; int[] ans = linearSearch(arr, target); Console.WriteLine("Element found at index: [" + ans[0] + "," + ans[1]+"]"); } static int[] linearSearch(int[, ] arr, int target) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { if (arr[i, j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; }} // This code is contributed by ukasp.
<script> // JavaScript code for the above approach const linearSearch = (arr, target) => { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { if (arr[i][j] == target) { return [i, j]; } } } return [-1, -1]; } // Driver code let arr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]; let target = 89; let ans = linearSearch(arr, target); document.write(`Element found at index: [${ans[0]} ${ans[1]}]`); // This code is contributed by rakeshsahni </script>
Element found at index: [1, 2]
The Time Complexity of linear search in a 2D array is O (N * M) where N is the number of rows and M is the number of columns.
Binary Search in a 2D Array
Binary search is an efficient method of searching in an array. Binary search works on sorted array. At each iteration the search space is divided in half, this is the reason why binary search is more efficient than linear search.
Why Binary Search is not useful for searching in unsorted arrays?
The basic condition to apply Binary Search anywhere in any algorithm is that the search space should be sorted. To perform a Binary search in the 2D array, the array needs to be sorted. Here is an unsorted 2D array is given, so applying Binary Search in an unsorted array is not possible. To apply Binary Search first the 2D array needs to be sorted in any order that itself takes (M*N)log(M*N) time. So the total time complexity to search any element here is O((M * N) log(M * N)) + O(N + M) which very poor when it is compared with the time complexity of Linear Search which is just O(N*M). Therefore, Linear Search is used for searching in an unsorted array, not Binary Search.
Below is the implementation for Binary search in 2D arrays
C++
Java
Python3
C#
Javascript
// Binary Search on sorted 2D array#include <bits/stdc++.h>using namespace std; vector<int> findAns(vector<vector<int>> arr, int target){ int r = 0; int c = arr[r].size() - 1; while (r < arr.size() && c >= 0) { if (arr[r] == target) { return { r, c }; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return { -1, -1 };} // Driver Codeint main(){ // Binary search in sorted matrix vector<vector<int>> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; vector<int> ans = findAns(arr, 12); cout << "Element found at index: ["; for(int i = 0; i < ans.size(); i++){ if(i == ans.size() - 1) cout << ans[i]; else cout << ans[i] << ", "; } cout << "]"; } // This code is contributed by Samim Hossain Mondal.
// Binary Search on sorted 2D arrayimport java.util.Arrays; class GFG { static int[] findAns(int[][] arr, int target) { int r = 0; int c = arr[r].length - 1; while (r < arr.length && c >= 0) { if (arr[r] == target) { return new int[] { r, c }; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return new int[] { -1, -1 }; } // Driver Code public static void main(String[] args) { // Binary search in sorted matrix int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int[] ans = findAns(arr, 12); System.out.println("Element found at index: " + Arrays.toString(ans)); }}
# Binary Search on sorted 2D arraydef findAns(arr, target): r = 0; c = len(arr[r]) - 1; while (r < len(arr) and c >= 0): if (arr[r] == target): return [r, c]; # Target lies in further row if (arr[r] < target): r += 1; # Target lies in previous column else: c -=1; return [ -1, -1]; # Driver Codeif __name__ == '__main__': # Binary search in sorted matrix arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; ans = findAns(arr, 12); print("Element found at index: ", ans); # This code contributed by shikhasingrajput
// Binary Search on sorted 2D arrayusing System;class GFG { static int[] findAns(int[, ] arr, int target) { int r = 0; int c = arr.GetLength(1) - 1; while (r < arr.GetLength(0) && c >= 0) { if (arr[r, c] == target) { return new int[] { r, c }; } // Target lies in further row if (arr[r, c] < target) { r++; } // Target lies in previous column else { c--; } } return new int[] { -1, -1 }; } // Driver Code public static void Main(string[] args) { // Binary search in sorted matrix int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int[] ans = findAns(arr, 12); Console.Write("Element found at index: ["); int i = 0; for (i = 0; i < ans.Length - 1; i++) Console.Write(ans[i] + " ,"); Console.Write(ans[i] + "]"); }} // This code is contributed by ukasp.
<script>// Binary Search on sorted 2D array function findAns(arr , target) { var r = 0; var c = arr[r].length - 1; while (r < arr.length && c >= 0) { if (arr[r] == target) { return [ r, c ]; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return [ -1, -1 ]; } // Driver Code // Binary search in sorted matrix var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ] ]; var ans = findAns(arr, 12); document.write("Element found at index: " + (ans)); // This code is contributed by shikhasingrajput</script>
Element found at index: [2, 3]
The Time Complexity of binary search in an already sorted 2D array is O (N + M) where N is the number of rows and M is the number of columns.
lokeshpotta20
rakeshsahni
_saurabh_jaiswal
ukasp
samim2000
shikhasingrajput
Binary Search
Arrays
Matrix
Searching
Arrays
Searching
Matrix
Binary Search
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
Longest Consecutive Subsequence
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Rotate a matrix by 90 degree in clockwise direction without using any extra space
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 54,
"s": 28,
"text": "Linear Search in 2D Array"
},
{
"code": null,
"e": 382,
"s": 54,
"text": "Linear search is a simple and sequential searching algorithm. It is used to find a particular element is present in the array or not by traversing every element in the array. While searching in the 2D array is exactly the same but here all the cells need to be traversed and In this way, any element is searched in a 2D array. "
},
{
"code": null,
"e": 441,
"s": 382,
"text": "Below is the implementation for linear search in 2D arrays"
},
{
"code": null,
"e": 445,
"s": 441,
"text": "C++"
},
{
"code": null,
"e": 450,
"s": 445,
"text": "Java"
},
{
"code": null,
"e": 458,
"s": 450,
"text": "Python3"
},
{
"code": null,
"e": 461,
"s": 458,
"text": "C#"
},
{
"code": null,
"e": 472,
"s": 461,
"text": "Javascript"
},
{
"code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std;vector<int> linearSearch(vector<vector<int>> arr, int target){ for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < arr[i].size(); j++) { if (arr[i][j] == target) { return {i, j}; } } } return {-1, -1};} // Driver codeint main(){ vector<vector<int>> arr = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; vector<int> ans = linearSearch(arr, target); cout << \"Element found at index: [\" << ans[0] << \" \" <<ans[1] <<\"]\"; return 0;} // This code is contributed by Potta Lokesh",
"e": 1135,
"s": 472,
"text": null
},
{
"code": "// Linear Search in 2D arraysimport java.util.Arrays; public class GFG { public static void main(String[] args) { int arr[][] = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; int ans[] = linearSearch(arr, target); System.out.println(\"Element found at index: \" + Arrays.toString(ans)); } static int[] linearSearch(int[][] arr, int target) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; }}",
"e": 1877,
"s": 1135,
"text": null
},
{
"code": "# Python code for the above approachdef linearSearch (arr, target): for i in range(len(arr)): for j in range(len(arr[i])): if (arr[i][j] == target): return [i, j] return [-1, -1] # Driver codearr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]target = 89ans = linearSearch(arr, target)print(f\"Element found at index: [{ans[0]} {ans[1]}]\") # This code is contributed by Saurabh Jaiswal",
"e": 2294,
"s": 1877,
"text": null
},
{
"code": "// Linear Search in 2D arraysusing System; public class GFG { public static void Main(string[] args) { int[, ] arr = { { 3, 12, 9 }, { 5, 2, 89 }, { 90, 45, 22 } }; int target = 89; int[] ans = linearSearch(arr, target); Console.WriteLine(\"Element found at index: [\" + ans[0] + \",\" + ans[1]+\"]\"); } static int[] linearSearch(int[, ] arr, int target) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) { if (arr[i, j] == target) { return new int[] { i, j }; } } } return new int[] { -1, -1 }; }} // This code is contributed by ukasp.",
"e": 3076,
"s": 2294,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach const linearSearch = (arr, target) => { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { if (arr[i][j] == target) { return [i, j]; } } } return [-1, -1]; } // Driver code let arr = [[3, 12, 9], [5, 2, 89], [90, 45, 22]]; let target = 89; let ans = linearSearch(arr, target); document.write(`Element found at index: [${ans[0]} ${ans[1]}]`); // This code is contributed by rakeshsahni </script>",
"e": 3679,
"s": 3076,
"text": null
},
{
"code": null,
"e": 3713,
"s": 3682,
"text": "Element found at index: [1, 2]"
},
{
"code": null,
"e": 3841,
"s": 3715,
"text": "The Time Complexity of linear search in a 2D array is O (N * M) where N is the number of rows and M is the number of columns."
},
{
"code": null,
"e": 3871,
"s": 3843,
"text": "Binary Search in a 2D Array"
},
{
"code": null,
"e": 4104,
"s": 3873,
"text": "Binary search is an efficient method of searching in an array. Binary search works on sorted array. At each iteration the search space is divided in half, this is the reason why binary search is more efficient than linear search. "
},
{
"code": null,
"e": 4172,
"s": 4106,
"text": "Why Binary Search is not useful for searching in unsorted arrays?"
},
{
"code": null,
"e": 4856,
"s": 4174,
"text": "The basic condition to apply Binary Search anywhere in any algorithm is that the search space should be sorted. To perform a Binary search in the 2D array, the array needs to be sorted. Here is an unsorted 2D array is given, so applying Binary Search in an unsorted array is not possible. To apply Binary Search first the 2D array needs to be sorted in any order that itself takes (M*N)log(M*N) time. So the total time complexity to search any element here is O((M * N) log(M * N)) + O(N + M) which very poor when it is compared with the time complexity of Linear Search which is just O(N*M). Therefore, Linear Search is used for searching in an unsorted array, not Binary Search. "
},
{
"code": null,
"e": 4917,
"s": 4858,
"text": "Below is the implementation for Binary search in 2D arrays"
},
{
"code": null,
"e": 4923,
"s": 4919,
"text": "C++"
},
{
"code": null,
"e": 4928,
"s": 4923,
"text": "Java"
},
{
"code": null,
"e": 4936,
"s": 4928,
"text": "Python3"
},
{
"code": null,
"e": 4939,
"s": 4936,
"text": "C#"
},
{
"code": null,
"e": 4950,
"s": 4939,
"text": "Javascript"
},
{
"code": "// Binary Search on sorted 2D array#include <bits/stdc++.h>using namespace std; vector<int> findAns(vector<vector<int>> arr, int target){ int r = 0; int c = arr[r].size() - 1; while (r < arr.size() && c >= 0) { if (arr[r] == target) { return { r, c }; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return { -1, -1 };} // Driver Codeint main(){ // Binary search in sorted matrix vector<vector<int>> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; vector<int> ans = findAns(arr, 12); cout << \"Element found at index: [\"; for(int i = 0; i < ans.size(); i++){ if(i == ans.size() - 1) cout << ans[i]; else cout << ans[i] << \", \"; } cout << \"]\"; } // This code is contributed by Samim Hossain Mondal.",
"e": 5853,
"s": 4950,
"text": null
},
{
"code": "// Binary Search on sorted 2D arrayimport java.util.Arrays; class GFG { static int[] findAns(int[][] arr, int target) { int r = 0; int c = arr[r].length - 1; while (r < arr.length && c >= 0) { if (arr[r] == target) { return new int[] { r, c }; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return new int[] { -1, -1 }; } // Driver Code public static void main(String[] args) { // Binary search in sorted matrix int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int[] ans = findAns(arr, 12); System.out.println(\"Element found at index: \" + Arrays.toString(ans)); }}",
"e": 6796,
"s": 5853,
"text": null
},
{
"code": "# Binary Search on sorted 2D arraydef findAns(arr, target): r = 0; c = len(arr[r]) - 1; while (r < len(arr) and c >= 0): if (arr[r] == target): return [r, c]; # Target lies in further row if (arr[r] < target): r += 1; # Target lies in previous column else: c -=1; return [ -1, -1]; # Driver Codeif __name__ == '__main__': # Binary search in sorted matrix arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; ans = findAns(arr, 12); print(\"Element found at index: \", ans); # This code contributed by shikhasingrajput",
"e": 7411,
"s": 6796,
"text": null
},
{
"code": "// Binary Search on sorted 2D arrayusing System;class GFG { static int[] findAns(int[, ] arr, int target) { int r = 0; int c = arr.GetLength(1) - 1; while (r < arr.GetLength(0) && c >= 0) { if (arr[r, c] == target) { return new int[] { r, c }; } // Target lies in further row if (arr[r, c] < target) { r++; } // Target lies in previous column else { c--; } } return new int[] { -1, -1 }; } // Driver Code public static void Main(string[] args) { // Binary search in sorted matrix int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; int[] ans = findAns(arr, 12); Console.Write(\"Element found at index: [\"); int i = 0; for (i = 0; i < ans.Length - 1; i++) Console.Write(ans[i] + \" ,\"); Console.Write(ans[i] + \"]\"); }} // This code is contributed by ukasp.",
"e": 8332,
"s": 7411,
"text": null
},
{
"code": "<script>// Binary Search on sorted 2D array function findAns(arr , target) { var r = 0; var c = arr[r].length - 1; while (r < arr.length && c >= 0) { if (arr[r] == target) { return [ r, c ]; } // Target lies in further row if (arr[r] < target) { r++; } // Target lies in previous column else { c--; } } return [ -1, -1 ]; } // Driver Code // Binary search in sorted matrix var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ] ]; var ans = findAns(arr, 12); document.write(\"Element found at index: \" + (ans)); // This code is contributed by shikhasingrajput</script>",
"e": 9224,
"s": 8332,
"text": null
},
{
"code": null,
"e": 9255,
"s": 9224,
"text": "Element found at index: [2, 3]"
},
{
"code": null,
"e": 9397,
"s": 9255,
"text": "The Time Complexity of binary search in an already sorted 2D array is O (N + M) where N is the number of rows and M is the number of columns."
},
{
"code": null,
"e": 9413,
"s": 9399,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 9425,
"s": 9413,
"text": "rakeshsahni"
},
{
"code": null,
"e": 9442,
"s": 9425,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 9448,
"s": 9442,
"text": "ukasp"
},
{
"code": null,
"e": 9458,
"s": 9448,
"text": "samim2000"
},
{
"code": null,
"e": 9475,
"s": 9458,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 9489,
"s": 9475,
"text": "Binary Search"
},
{
"code": null,
"e": 9496,
"s": 9489,
"text": "Arrays"
},
{
"code": null,
"e": 9503,
"s": 9496,
"text": "Matrix"
},
{
"code": null,
"e": 9513,
"s": 9503,
"text": "Searching"
},
{
"code": null,
"e": 9520,
"s": 9513,
"text": "Arrays"
},
{
"code": null,
"e": 9530,
"s": 9520,
"text": "Searching"
},
{
"code": null,
"e": 9537,
"s": 9530,
"text": "Matrix"
},
{
"code": null,
"e": 9551,
"s": 9537,
"text": "Binary Search"
},
{
"code": null,
"e": 9649,
"s": 9551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9681,
"s": 9649,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9728,
"s": 9681,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9753,
"s": 9728,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9784,
"s": 9753,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9816,
"s": 9784,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 9851,
"s": 9816,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 9882,
"s": 9851,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 9906,
"s": 9882,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 9953,
"s": 9906,
"text": "Find the number of islands | Set 1 (Using DFS)"
}
] |
isalpha() and isdigit() functions in C with cstring examples.
|
23 Jun, 2022
isalpha(c) is a function in C which can be used to check if the passed character is an alphabet or not. It returns a non-zero value if itβs an alphabet else it returns 0. For example, it returns non-zero values for βaβ to βzβ and βAβ to βZβ and zeroes for other characters.Similarly, isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if itβs a digit else it returns 0. For example, it returns a non-zero value for β0β to β9β and zero for others.Avoiding common errors : It is important to note this article does not cover strings! Only Cstrings. Cstrings are an array of single characters (char) in their behaviour. There are advantages and disadvantages to this.Example Problem : Given a cstring str, find the number of alphabetic letters and number of decimal digits in that cstring.Examples:
Input: 12abc12
Output: Alphabetic_letters = 3, Decimal_digits = 4
Input: 123 GeeksForGeeks is Number 1
Output: Alphabetic_letters = 21, Decimal_digits = 4
Explanation And Approach:
C
// C program to demonstrate working of isalpha() and// isdigit().#include <ctype.h>#include <stdio.h>#include <stdlib.h> int main(){ char str[] = "12abc12"; int alphabet = 0, number = 0, i; for (i = 0; str[i] != '\0'; i++) { // check for alphabets if (isalpha(str[i]) != 0) alphabet++; // check for decimal digits else if (isdigit(str[i]) != 0) number++; } printf("Alphabetic_letters = %d, " "Decimal_digits = %d\n", alphabet, number); return 0;}
Output:
Alphabetic_letters = 3, Decimal_digits = 4
Let us see the differences in a tabular form -:
Its syntax is -:
isalpha(int c);
Its syntax is -:
isdigit(int c);
This article is contributed by Mazhar Imam Khan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
BrenlyDrake
vardaangpt
mayank007rawa
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
Unordered Sets in C++ Standard Template Library
Enumeration (or enum) in C
Memory Layout of C Programs
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 926,
"s": 52,
"text": "isalpha(c) is a function in C which can be used to check if the passed character is an alphabet or not. It returns a non-zero value if itβs an alphabet else it returns 0. For example, it returns non-zero values for βaβ to βzβ and βAβ to βZβ and zeroes for other characters.Similarly, isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if itβs a digit else it returns 0. For example, it returns a non-zero value for β0β to β9β and zero for others.Avoiding common errors : It is important to note this article does not cover strings! Only Cstrings. Cstrings are an array of single characters (char) in their behaviour. There are advantages and disadvantages to this.Example Problem : Given a cstring str, find the number of alphabetic letters and number of decimal digits in that cstring.Examples: "
},
{
"code": null,
"e": 1082,
"s": 926,
"text": "Input: 12abc12\nOutput: Alphabetic_letters = 3, Decimal_digits = 4\n\nInput: 123 GeeksForGeeks is Number 1\nOutput: Alphabetic_letters = 21, Decimal_digits = 4"
},
{
"code": null,
"e": 1109,
"s": 1082,
"text": "Explanation And Approach: "
},
{
"code": null,
"e": 1111,
"s": 1109,
"text": "C"
},
{
"code": "// C program to demonstrate working of isalpha() and// isdigit().#include <ctype.h>#include <stdio.h>#include <stdlib.h> int main(){ char str[] = \"12abc12\"; int alphabet = 0, number = 0, i; for (i = 0; str[i] != '\\0'; i++) { // check for alphabets if (isalpha(str[i]) != 0) alphabet++; // check for decimal digits else if (isdigit(str[i]) != 0) number++; } printf(\"Alphabetic_letters = %d, \" \"Decimal_digits = %d\\n\", alphabet, number); return 0;}",
"e": 1658,
"s": 1111,
"text": null
},
{
"code": null,
"e": 1667,
"s": 1658,
"text": "Output: "
},
{
"code": null,
"e": 1710,
"s": 1667,
"text": "Alphabetic_letters = 3, Decimal_digits = 4"
},
{
"code": null,
"e": 1759,
"s": 1710,
"text": "Let us see the differences in a tabular form -: "
},
{
"code": null,
"e": 1776,
"s": 1759,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1792,
"s": 1776,
"text": "isalpha(int c);"
},
{
"code": null,
"e": 1809,
"s": 1792,
"text": "Its syntax is -:"
},
{
"code": null,
"e": 1825,
"s": 1809,
"text": "isdigit(int c);"
},
{
"code": null,
"e": 2250,
"s": 1825,
"text": "This article is contributed by Mazhar Imam Khan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 2262,
"s": 2250,
"text": "BrenlyDrake"
},
{
"code": null,
"e": 2273,
"s": 2262,
"text": "vardaangpt"
},
{
"code": null,
"e": 2287,
"s": 2273,
"text": "mayank007rawa"
},
{
"code": null,
"e": 2297,
"s": 2287,
"text": "C-Library"
},
{
"code": null,
"e": 2309,
"s": 2297,
"text": "CPP-Library"
},
{
"code": null,
"e": 2320,
"s": 2309,
"text": "C Language"
},
{
"code": null,
"e": 2324,
"s": 2320,
"text": "C++"
},
{
"code": null,
"e": 2328,
"s": 2324,
"text": "CPP"
},
{
"code": null,
"e": 2426,
"s": 2328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2448,
"s": 2426,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2473,
"s": 2448,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2521,
"s": 2473,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2548,
"s": 2521,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 2576,
"s": 2548,
"text": "Memory Layout of C Programs"
},
{
"code": null,
"e": 2594,
"s": 2576,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 2637,
"s": 2594,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2683,
"s": 2637,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 2726,
"s": 2683,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Django Introduction and Installation
|
03 Jul, 2022
Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks.When youβre building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use.
Itβs very easy to switch database in Django framework.It has built-in admin interface which makes easy to work with it.Django is fully functional framework that requires nothing else.It has thousands of additional packages available.It is very scalable.
Itβs very easy to switch database in Django framework.
It has built-in admin interface which makes easy to work with it.
Django is fully functional framework that requires nothing else.
It has thousands of additional packages available.
It is very scalable.
Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on the Django framework. ( Source )Sites like Hot Frameworks assess the popularity of a framework by counting the number of GitHub projects and StackOverflow questions for each platform, here Django is in 6th position. Web frameworks often refer to themselves as βopinionatedβ or βun-opinionatedβ based on opinions about the right way to handle any particular task. Django is somewhat opinionated, hence delivers the in both worlds( opinionated & un-opinionated ).
Versatility of DjangoDjango can build almost any type of website. It can also work with any client-side framework and can deliver content in any format such as HTML, JSON, XML etc. Some sites which can be built using Django are wikis, social networks, new sites etc.
SecuritySince Django framework is made for making web development easy, it has been engineered in such a way that it automatically do the right things to protect the website. For example, In the Django framework instead of putting a password in cookies, the hashed password is stored in it so that it canβt be fetched easily by hackers.
ScalabilityDjango web nodes have no stored state, they scale horizontally β just fire up more of them when you need them. Being able to do this is the essence of good scalability. Instagram and Disqus are two Django based products that have millions of active users, this is taken as an example of the scalability of Django.
PortabilityAll the codes of the Django framework are written in Python, which runs on many platforms. Which leads to run Django too in many platforms such as Linux, Windows and Mac OS.
Installation of Django
Install python3 if not installed in your system ( according to configuration of your system and OS) from here . Try to download the latest version of python itβs python3.6.4 this time.
Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for Linux and mac just open terminal in place of command prompt and go through the following commands.
Install pip- Open command prompt and enter following command-
python -m pip install -U pip
Install virtual environment- Enter following command in cmd-
pip install virtualenv
Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency which generally your system wouldnβt allow.Follow these steps to set up a virtual environment-Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate
Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate
Create a virtual environment by giving this command in cmd-virtualenv env_site
virtualenv env_site
Change directory to env_site by this command-cd env_site
cd env_site
Go to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate
cd Scripts
activate
Install Django- Install django by giving following command-pip install django
pip install django
Return to the env_site directory-cd ..
cd ..
Start a project by following command-django-admin startproject geeks_site
django-admin startproject geeks_site
Change directory to geeks_sitecd geeks_site
cd geeks_site
Start the server- Start the server by typing following command in cmd-python manage.py runserver
python manage.py runserver
To check whether server is running or not go to web browser and enter http://127.0.0.1:8000/ as url.
Benefits of Django Architecture β
Rapid Development
Loosely Coupled
Ease of Modification
Drawbacks of MVC Architecture β
Too much load on Model Component
Development Complexity is high
Two components are controlling View
NaveenArora
sayank2002
Python Django
Python
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, 2022"
},
{
"code": null,
"e": 518,
"s": 52,
"text": "Django is a Python-based web framework which allows you to quickly create web application without all of the installation or dependency problems that you normally will find with other frameworks.When youβre building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use."
},
{
"code": null,
"e": 772,
"s": 518,
"text": "Itβs very easy to switch database in Django framework.It has built-in admin interface which makes easy to work with it.Django is fully functional framework that requires nothing else.It has thousands of additional packages available.It is very scalable."
},
{
"code": null,
"e": 827,
"s": 772,
"text": "Itβs very easy to switch database in Django framework."
},
{
"code": null,
"e": 893,
"s": 827,
"text": "It has built-in admin interface which makes easy to work with it."
},
{
"code": null,
"e": 958,
"s": 893,
"text": "Django is fully functional framework that requires nothing else."
},
{
"code": null,
"e": 1009,
"s": 958,
"text": "It has thousands of additional packages available."
},
{
"code": null,
"e": 1030,
"s": 1009,
"text": "It is very scalable."
},
{
"code": null,
"e": 1677,
"s": 1030,
"text": "Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on the Django framework. ( Source )Sites like Hot Frameworks assess the popularity of a framework by counting the number of GitHub projects and StackOverflow questions for each platform, here Django is in 6th position. Web frameworks often refer to themselves as βopinionatedβ or βun-opinionatedβ based on opinions about the right way to handle any particular task. Django is somewhat opinionated, hence delivers the in both worlds( opinionated & un-opinionated )."
},
{
"code": null,
"e": 1944,
"s": 1677,
"text": "Versatility of DjangoDjango can build almost any type of website. It can also work with any client-side framework and can deliver content in any format such as HTML, JSON, XML etc. Some sites which can be built using Django are wikis, social networks, new sites etc."
},
{
"code": null,
"e": 2281,
"s": 1944,
"text": "SecuritySince Django framework is made for making web development easy, it has been engineered in such a way that it automatically do the right things to protect the website. For example, In the Django framework instead of putting a password in cookies, the hashed password is stored in it so that it canβt be fetched easily by hackers."
},
{
"code": null,
"e": 2606,
"s": 2281,
"text": "ScalabilityDjango web nodes have no stored state, they scale horizontally β just fire up more of them when you need them. Being able to do this is the essence of good scalability. Instagram and Disqus are two Django based products that have millions of active users, this is taken as an example of the scalability of Django."
},
{
"code": null,
"e": 2791,
"s": 2606,
"text": "PortabilityAll the codes of the Django framework are written in Python, which runs on many platforms. Which leads to run Django too in many platforms such as Linux, Windows and Mac OS."
},
{
"code": null,
"e": 2814,
"s": 2791,
"text": "Installation of Django"
},
{
"code": null,
"e": 2999,
"s": 2814,
"text": "Install python3 if not installed in your system ( according to configuration of your system and OS) from here . Try to download the latest version of python itβs python3.6.4 this time."
},
{
"code": null,
"e": 3192,
"s": 2999,
"text": "Note- Installation of Django in Linux and Mac is similar, here I am showing it in windows for Linux and mac just open terminal in place of command prompt and go through the following commands."
},
{
"code": null,
"e": 3254,
"s": 3192,
"text": "Install pip- Open command prompt and enter following command-"
},
{
"code": null,
"e": 3283,
"s": 3254,
"text": "python -m pip install -U pip"
},
{
"code": null,
"e": 3344,
"s": 3283,
"text": "Install virtual environment- Enter following command in cmd-"
},
{
"code": null,
"e": 3367,
"s": 3344,
"text": "pip install virtualenv"
},
{
"code": null,
"e": 3785,
"s": 3367,
"text": "Set Virtual environment- Setting up the virtual environment will allow you to edit the dependency which generally your system wouldnβt allow.Follow these steps to set up a virtual environment-Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate"
},
{
"code": null,
"e": 4011,
"s": 3785,
"text": "Create a virtual environment by giving this command in cmd-virtualenv env_siteChange directory to env_site by this command-cd env_siteGo to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate"
},
{
"code": null,
"e": 4090,
"s": 4011,
"text": "Create a virtual environment by giving this command in cmd-virtualenv env_site"
},
{
"code": null,
"e": 4110,
"s": 4090,
"text": "virtualenv env_site"
},
{
"code": null,
"e": 4167,
"s": 4110,
"text": "Change directory to env_site by this command-cd env_site"
},
{
"code": null,
"e": 4179,
"s": 4167,
"text": "cd env_site"
},
{
"code": null,
"e": 4271,
"s": 4179,
"text": "Go to Scripts directory inside env_site and activate virtual environment-cd Scriptsactivate"
},
{
"code": null,
"e": 4282,
"s": 4271,
"text": "cd Scripts"
},
{
"code": null,
"e": 4291,
"s": 4282,
"text": "activate"
},
{
"code": null,
"e": 4369,
"s": 4291,
"text": "Install Django- Install django by giving following command-pip install django"
},
{
"code": null,
"e": 4388,
"s": 4369,
"text": "pip install django"
},
{
"code": null,
"e": 4427,
"s": 4388,
"text": "Return to the env_site directory-cd .."
},
{
"code": null,
"e": 4433,
"s": 4427,
"text": "cd .."
},
{
"code": null,
"e": 4507,
"s": 4433,
"text": "Start a project by following command-django-admin startproject geeks_site"
},
{
"code": null,
"e": 4544,
"s": 4507,
"text": "django-admin startproject geeks_site"
},
{
"code": null,
"e": 4588,
"s": 4544,
"text": "Change directory to geeks_sitecd geeks_site"
},
{
"code": null,
"e": 4602,
"s": 4588,
"text": "cd geeks_site"
},
{
"code": null,
"e": 4699,
"s": 4602,
"text": "Start the server- Start the server by typing following command in cmd-python manage.py runserver"
},
{
"code": null,
"e": 4726,
"s": 4699,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 4827,
"s": 4726,
"text": "To check whether server is running or not go to web browser and enter http://127.0.0.1:8000/ as url."
},
{
"code": null,
"e": 4861,
"s": 4827,
"text": "Benefits of Django Architecture β"
},
{
"code": null,
"e": 4879,
"s": 4861,
"text": "Rapid Development"
},
{
"code": null,
"e": 4895,
"s": 4879,
"text": "Loosely Coupled"
},
{
"code": null,
"e": 4916,
"s": 4895,
"text": "Ease of Modification"
},
{
"code": null,
"e": 4948,
"s": 4916,
"text": "Drawbacks of MVC Architecture β"
},
{
"code": null,
"e": 4981,
"s": 4948,
"text": "Too much load on Model Component"
},
{
"code": null,
"e": 5012,
"s": 4981,
"text": "Development Complexity is high"
},
{
"code": null,
"e": 5048,
"s": 5012,
"text": "Two components are controlling View"
},
{
"code": null,
"e": 5060,
"s": 5048,
"text": "NaveenArora"
},
{
"code": null,
"e": 5071,
"s": 5060,
"text": "sayank2002"
},
{
"code": null,
"e": 5085,
"s": 5071,
"text": "Python Django"
},
{
"code": null,
"e": 5092,
"s": 5085,
"text": "Python"
}
] |
Software Testing | Reliability Testing
|
06 May, 2019
Reliability Testing is a testing technique that relates to test the ability of a software to function and given environmental conditions that helps in uncovering issues in the software design and functionality. It is defined as a type of software testing that determines whether the software can perform a failure free operation for a specific period of time in a specific environment. It ensures that the product is fault free and is reliable for its intended purpose.
Objective of Reliability Testing:The objective of reliability testing is:
To find the perpetual structure of repeating failures.
To find the number of failures occurring is the specific period of time.
To discover the main cause of failure.
To conduct performance testing of various modules of software product after fixing defects.
Types of Reliability Testing:There are three types of reliability testing:-
Feature Testing:Following three steps are involved in this testing:Each function in the software should be executed at least once.Interaction between two or more functions should be reduced.Each function should be properly executed.Regression Testing:Regression testing is basically performed whenever any new functionality is added, old functionalities are removed or the bugs are fixed in an application to make sure with introduction of new functionality or with the fixing of previous bugs, no new bugs are introduced in the application.Load Testing:Load testing is carried out to determine whether the application is supporting the required load without getting breakdown. It is performed to check the performance of the software under maximum work load.
Feature Testing:Following three steps are involved in this testing:Each function in the software should be executed at least once.Interaction between two or more functions should be reduced.Each function should be properly executed.
Each function in the software should be executed at least once.
Interaction between two or more functions should be reduced.
Each function should be properly executed.
Regression Testing:Regression testing is basically performed whenever any new functionality is added, old functionalities are removed or the bugs are fixed in an application to make sure with introduction of new functionality or with the fixing of previous bugs, no new bugs are introduced in the application.
Load Testing:Load testing is carried out to determine whether the application is supporting the required load without getting breakdown. It is performed to check the performance of the software under maximum work load.
The study of reliability testing can be divided into three categories:-
ModellingMeasurementImprovement
Modelling
Measurement
Improvement
Measurement of Reliability Testing:
Mean Time Between Failures (MTBF):Measurement of reliability testing is done in terms of mean time between failures (MTBF).
Mean Time To Failure (MTTF):The time between two consecutive failures is called as mean time to failure (MTTF).
Mean Time To Repair (MTTR):The time taken to fix the failures is known as mean time to repair (MTTR).MTBF = MTTF + MTTR
MTBF = MTTF + MTTR
Software Testing
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Functional vs Non Functional Requirements
Differences between Verification and Validation
Unit Testing | Software Testing
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Engineering | Requirements Engineering Process
Software Testing Life Cycle (STLC)
Difference between IAAS, PAAS and SAAS
Equivalence Partitioning Method
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 May, 2019"
},
{
"code": null,
"e": 524,
"s": 54,
"text": "Reliability Testing is a testing technique that relates to test the ability of a software to function and given environmental conditions that helps in uncovering issues in the software design and functionality. It is defined as a type of software testing that determines whether the software can perform a failure free operation for a specific period of time in a specific environment. It ensures that the product is fault free and is reliable for its intended purpose."
},
{
"code": null,
"e": 598,
"s": 524,
"text": "Objective of Reliability Testing:The objective of reliability testing is:"
},
{
"code": null,
"e": 653,
"s": 598,
"text": "To find the perpetual structure of repeating failures."
},
{
"code": null,
"e": 726,
"s": 653,
"text": "To find the number of failures occurring is the specific period of time."
},
{
"code": null,
"e": 765,
"s": 726,
"text": "To discover the main cause of failure."
},
{
"code": null,
"e": 857,
"s": 765,
"text": "To conduct performance testing of various modules of software product after fixing defects."
},
{
"code": null,
"e": 933,
"s": 857,
"text": "Types of Reliability Testing:There are three types of reliability testing:-"
},
{
"code": null,
"e": 1693,
"s": 933,
"text": "Feature Testing:Following three steps are involved in this testing:Each function in the software should be executed at least once.Interaction between two or more functions should be reduced.Each function should be properly executed.Regression Testing:Regression testing is basically performed whenever any new functionality is added, old functionalities are removed or the bugs are fixed in an application to make sure with introduction of new functionality or with the fixing of previous bugs, no new bugs are introduced in the application.Load Testing:Load testing is carried out to determine whether the application is supporting the required load without getting breakdown. It is performed to check the performance of the software under maximum work load."
},
{
"code": null,
"e": 1926,
"s": 1693,
"text": "Feature Testing:Following three steps are involved in this testing:Each function in the software should be executed at least once.Interaction between two or more functions should be reduced.Each function should be properly executed."
},
{
"code": null,
"e": 1990,
"s": 1926,
"text": "Each function in the software should be executed at least once."
},
{
"code": null,
"e": 2051,
"s": 1990,
"text": "Interaction between two or more functions should be reduced."
},
{
"code": null,
"e": 2094,
"s": 2051,
"text": "Each function should be properly executed."
},
{
"code": null,
"e": 2404,
"s": 2094,
"text": "Regression Testing:Regression testing is basically performed whenever any new functionality is added, old functionalities are removed or the bugs are fixed in an application to make sure with introduction of new functionality or with the fixing of previous bugs, no new bugs are introduced in the application."
},
{
"code": null,
"e": 2623,
"s": 2404,
"text": "Load Testing:Load testing is carried out to determine whether the application is supporting the required load without getting breakdown. It is performed to check the performance of the software under maximum work load."
},
{
"code": null,
"e": 2695,
"s": 2623,
"text": "The study of reliability testing can be divided into three categories:-"
},
{
"code": null,
"e": 2727,
"s": 2695,
"text": "ModellingMeasurementImprovement"
},
{
"code": null,
"e": 2737,
"s": 2727,
"text": "Modelling"
},
{
"code": null,
"e": 2749,
"s": 2737,
"text": "Measurement"
},
{
"code": null,
"e": 2761,
"s": 2749,
"text": "Improvement"
},
{
"code": null,
"e": 2797,
"s": 2761,
"text": "Measurement of Reliability Testing:"
},
{
"code": null,
"e": 2921,
"s": 2797,
"text": "Mean Time Between Failures (MTBF):Measurement of reliability testing is done in terms of mean time between failures (MTBF)."
},
{
"code": null,
"e": 3033,
"s": 2921,
"text": "Mean Time To Failure (MTTF):The time between two consecutive failures is called as mean time to failure (MTTF)."
},
{
"code": null,
"e": 3154,
"s": 3033,
"text": "Mean Time To Repair (MTTR):The time taken to fix the failures is known as mean time to repair (MTTR).MTBF = MTTF + MTTR "
},
{
"code": null,
"e": 3174,
"s": 3154,
"text": "MTBF = MTTF + MTTR "
},
{
"code": null,
"e": 3191,
"s": 3174,
"text": "Software Testing"
},
{
"code": null,
"e": 3212,
"s": 3191,
"text": "Software Engineering"
},
{
"code": null,
"e": 3310,
"s": 3212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3352,
"s": 3310,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 3400,
"s": 3352,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 3432,
"s": 3400,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 3481,
"s": 3432,
"text": "Software Engineering | Classical Waterfall Model"
},
{
"code": null,
"e": 3529,
"s": 3481,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 3571,
"s": 3529,
"text": "Difference between Spring and Spring Boot"
},
{
"code": null,
"e": 3627,
"s": 3571,
"text": "Software Engineering | Requirements Engineering Process"
},
{
"code": null,
"e": 3662,
"s": 3627,
"text": "Software Testing Life Cycle (STLC)"
},
{
"code": null,
"e": 3701,
"s": 3662,
"text": "Difference between IAAS, PAAS and SAAS"
}
] |
Matplotlib.gridspec.GridSpec Class in Python
|
07 Oct, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For this, to work the number of rows and columns must be set. Optionally, tuning of subplot layout parameters can be also done.
Syntax: class matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None)Parameters:
nrows: It is an integer representing the number of rows in the grid.
ncols: It is an integer representing the number of columns in the grid.
figure: It is an optional parameter used to draw figures.
left, right, top, bottom: These are optional parameters used to define the extent of the subplots as fraction of figure width or height.
wspase: It is an optional float argument used to reserve the width space between subplots.
hspace: It is an optional float argument used to reserve the height space between subplots.
width_ratios: It is an optional parameter that represents the width ratios of the columns.
height_ratios: It is an optional parameter that represents the width ratios of the rows.
Methods of the class:
get_subplot_params(self, figure=None): It returns a dictionary of subplot layout parameters. unless a figure attribute is set, the default parameter is from rcParams.
ight_layout(self, figure, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): It is used to give specific padding to adjust the subplots. Here pad is a float value that sets padding between figure edge and the subplot edges as a fraction of the font size. The h_pad and w_pad are optional argument used to set padding between adjacent subplots. Also rect is used to normalize figure coordinates of a rectangle that includes all the subplot area. its default is (0, 0, 1, 1). It is a tuple of 4 floats.
Example 1:
Python3
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.gridspec import GridSpec gs = GridSpec(8, 39)ax1 = plt.subplot(gs[:6, :35])ax2 = plt.subplot(gs[6:, :]) data1 = np.random.rand(6, 35)data2 = np.random.rand(2, 39) ax1.imshow(data1)ax2.imshow(data2) plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure(figsize =([7, 4])) gs = gridspec.GridSpec(2, 6)gs.update(wspace = 1.5, hspace = 0.3) ax1 = plt.subplot(gs[0, :2])ax1.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax2 = plt.subplot(gs[0, 2:4])ax2.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax3 = plt.subplot(gs[0, 4:6])ax3.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax4 = plt.subplot(gs[1, 1:3])ax4.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax5 = plt.subplot(gs[1, 3:5])ax5.set_ylabel('ylabel', labelpad = 0, fontsize = 12) plt.show()
Output:
gulshankumarar231
anikaseth98
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 241,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. "
},
{
"code": null,
"e": 473,
"s": 241,
"text": "The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For this, to work the number of rows and columns must be set. Optionally, tuning of subplot layout parameters can be also done. "
},
{
"code": null,
"e": 667,
"s": 473,
"text": "Syntax: class matplotlib.gridspec.GridSpec(nrows, ncols, figure=None, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None, width_ratios=None, height_ratios=None)Parameters: "
},
{
"code": null,
"e": 737,
"s": 667,
"text": "nrows: It is an integer representing the number of rows in the grid. "
},
{
"code": null,
"e": 810,
"s": 737,
"text": "ncols: It is an integer representing the number of columns in the grid. "
},
{
"code": null,
"e": 869,
"s": 810,
"text": "figure: It is an optional parameter used to draw figures. "
},
{
"code": null,
"e": 1007,
"s": 869,
"text": "left, right, top, bottom: These are optional parameters used to define the extent of the subplots as fraction of figure width or height. "
},
{
"code": null,
"e": 1099,
"s": 1007,
"text": "wspase: It is an optional float argument used to reserve the width space between subplots. "
},
{
"code": null,
"e": 1192,
"s": 1099,
"text": "hspace: It is an optional float argument used to reserve the height space between subplots. "
},
{
"code": null,
"e": 1284,
"s": 1192,
"text": "width_ratios: It is an optional parameter that represents the width ratios of the columns. "
},
{
"code": null,
"e": 1375,
"s": 1284,
"text": "height_ratios: It is an optional parameter that represents the width ratios of the rows. "
},
{
"code": null,
"e": 1401,
"s": 1377,
"text": "Methods of the class: "
},
{
"code": null,
"e": 1569,
"s": 1401,
"text": "get_subplot_params(self, figure=None): It returns a dictionary of subplot layout parameters. unless a figure attribute is set, the default parameter is from rcParams. "
},
{
"code": null,
"e": 2081,
"s": 1569,
"text": "ight_layout(self, figure, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None): It is used to give specific padding to adjust the subplots. Here pad is a float value that sets padding between figure edge and the subplot edges as a fraction of the font size. The h_pad and w_pad are optional argument used to set padding between adjacent subplots. Also rect is used to normalize figure coordinates of a rectangle that includes all the subplot area. its default is (0, 0, 1, 1). It is a tuple of 4 floats. "
},
{
"code": null,
"e": 2094,
"s": 2081,
"text": "Example 1: "
},
{
"code": null,
"e": 2102,
"s": 2094,
"text": "Python3"
},
{
"code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.gridspec import GridSpec gs = GridSpec(8, 39)ax1 = plt.subplot(gs[:6, :35])ax2 = plt.subplot(gs[6:, :]) data1 = np.random.rand(6, 35)data2 = np.random.rand(2, 39) ax1.imshow(data1)ax2.imshow(data2) plt.show()",
"e": 2377,
"s": 2102,
"text": null
},
{
"code": null,
"e": 2387,
"s": 2377,
"text": "Output: "
},
{
"code": null,
"e": 2400,
"s": 2387,
"text": "Example 2: "
},
{
"code": null,
"e": 2408,
"s": 2400,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspec fig = plt.figure(figsize =([7, 4])) gs = gridspec.GridSpec(2, 6)gs.update(wspace = 1.5, hspace = 0.3) ax1 = plt.subplot(gs[0, :2])ax1.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax2 = plt.subplot(gs[0, 2:4])ax2.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax3 = plt.subplot(gs[0, 4:6])ax3.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax4 = plt.subplot(gs[1, 1:3])ax4.set_ylabel('ylabel', labelpad = 0, fontsize = 12) ax5 = plt.subplot(gs[1, 3:5])ax5.set_ylabel('ylabel', labelpad = 0, fontsize = 12) plt.show()",
"e": 3006,
"s": 2408,
"text": null
},
{
"code": null,
"e": 3016,
"s": 3006,
"text": "Output: "
},
{
"code": null,
"e": 3036,
"s": 3018,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 3048,
"s": 3036,
"text": "anikaseth98"
},
{
"code": null,
"e": 3066,
"s": 3048,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3073,
"s": 3066,
"text": "Python"
},
{
"code": null,
"e": 3089,
"s": 3073,
"text": "Write From Home"
}
] |
Python | Get first K items in dictionary
|
26 Jul, 2019
While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of web development domain. Letβs discuss certain ways in which this problem can be solved.
Method #1 : Using items() + list slicingTo solve this problem, combination of above functions have to implied. The items function can be used to get all the dictionary items and main task is done by list slicing, which limits the dictionary key-value pair.
# Python3 code to demonstrate working of# Get first K items in dictionary# Using items() + list slicing # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize limitK = 3 # Using items() + list slicing# Get first K items in dictionaryres = dict(list(test_dict.items())[0: K]) # printing result print("Dictionary limited by K is : " + str(res))
The original dictionary : {βisβ: 2, βCSβ: 5, βbestβ: 3, βgfgβ: 1, βforβ: 4}Dictionary limited by K is : {βisβ: 2, βCSβ: 5, βbestβ: 3}
Method #2 : Using islice() + items()The combination of above functions can be used to perform this particular task. In these, we perform the slice using the islice() and items function allows to get the items out of iterable.
# Python3 code to demonstrate working of# Get first K items in dictionary# Using islice() + items()import itertools # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5} # printing original dictionaryprint("The original dictionary : " + str(test_dict)) # Initialize limitK = 3 # Using islice() + items()# Get first K items in dictionaryres = dict(itertools.islice(test_dict.items(), K)) # printing result print("Dictionary limited by K is : " + str(res))
The original dictionary : {βisβ: 2, βCSβ: 5, βbestβ: 3, βgfgβ: 1, βforβ: 4}Dictionary limited by K is : {βisβ: 2, βCSβ: 5, βbestβ: 3}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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": "\n26 Jul, 2019"
},
{
"code": null,
"e": 298,
"s": 28,
"text": "While working with dictionaries, we can come across a problem in which we might have to get just some of the initial keys in dictionary. This problem can typically occur in cases of web development domain. Letβs discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 555,
"s": 298,
"text": "Method #1 : Using items() + list slicingTo solve this problem, combination of above functions have to implied. The items function can be used to get all the dictionary items and main task is done by list slicing, which limits the dictionary key-value pair."
},
{
"code": "# Python3 code to demonstrate working of# Get first K items in dictionary# Using items() + list slicing # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize limitK = 3 # Using items() + list slicing# Get first K items in dictionaryres = dict(list(test_dict.items())[0: K]) # printing result print(\"Dictionary limited by K is : \" + str(res))",
"e": 1039,
"s": 555,
"text": null
},
{
"code": null,
"e": 1173,
"s": 1039,
"text": "The original dictionary : {βisβ: 2, βCSβ: 5, βbestβ: 3, βgfgβ: 1, βforβ: 4}Dictionary limited by K is : {βisβ: 2, βCSβ: 5, βbestβ: 3}"
},
{
"code": null,
"e": 1401,
"s": 1175,
"text": "Method #2 : Using islice() + items()The combination of above functions can be used to perform this particular task. In these, we perform the slice using the islice() and items function allows to get the items out of iterable."
},
{
"code": "# Python3 code to demonstrate working of# Get first K items in dictionary# Using islice() + items()import itertools # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5} # printing original dictionaryprint(\"The original dictionary : \" + str(test_dict)) # Initialize limitK = 3 # Using islice() + items()# Get first K items in dictionaryres = dict(itertools.islice(test_dict.items(), K)) # printing result print(\"Dictionary limited by K is : \" + str(res))",
"e": 1902,
"s": 1401,
"text": null
},
{
"code": null,
"e": 2036,
"s": 1902,
"text": "The original dictionary : {βisβ: 2, βCSβ: 5, βbestβ: 3, βgfgβ: 1, βforβ: 4}Dictionary limited by K is : {βisβ: 2, βCSβ: 5, βbestβ: 3}"
},
{
"code": null,
"e": 2063,
"s": 2036,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Python"
},
{
"code": null,
"e": 2086,
"s": 2070,
"text": "Python Programs"
},
{
"code": null,
"e": 2184,
"s": 2086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2216,
"s": 2184,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2243,
"s": 2216,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2274,
"s": 2243,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2297,
"s": 2274,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2318,
"s": 2297,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2340,
"s": 2318,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2379,
"s": 2340,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2417,
"s": 2379,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2466,
"s": 2417,
"text": "Python | Convert string dictionary to dictionary"
}
] |
<mat-button> in Angular material
|
25 Nov, 2020
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications.
In order to use it, we need to have angular installed in our project, after having it you can enter the below command and can download it.
Installation syntax:
ng add @angular/material
Types of Buttons in Angular material: Buttons present in angular material are called as <mat-button>. They are many types of mat-buttons available in angular material, they are:
Button Name
The tag used for the buttons
Explanation
Basic Buttons
<mat-button>
Raised Buttons
<mat-raised-button>
Stroked buttons
<mat-stroked-button>
Flat Buttons
<mat-flat-button>
Fab Buttons
<mat-fab>
Mini Fab Buttons
<mat-mini-fab>
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import βMatButtonModuleβ from β@angular/material/buttonβ in the app.module.ts file.
Then using the above-mentioned tags in the table code all types of buttons.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Code Implementation: In this example, we will implement all types of <mat-button> in angular.
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import {MatButtonModule} from '@angular/material/button'; @NgModule({ imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }
app.component.html:
HTML
<h5>Basic Buttons</h5><div> <button mat-button>Basic</button> <button mat-button color="primary">Primary</button> <button mat-button color="accent">Accent</button> <button mat-button color="warn">Warn</button> <button mat-button disabled>Disabled</button></div> <h5>Raised Buttons</h5><div> <button mat-raised-button>Basic</button> <button mat-raised-button color="primary">Primary</button> <button mat-raised-button color="accent">Accent</button> <button mat-raised-button color="warn">Warn</button> <button mat-raised-button disabled>Disabled</button></div> <h5>Stroked Buttons</h5><div> <button mat-stroked-button>Basic</button> <button mat-stroked-button color="primary">Primary</button> <button mat-stroked-button color="accent">Accent</button> <button mat-stroked-button color="warn">Warn</button> <button mat-stroked-button disabled>Disabled</button></div> <h5>Flat Buttons</h5><div> <button mat-flat-button>Basic</button> <button mat-flat-button color="primary">Primary</button> <button mat-flat-button color="accent">Accent</button> <button mat-flat-button color="warn">Warn</button> <button mat-flat-button disabled>Disabled</button></div> <h5>Fab Buttons</h5><div> <button mat-fab>Basic</button> <button mat-fab color="primary">Primary</button> <button mat-fab color="accent">Accent</button> <button mat-fab color="warn">Warn</button> <button mat-fab disabled>Disabled</button></div> <h5>Mini Fab Buttons</h5><div> <button mat-mini-fab>Basic</button> <button mat-mini-fab color="primary">Primary</button> <button mat-mini-fab color="accent">Accent</button> <button mat-mini-fab color="warn">Warn</button></div>
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. "
},
{
"code": null,
"e": 341,
"s": 202,
"text": "In order to use it, we need to have angular installed in our project, after having it you can enter the below command and can download it."
},
{
"code": null,
"e": 362,
"s": 341,
"text": "Installation syntax:"
},
{
"code": null,
"e": 388,
"s": 362,
"text": "ng add @angular/material\n"
},
{
"code": null,
"e": 566,
"s": 388,
"text": "Types of Buttons in Angular material: Buttons present in angular material are called as <mat-button>. They are many types of mat-buttons available in angular material, they are:"
},
{
"code": null,
"e": 578,
"s": 566,
"text": "Button Name"
},
{
"code": null,
"e": 607,
"s": 578,
"text": "The tag used for the buttons"
},
{
"code": null,
"e": 619,
"s": 607,
"text": "Explanation"
},
{
"code": null,
"e": 634,
"s": 619,
"text": " Basic Buttons"
},
{
"code": null,
"e": 647,
"s": 634,
"text": "<mat-button>"
},
{
"code": null,
"e": 662,
"s": 647,
"text": "Raised Buttons"
},
{
"code": null,
"e": 682,
"s": 662,
"text": "<mat-raised-button>"
},
{
"code": null,
"e": 699,
"s": 682,
"text": " Stroked buttons"
},
{
"code": null,
"e": 720,
"s": 699,
"text": "<mat-stroked-button>"
},
{
"code": null,
"e": 733,
"s": 720,
"text": "Flat Buttons"
},
{
"code": null,
"e": 751,
"s": 733,
"text": "<mat-flat-button>"
},
{
"code": null,
"e": 763,
"s": 751,
"text": "Fab Buttons"
},
{
"code": null,
"e": 773,
"s": 763,
"text": "<mat-fab>"
},
{
"code": null,
"e": 790,
"s": 773,
"text": "Mini Fab Buttons"
},
{
"code": null,
"e": 805,
"s": 790,
"text": "<mat-mini-fab>"
},
{
"code": null,
"e": 815,
"s": 805,
"text": "Approach:"
},
{
"code": null,
"e": 886,
"s": 815,
"text": "First, install the angular material using the above-mentioned command."
},
{
"code": null,
"e": 1005,
"s": 886,
"text": "After completing the installation, Import βMatButtonModuleβ from β@angular/material/buttonβ in the app.module.ts file."
},
{
"code": null,
"e": 1081,
"s": 1005,
"text": "Then using the above-mentioned tags in the table code all types of buttons."
},
{
"code": null,
"e": 1228,
"s": 1081,
"text": "If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn."
},
{
"code": null,
"e": 1292,
"s": 1228,
"text": "Once done with the above steps then serve or start the project."
},
{
"code": null,
"e": 1386,
"s": 1292,
"text": "Code Implementation: In this example, we will implement all types of <mat-button> in angular."
},
{
"code": null,
"e": 1401,
"s": 1386,
"text": "app.module.ts:"
},
{
"code": null,
"e": 1412,
"s": 1401,
"text": "Javascript"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import {MatButtonModule} from '@angular/material/button'; @NgModule({ imports: [ BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ]})export class AppModule { }",
"e": 1991,
"s": 1412,
"text": null
},
{
"code": null,
"e": 2011,
"s": 1991,
"text": "app.component.html:"
},
{
"code": null,
"e": 2016,
"s": 2011,
"text": "HTML"
},
{
"code": "<h5>Basic Buttons</h5><div> <button mat-button>Basic</button> <button mat-button color=\"primary\">Primary</button> <button mat-button color=\"accent\">Accent</button> <button mat-button color=\"warn\">Warn</button> <button mat-button disabled>Disabled</button></div> <h5>Raised Buttons</h5><div> <button mat-raised-button>Basic</button> <button mat-raised-button color=\"primary\">Primary</button> <button mat-raised-button color=\"accent\">Accent</button> <button mat-raised-button color=\"warn\">Warn</button> <button mat-raised-button disabled>Disabled</button></div> <h5>Stroked Buttons</h5><div> <button mat-stroked-button>Basic</button> <button mat-stroked-button color=\"primary\">Primary</button> <button mat-stroked-button color=\"accent\">Accent</button> <button mat-stroked-button color=\"warn\">Warn</button> <button mat-stroked-button disabled>Disabled</button></div> <h5>Flat Buttons</h5><div> <button mat-flat-button>Basic</button> <button mat-flat-button color=\"primary\">Primary</button> <button mat-flat-button color=\"accent\">Accent</button> <button mat-flat-button color=\"warn\">Warn</button> <button mat-flat-button disabled>Disabled</button></div> <h5>Fab Buttons</h5><div> <button mat-fab>Basic</button> <button mat-fab color=\"primary\">Primary</button> <button mat-fab color=\"accent\">Accent</button> <button mat-fab color=\"warn\">Warn</button> <button mat-fab disabled>Disabled</button></div> <h5>Mini Fab Buttons</h5><div> <button mat-mini-fab>Basic</button> <button mat-mini-fab color=\"primary\">Primary</button> <button mat-mini-fab color=\"accent\">Accent</button> <button mat-mini-fab color=\"warn\">Warn</button></div>",
"e": 3672,
"s": 2016,
"text": null
},
{
"code": null,
"e": 3681,
"s": 3672,
"text": "Output: "
},
{
"code": null,
"e": 3698,
"s": 3683,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3705,
"s": 3698,
"text": "Picked"
},
{
"code": null,
"e": 3715,
"s": 3705,
"text": "AngularJS"
},
{
"code": null,
"e": 3732,
"s": 3715,
"text": "Web Technologies"
}
] |
Lodash | _.pull() Method
|
29 Apr, 2020
The _.pull() method is used to remove all the given values from a given array.
Syntax:
_.pull(array, [values])
Parameters: This method accepts two or more parameters as mentioned above and described below:
Array: This parameter holds the query array.
values: This parameter holds one or multiple element that need to be removed from array.
Return Value: It return an array that contains remaining element.
Example 1: This example removes all the values from array that matches with given values.
const _ = require('lodash'); let ar = [1, 2, 3, 4, 5] let value = _.pull(ar, 3, 5) console.log(value)
Here, const _ = require('lodash') is used to import the lodash library into the file.
Output:
[ 1, 2, 4 ]
Example 2: This example removes all the values from array that matches with given values.
const _ = require('lodash'); let ar = [1, 2, 3, 1, 3, 4, 1, 5] let value = _.pull(ar, 1, 5) console.log(value)
Output:
[ 2, 3, 3, 4 ]
Example 3: This example removes all the values from array that matches with given values.
const _ = require('lodash'); let ar = ['a', 'b', 'c', 'd'] let value = _.pull(ar, 'c') console.log(value)
Output:
[ 'a', 'b', 'd' ]
Note: It will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#pull
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
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": "\n29 Apr, 2020"
},
{
"code": null,
"e": 107,
"s": 28,
"text": "The _.pull() method is used to remove all the given values from a given array."
},
{
"code": null,
"e": 115,
"s": 107,
"text": "Syntax:"
},
{
"code": null,
"e": 139,
"s": 115,
"text": "_.pull(array, [values])"
},
{
"code": null,
"e": 234,
"s": 139,
"text": "Parameters: This method accepts two or more parameters as mentioned above and described below:"
},
{
"code": null,
"e": 279,
"s": 234,
"text": "Array: This parameter holds the query array."
},
{
"code": null,
"e": 368,
"s": 279,
"text": "values: This parameter holds one or multiple element that need to be removed from array."
},
{
"code": null,
"e": 434,
"s": 368,
"text": "Return Value: It return an array that contains remaining element."
},
{
"code": null,
"e": 524,
"s": 434,
"text": "Example 1: This example removes all the values from array that matches with given values."
},
{
"code": "const _ = require('lodash'); let ar = [1, 2, 3, 4, 5] let value = _.pull(ar, 3, 5) console.log(value)",
"e": 629,
"s": 524,
"text": null
},
{
"code": null,
"e": 715,
"s": 629,
"text": "Here, const _ = require('lodash') is used to import the lodash library into the file."
},
{
"code": null,
"e": 723,
"s": 715,
"text": "Output:"
},
{
"code": null,
"e": 736,
"s": 723,
"text": "[ 1, 2, 4 ]\n"
},
{
"code": null,
"e": 826,
"s": 736,
"text": "Example 2: This example removes all the values from array that matches with given values."
},
{
"code": "const _ = require('lodash'); let ar = [1, 2, 3, 1, 3, 4, 1, 5] let value = _.pull(ar, 1, 5) console.log(value)",
"e": 940,
"s": 826,
"text": null
},
{
"code": null,
"e": 948,
"s": 940,
"text": "Output:"
},
{
"code": null,
"e": 964,
"s": 948,
"text": "[ 2, 3, 3, 4 ]\n"
},
{
"code": null,
"e": 1054,
"s": 964,
"text": "Example 3: This example removes all the values from array that matches with given values."
},
{
"code": "const _ = require('lodash'); let ar = ['a', 'b', 'c', 'd'] let value = _.pull(ar, 'c') console.log(value)",
"e": 1163,
"s": 1054,
"text": null
},
{
"code": null,
"e": 1171,
"s": 1163,
"text": "Output:"
},
{
"code": null,
"e": 1190,
"s": 1171,
"text": "[ 'a', 'b', 'd' ]\n"
},
{
"code": null,
"e": 1290,
"s": 1190,
"text": "Note: It will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 1338,
"s": 1290,
"text": "Reference: https://lodash.com/docs/4.17.15#pull"
},
{
"code": null,
"e": 1356,
"s": 1338,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1367,
"s": 1356,
"text": "JavaScript"
},
{
"code": null,
"e": 1384,
"s": 1367,
"text": "Web Technologies"
},
{
"code": null,
"e": 1482,
"s": 1384,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1543,
"s": 1482,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1615,
"s": 1543,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1655,
"s": 1615,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1696,
"s": 1655,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1742,
"s": 1696,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 1804,
"s": 1742,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1837,
"s": 1804,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1898,
"s": 1837,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1948,
"s": 1898,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Implement dynamic queue using templates class and a circular array
|
21 Jun, 2022
In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality:
Front(): Get the front item from the queue.
Back(): Get the last item from the queue.
Push(X): Push the X in the queue at the end of the queue.
Pop(): Delete an element from the queue.
Below is the step-by-step illustration:
Initially, the queue is empty.
Insert element 1 to the back of the queue.
Insert elements 2, 3, 4 to the back of the queue.
Insert elements 5 to the back of the queue.
Pop 4 elements from the queue.
Pop 1 element from the queue.
Approach: The idea is to double the size of the array used every time the capacity of the array gets full and copy the elements of the previous array into the new array. Follow the steps below to solve the problem:
Initialize 4 variables say frontIndex, backIndex, sizeVar, and capacity and an array say arr[] to implement the queue,
Define a function say Capacity() to find the size of the current array used:Return the capacity.
Return the capacity.
Define a function say size() to find the count of elements in the queue:Return the variable sizeVar.
Return the variable sizeVar.
Define a function say full() to find if the queue is full or not:Return true if sizeVar is equal to capacity. Otherwise, return false.
Return true if sizeVar is equal to capacity. Otherwise, return false.
Define a function say empty() to find if the queue is empty or not:If frontIndex and backIndex are equal to -1 then return true. Otherwise, return false.
If frontIndex and backIndex are equal to -1 then return true. Otherwise, return false.
Define a function say Front() to print the front element of the queue:Print the element of arr[frontIndex] if queue is not empty().
Print the element of arr[frontIndex] if queue is not empty().
Define a function say Back() to print the last element of the queue:Print the element of arr[BackIndex] if queue is not empty().
Print the element of arr[BackIndex] if queue is not empty().
Define a function say Push(X) to insert an element at the end of the queue:If the queue is full then double the size of the current array and copy the elements of the previous array into the new array.If queue is empty() then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one.Else, update backIndex as backIndex = (backIndex+1)%capacity and then assign X to arr[backIndex] and increment sizeVar by one.
If the queue is full then double the size of the current array and copy the elements of the previous array into the new array.
If queue is empty() then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one.
Else, update backIndex as backIndex = (backIndex+1)%capacity and then assign X to arr[backIndex] and increment sizeVar by one.
Define a function say Pop() to delete an element at the front of the queue:If the queue is empty print βUnderflowβ.Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one.Else, Update frontIndex as frontIndex = (frontIndex+1)%capacity and decrement sizeVar by one.
If the queue is empty print βUnderflowβ.
Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one.
Else, Update frontIndex as frontIndex = (frontIndex+1)%capacity and decrement sizeVar by one.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Class defination for queuetemplate <class X>class Queue { private: // Stores the frontIndex int frontIndex; // Stores the back Index int backIndex; // Stores the array X* arr; // Stores the sizeof queue int sizeVar; // Stores the size of array int capacityVar = 4; public: // Queue class constructor Queue() { arr = new X[capacityVar]; frontIndex = backIndex = -1; sizeVar = 0; } // Function Methods bool empty(); bool full(); void push(X x); void pop(); X front(); X back(); int capacity(); int size();}; // Find the capacity of queuetemplate <class X>int Queue<X>::capacity(){ return capacityVar;} // Find the number of elements// present in Queuetemplate <class X>int Queue<X>::size(){ return sizeVar;} // Function to check if// Queue is empty or nottemplate <class X>bool Queue<X>::empty(){ if (frontIndex == -1 && backIndex == -1) return true; else return false;} // Function to check if the queue// is full or nottemplate <class X>bool Queue<X>::full(){ if (sizeVar == capacityVar) return true; else return false;} // Function to find the front element// of the queuetemplate <class X>X Queue<X>::front(){ // If queue is empty if (empty()) { cout << "Queue underflow" << endl; abort(); } return arr[frontIndex];} // Function to find the last element// of the Queuetemplate <class X>X Queue<X>::back(){ if (empty()) { cout << "Queue underflow" << endl; abort(); } return arr[backIndex];} // Function to insert the element// to the rear end of the queuetemplate <class X>void Queue<X>::push(X x){ if (full()) { // If the queue is full, then // double the capacity capacityVar = capacityVar * 2; // Initialize new array of // double size X* temp = new X[capacityVar]; // Copy the elements of the // previous array in the order of the queue for (int i = 0, j= frontIndex; i < sizeVar; i++){ temp[i] = arr[j]; j = (j+1) % sizeVar; } // update the front and rear indices in the new array frontIndex = 0; backIndex = sizeVar -1; // Deallocate the memory // of previous array delete[] arr; arr = temp; } // If size is zero if (empty()) { frontIndex = backIndex = 0; arr[backIndex] = x; sizeVar++; return; } // Increment the backIndex backIndex = (backIndex + 1) % capacityVar; arr[backIndex] = x; sizeVar++; return;} // Function to pop an element from// front end of the queuetemplate <class X>void Queue<X>::pop(){ // If queue is empty if (empty()) { cout << "Queue underflow" << endl; abort(); } // If there is only one character if (frontIndex == backIndex) { // Mark Queue as empty // and decrement sizeVar frontIndex = backIndex = -1; sizeVar--; return; } // Increment frontIndex cyclically // using modulo arithmetic frontIndex = (frontIndex + 1) % capacityVar; sizeVar--; return;} // Driver Codeint main(){ // Queue initialization Queue<int> q; // Iterate the range [1, 100] for (int i = 1; i < 5; i++) q.push(i); // Print the current capacity cout << "Current capacity " << q.capacity() << endl; // Print current size cout << "Current size " << q.size() << endl; // Print front elements of queue cout << "Front element " << q.front() << endl; // Print last element of the queue cout << "Rear element " << q.back() << endl; cout << endl; cout << "Pop an element" << endl; // Pop an element from the queue q.pop(); cout << "Pop an element" << endl; // Pop an element from the queue q.pop(); cout << endl; // Print the current capacity cout << "Current capacity " << q.capacity() << endl; // Print current size cout << "Current size " << q.size() << endl; // Print front elements of queue cout << "Front element " << q.front() << endl; // Print last element of the queue cout << "Rear element " << q.back() << endl; cout << endl; cout << "Push element 5" << endl; cout << "Push element 6" << endl; q.push(5); q.push(6); cout << endl; // Print the current capacity cout << "Current capacity " << q.capacity() << endl; // Print current size cout << "Current size " << q.size() << endl; // Print front elements of queue cout << "Front element " << q.front() << endl; // Print last element of the queue cout << "Rear element " << q.back() << endl; cout << endl; cout << "Push element 7" << endl; q.push(7); cout << endl; // Print the current capacity cout << "Current capacity " << q.capacity() << endl; // Print current size cout << "Current size " << q.size() << endl; // Print front elements of queue cout << "Front element " << q.front() << endl; // Print last element of the queue cout << "Rear element " << q.back() << endl; return 0;}
Current capacity 128
Current size 99
Front element 1
Rear element 99
Pop an element
Pop an element
Current capacity 128
Current size 97
Front element 3
Rear element 99
Time Complexity: O(N)Auxiliary Space: O(N)
arorakashish0911
ruchithajujjuru1405
Queue
Queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Sum of minimum and maximum elements of all subarrays of size k.
Reversing a Queue
Implement Stack and Queue using Deque
First negative integer in every window of size k
Priority queue of pairs in C++ with ordering by first and second element
How to efficiently implement k Queues in a single array?
Find the first non-repeating character from a stream of characters
Stack Permutations (Check if an array is stack permutation of other)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 186,
"s": 54,
"text": "In this article, we will discuss how to create a dynamic circular queue using a circular array having the following functionality: "
},
{
"code": null,
"e": 230,
"s": 186,
"text": "Front(): Get the front item from the queue."
},
{
"code": null,
"e": 272,
"s": 230,
"text": "Back(): Get the last item from the queue."
},
{
"code": null,
"e": 330,
"s": 272,
"text": "Push(X): Push the X in the queue at the end of the queue."
},
{
"code": null,
"e": 371,
"s": 330,
"text": "Pop(): Delete an element from the queue."
},
{
"code": null,
"e": 411,
"s": 371,
"text": "Below is the step-by-step illustration:"
},
{
"code": null,
"e": 442,
"s": 411,
"text": "Initially, the queue is empty."
},
{
"code": null,
"e": 485,
"s": 442,
"text": "Insert element 1 to the back of the queue."
},
{
"code": null,
"e": 535,
"s": 485,
"text": "Insert elements 2, 3, 4 to the back of the queue."
},
{
"code": null,
"e": 579,
"s": 535,
"text": "Insert elements 5 to the back of the queue."
},
{
"code": null,
"e": 610,
"s": 579,
"text": "Pop 4 elements from the queue."
},
{
"code": null,
"e": 640,
"s": 610,
"text": "Pop 1 element from the queue."
},
{
"code": null,
"e": 855,
"s": 640,
"text": "Approach: The idea is to double the size of the array used every time the capacity of the array gets full and copy the elements of the previous array into the new array. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 974,
"s": 855,
"text": "Initialize 4 variables say frontIndex, backIndex, sizeVar, and capacity and an array say arr[] to implement the queue,"
},
{
"code": null,
"e": 1071,
"s": 974,
"text": "Define a function say Capacity() to find the size of the current array used:Return the capacity."
},
{
"code": null,
"e": 1092,
"s": 1071,
"text": "Return the capacity."
},
{
"code": null,
"e": 1193,
"s": 1092,
"text": "Define a function say size() to find the count of elements in the queue:Return the variable sizeVar."
},
{
"code": null,
"e": 1222,
"s": 1193,
"text": "Return the variable sizeVar."
},
{
"code": null,
"e": 1357,
"s": 1222,
"text": "Define a function say full() to find if the queue is full or not:Return true if sizeVar is equal to capacity. Otherwise, return false."
},
{
"code": null,
"e": 1427,
"s": 1357,
"text": "Return true if sizeVar is equal to capacity. Otherwise, return false."
},
{
"code": null,
"e": 1581,
"s": 1427,
"text": "Define a function say empty() to find if the queue is empty or not:If frontIndex and backIndex are equal to -1 then return true. Otherwise, return false."
},
{
"code": null,
"e": 1668,
"s": 1581,
"text": "If frontIndex and backIndex are equal to -1 then return true. Otherwise, return false."
},
{
"code": null,
"e": 1800,
"s": 1668,
"text": "Define a function say Front() to print the front element of the queue:Print the element of arr[frontIndex] if queue is not empty()."
},
{
"code": null,
"e": 1862,
"s": 1800,
"text": "Print the element of arr[frontIndex] if queue is not empty()."
},
{
"code": null,
"e": 1991,
"s": 1862,
"text": "Define a function say Back() to print the last element of the queue:Print the element of arr[BackIndex] if queue is not empty()."
},
{
"code": null,
"e": 2052,
"s": 1991,
"text": "Print the element of arr[BackIndex] if queue is not empty()."
},
{
"code": null,
"e": 2534,
"s": 2052,
"text": "Define a function say Push(X) to insert an element at the end of the queue:If the queue is full then double the size of the current array and copy the elements of the previous array into the new array.If queue is empty() then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one.Else, update backIndex as backIndex = (backIndex+1)%capacity and then assign X to arr[backIndex] and increment sizeVar by one."
},
{
"code": null,
"e": 2661,
"s": 2534,
"text": "If the queue is full then double the size of the current array and copy the elements of the previous array into the new array."
},
{
"code": null,
"e": 2816,
"s": 2661,
"text": "If queue is empty() then assign frontIndex = backIndex = 0 and then assign X to both arr[frontIndex] and arr[backIndex] and then increment sizeVar by one."
},
{
"code": null,
"e": 2943,
"s": 2816,
"text": "Else, update backIndex as backIndex = (backIndex+1)%capacity and then assign X to arr[backIndex] and increment sizeVar by one."
},
{
"code": null,
"e": 3264,
"s": 2943,
"text": "Define a function say Pop() to delete an element at the front of the queue:If the queue is empty print βUnderflowβ.Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one.Else, Update frontIndex as frontIndex = (frontIndex+1)%capacity and decrement sizeVar by one."
},
{
"code": null,
"e": 3305,
"s": 3264,
"text": "If the queue is empty print βUnderflowβ."
},
{
"code": null,
"e": 3418,
"s": 3305,
"text": "Else if sizeVar is equal to 1 then assign -1 to frontIndex and backIndex both and then decrement sizeVar by one."
},
{
"code": null,
"e": 3512,
"s": 3418,
"text": "Else, Update frontIndex as frontIndex = (frontIndex+1)%capacity and decrement sizeVar by one."
},
{
"code": null,
"e": 3563,
"s": 3512,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3567,
"s": 3563,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Class defination for queuetemplate <class X>class Queue { private: // Stores the frontIndex int frontIndex; // Stores the back Index int backIndex; // Stores the array X* arr; // Stores the sizeof queue int sizeVar; // Stores the size of array int capacityVar = 4; public: // Queue class constructor Queue() { arr = new X[capacityVar]; frontIndex = backIndex = -1; sizeVar = 0; } // Function Methods bool empty(); bool full(); void push(X x); void pop(); X front(); X back(); int capacity(); int size();}; // Find the capacity of queuetemplate <class X>int Queue<X>::capacity(){ return capacityVar;} // Find the number of elements// present in Queuetemplate <class X>int Queue<X>::size(){ return sizeVar;} // Function to check if// Queue is empty or nottemplate <class X>bool Queue<X>::empty(){ if (frontIndex == -1 && backIndex == -1) return true; else return false;} // Function to check if the queue// is full or nottemplate <class X>bool Queue<X>::full(){ if (sizeVar == capacityVar) return true; else return false;} // Function to find the front element// of the queuetemplate <class X>X Queue<X>::front(){ // If queue is empty if (empty()) { cout << \"Queue underflow\" << endl; abort(); } return arr[frontIndex];} // Function to find the last element// of the Queuetemplate <class X>X Queue<X>::back(){ if (empty()) { cout << \"Queue underflow\" << endl; abort(); } return arr[backIndex];} // Function to insert the element// to the rear end of the queuetemplate <class X>void Queue<X>::push(X x){ if (full()) { // If the queue is full, then // double the capacity capacityVar = capacityVar * 2; // Initialize new array of // double size X* temp = new X[capacityVar]; // Copy the elements of the // previous array in the order of the queue for (int i = 0, j= frontIndex; i < sizeVar; i++){ temp[i] = arr[j]; j = (j+1) % sizeVar; } // update the front and rear indices in the new array frontIndex = 0; backIndex = sizeVar -1; // Deallocate the memory // of previous array delete[] arr; arr = temp; } // If size is zero if (empty()) { frontIndex = backIndex = 0; arr[backIndex] = x; sizeVar++; return; } // Increment the backIndex backIndex = (backIndex + 1) % capacityVar; arr[backIndex] = x; sizeVar++; return;} // Function to pop an element from// front end of the queuetemplate <class X>void Queue<X>::pop(){ // If queue is empty if (empty()) { cout << \"Queue underflow\" << endl; abort(); } // If there is only one character if (frontIndex == backIndex) { // Mark Queue as empty // and decrement sizeVar frontIndex = backIndex = -1; sizeVar--; return; } // Increment frontIndex cyclically // using modulo arithmetic frontIndex = (frontIndex + 1) % capacityVar; sizeVar--; return;} // Driver Codeint main(){ // Queue initialization Queue<int> q; // Iterate the range [1, 100] for (int i = 1; i < 5; i++) q.push(i); // Print the current capacity cout << \"Current capacity \" << q.capacity() << endl; // Print current size cout << \"Current size \" << q.size() << endl; // Print front elements of queue cout << \"Front element \" << q.front() << endl; // Print last element of the queue cout << \"Rear element \" << q.back() << endl; cout << endl; cout << \"Pop an element\" << endl; // Pop an element from the queue q.pop(); cout << \"Pop an element\" << endl; // Pop an element from the queue q.pop(); cout << endl; // Print the current capacity cout << \"Current capacity \" << q.capacity() << endl; // Print current size cout << \"Current size \" << q.size() << endl; // Print front elements of queue cout << \"Front element \" << q.front() << endl; // Print last element of the queue cout << \"Rear element \" << q.back() << endl; cout << endl; cout << \"Push element 5\" << endl; cout << \"Push element 6\" << endl; q.push(5); q.push(6); cout << endl; // Print the current capacity cout << \"Current capacity \" << q.capacity() << endl; // Print current size cout << \"Current size \" << q.size() << endl; // Print front elements of queue cout << \"Front element \" << q.front() << endl; // Print last element of the queue cout << \"Rear element \" << q.back() << endl; cout << endl; cout << \"Push element 7\" << endl; q.push(7); cout << endl; // Print the current capacity cout << \"Current capacity \" << q.capacity() << endl; // Print current size cout << \"Current size \" << q.size() << endl; // Print front elements of queue cout << \"Front element \" << q.front() << endl; // Print last element of the queue cout << \"Rear element \" << q.back() << endl; return 0;}",
"e": 8958,
"s": 3567,
"text": null
},
{
"code": null,
"e": 9128,
"s": 8958,
"text": "Current capacity 128\nCurrent size 99\nFront element 1\nRear element 99\n\nPop an element\nPop an element\n\nCurrent capacity 128\nCurrent size 97\nFront element 3\nRear element 99"
},
{
"code": null,
"e": 9173,
"s": 9130,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 9190,
"s": 9173,
"text": "arorakashish0911"
},
{
"code": null,
"e": 9210,
"s": 9190,
"text": "ruchithajujjuru1405"
},
{
"code": null,
"e": 9216,
"s": 9210,
"text": "Queue"
},
{
"code": null,
"e": 9222,
"s": 9216,
"text": "Queue"
},
{
"code": null,
"e": 9320,
"s": 9222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9352,
"s": 9320,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9416,
"s": 9352,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9480,
"s": 9416,
"text": "Sum of minimum and maximum elements of all subarrays of size k."
},
{
"code": null,
"e": 9498,
"s": 9480,
"text": "Reversing a Queue"
},
{
"code": null,
"e": 9536,
"s": 9498,
"text": "Implement Stack and Queue using Deque"
},
{
"code": null,
"e": 9585,
"s": 9536,
"text": "First negative integer in every window of size k"
},
{
"code": null,
"e": 9658,
"s": 9585,
"text": "Priority queue of pairs in C++ with ordering by first and second element"
},
{
"code": null,
"e": 9715,
"s": 9658,
"text": "How to efficiently implement k Queues in a single array?"
},
{
"code": null,
"e": 9782,
"s": 9715,
"text": "Find the first non-repeating character from a stream of characters"
}
] |
Python | Pandas dataframe.add_prefix()
|
16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Dataframe.add_prefix() function can be used with both series as well as dataframes.
For Series, the row labels are prefixed.
For DataFrame, the column labels are prefixed.
Syntax: DataFrame.add_prefix(prefix)
Parameters:
prefix : string
Returns: with_prefix: type of caller
For link to CSV file Used in Code, click here
Example #1: Prefix col_ in each columns in the dataframe
# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv("nba.csv") # Printing the first 10 rows of the# dataframe for visualizationdf[:10]
# Using add_prefix() function # to add 'col_' in each column labeldf = df.add_prefix('col_') # Print the dataframedf
Output:
Example #2: Using add_prefix() with Series in pandas
add_prefix() alters the row index labels in the case of series.
# importing pandas as pdimport pandas as pd # Creating a Series df = pd.Series([1, 2, 3, 4, 5, 10, 11, 21, 4]) # This will prefix 'Row_' in # each row of the seriesdf = df.add_prefix('Row_') # Print the Seriesdf
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python pandas-general-functions
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Nov, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 326,
"s": 242,
"text": "Dataframe.add_prefix() function can be used with both series as well as dataframes."
},
{
"code": null,
"e": 367,
"s": 326,
"text": "For Series, the row labels are prefixed."
},
{
"code": null,
"e": 414,
"s": 367,
"text": "For DataFrame, the column labels are prefixed."
},
{
"code": null,
"e": 520,
"s": 414,
"text": "Syntax: DataFrame.add_prefix(prefix)\n\nParameters:\nprefix : string\n\nReturns: with_prefix: type of caller\n"
},
{
"code": null,
"e": 566,
"s": 520,
"text": "For link to CSV file Used in Code, click here"
},
{
"code": null,
"e": 623,
"s": 566,
"text": "Example #1: Prefix col_ in each columns in the dataframe"
},
{
"code": "# importing pandas as pdimport pandas as pd # Making data frame from the csv filedf = pd.read_csv(\"nba.csv\") # Printing the first 10 rows of the# dataframe for visualizationdf[:10]",
"e": 806,
"s": 623,
"text": null
},
{
"code": "# Using add_prefix() function # to add 'col_' in each column labeldf = df.add_prefix('col_') # Print the dataframedf ",
"e": 925,
"s": 806,
"text": null
},
{
"code": null,
"e": 933,
"s": 925,
"text": "Output:"
},
{
"code": null,
"e": 988,
"s": 935,
"text": "Example #2: Using add_prefix() with Series in pandas"
},
{
"code": null,
"e": 1052,
"s": 988,
"text": "add_prefix() alters the row index labels in the case of series."
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating a Series df = pd.Series([1, 2, 3, 4, 5, 10, 11, 21, 4]) # This will prefix 'Row_' in # each row of the seriesdf = df.add_prefix('Row_') # Print the Seriesdf",
"e": 1267,
"s": 1052,
"text": null
},
{
"code": null,
"e": 1275,
"s": 1267,
"text": "Output:"
},
{
"code": null,
"e": 1299,
"s": 1275,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 1331,
"s": 1299,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 1363,
"s": 1331,
"text": "Python pandas-general-functions"
},
{
"code": null,
"e": 1384,
"s": 1363,
"text": "Python pandas-series"
},
{
"code": null,
"e": 1398,
"s": 1384,
"text": "Python-pandas"
},
{
"code": null,
"e": 1405,
"s": 1398,
"text": "Python"
},
{
"code": null,
"e": 1503,
"s": 1405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1535,
"s": 1503,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1562,
"s": 1535,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1583,
"s": 1562,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1606,
"s": 1583,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1662,
"s": 1606,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1693,
"s": 1662,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1735,
"s": 1693,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1777,
"s": 1735,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1816,
"s": 1777,
"text": "Python | Get unique values from a list"
}
] |
How a Preprocessor works in C?
|
08 Feb, 2018
Compiling a C program β Behind the Scene
A Preprocessor is a system software (a computer program that is designed to run on computerβs hardware and application programs). It performs preprocessing of the High Level Language(HLL). Preprocessing is the first step of the language processing system. Language processing system translates the high level language to machine level language or absolute machine code(i.e. to the form that can be understood by machine).
The preprocessor doesnβt know about the scope rules of C. Preprocessor directives like #define come into effect as soon as they are seen and remain in effect until the end of the file that contains them; the programβs block structure is irrelevant.
A Preprocessor mainly performs three tasks on the HLL code :
Removing comments : It removes all the comments. A comment is written only for the humans to understand the code. So, it is obvious that they are of no use to a machine. So, preprocessor removes all of them as they are not required in the execution and wonβt be executed as well.This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.cYou will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler.File inclusion : Including all the files from library that our program needs. In HLL we write #include which is a directive for the preprocessor that tells it to include the contents of the library file specified. For example, #include will tell the preprocessor to include all the contents in the library file stdio.h.This can also be written using double quotes β #include βstdio.hβNote: If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory.Macro expansion : Macros can be called as small functions that are not as overhead to process. If we have to write a function (having a small definition) that needs to be called recursively (again and again), then we should prefer a macro over a function.So, defining these macros is done by preprocessor.#define SI 1000is a simple example of a macro.There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro
#define
// function-like macro
#define () You can delete a macro definition with #undef:// delete the macro
# undef
We can write multi-line macro same like function, but each statement ends with β\β.
#include <stdio.h> #define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ }
Removing comments : It removes all the comments. A comment is written only for the humans to understand the code. So, it is obvious that they are of no use to a machine. So, preprocessor removes all of them as they are not required in the execution and wonβt be executed as well.This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.cYou will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler.
This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.c
You will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler.
File inclusion : Including all the files from library that our program needs. In HLL we write #include which is a directive for the preprocessor that tells it to include the contents of the library file specified. For example, #include will tell the preprocessor to include all the contents in the library file stdio.h.This can also be written using double quotes β #include βstdio.hβNote: If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory.
Macro expansion : Macros can be called as small functions that are not as overhead to process. If we have to write a function (having a small definition) that needs to be called recursively (again and again), then we should prefer a macro over a function.So, defining these macros is done by preprocessor.#define SI 1000is a simple example of a macro.There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro
#define
// function-like macro
#define () You can delete a macro definition with #undef:// delete the macro
# undef
We can write multi-line macro same like function, but each statement ends with β\β.
#include <stdio.h> #define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ }
#define SI 1000
is a simple example of a macro.
There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro
#define
// function-like macro
#define ()
// object-like macro
#define
// function-like macro
#define ()
You can delete a macro definition with #undef:// delete the macro
# undef
// delete the macro
# undef
We can write multi-line macro same like function, but each statement ends with β\β.
#include <stdio.h> #define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ }
#include <stdio.h> #define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ }
This article is contributed by Diksha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Macro & Preprocessor
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Feb, 2018"
},
{
"code": null,
"e": 93,
"s": 52,
"text": "Compiling a C program β Behind the Scene"
},
{
"code": null,
"e": 515,
"s": 93,
"text": "A Preprocessor is a system software (a computer program that is designed to run on computerβs hardware and application programs). It performs preprocessing of the High Level Language(HLL). Preprocessing is the first step of the language processing system. Language processing system translates the high level language to machine level language or absolute machine code(i.e. to the form that can be understood by machine)."
},
{
"code": null,
"e": 764,
"s": 515,
"text": "The preprocessor doesnβt know about the scope rules of C. Preprocessor directives like #define come into effect as soon as they are seen and remain in effect until the end of the file that contains them; the programβs block structure is irrelevant."
},
{
"code": null,
"e": 825,
"s": 764,
"text": "A Preprocessor mainly performs three tasks on the HLL code :"
},
{
"code": null,
"e": 2940,
"s": 825,
"text": "Removing comments : It removes all the comments. A comment is written only for the humans to understand the code. So, it is obvious that they are of no use to a machine. So, preprocessor removes all of them as they are not required in the execution and wonβt be executed as well.This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.cYou will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler.File inclusion : Including all the files from library that our program needs. In HLL we write #include which is a directive for the preprocessor that tells it to include the contents of the library file specified. For example, #include will tell the preprocessor to include all the contents in the library file stdio.h.This can also be written using double quotes β #include βstdio.hβNote: If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory.Macro expansion : Macros can be called as small functions that are not as overhead to process. If we have to write a function (having a small definition) that needs to be called recursively (again and again), then we should prefer a macro over a function.So, defining these macros is done by preprocessor.#define SI 1000is a simple example of a macro.There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro\n#define \n// function-like macro \n#define () You can delete a macro definition with #undef:// delete the macro\n# undef \n We can write multi-line macro same like function, but each statement ends with β\\β. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include <stdio.h> #define MACRO(num, str) {\\ printf(\"%d\", num);\\ printf(\" is\");\\ printf(\" %s number\", str);\\ printf(\"\\n\");\\ }\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 3513,
"s": 2940,
"text": "Removing comments : It removes all the comments. A comment is written only for the humans to understand the code. So, it is obvious that they are of no use to a machine. So, preprocessor removes all of them as they are not required in the execution and wonβt be executed as well.This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.cYou will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler."
},
{
"code": null,
"e": 3664,
"s": 3513,
"text": "This is how to see a file with removed comments in linux) :Write a C code (let the file name be prog.c). Preprocess it using the command gcc -E prog.c"
},
{
"code": null,
"e": 3808,
"s": 3664,
"text": "You will see the output with the code having no comments.This file is saved with a β.iβ extension (prog.i) which will be input to the compiler."
},
{
"code": null,
"e": 4433,
"s": 3808,
"text": "File inclusion : Including all the files from library that our program needs. In HLL we write #include which is a directive for the preprocessor that tells it to include the contents of the library file specified. For example, #include will tell the preprocessor to include all the contents in the library file stdio.h.This can also be written using double quotes β #include βstdio.hβNote: If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory."
},
{
"code": null,
"e": 5352,
"s": 4433,
"text": "Macro expansion : Macros can be called as small functions that are not as overhead to process. If we have to write a function (having a small definition) that needs to be called recursively (again and again), then we should prefer a macro over a function.So, defining these macros is done by preprocessor.#define SI 1000is a simple example of a macro.There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro\n#define \n// function-like macro \n#define () You can delete a macro definition with #undef:// delete the macro\n# undef \n We can write multi-line macro same like function, but each statement ends with β\\β. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include <stdio.h> #define MACRO(num, str) {\\ printf(\"%d\", num);\\ printf(\" is\");\\ printf(\" %s number\", str);\\ printf(\"\\n\");\\ }\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 5368,
"s": 5352,
"text": "#define SI 1000"
},
{
"code": null,
"e": 5400,
"s": 5368,
"text": "is a simple example of a macro."
},
{
"code": null,
"e": 5591,
"s": 5400,
"text": "There are two types of macros: Object-like (do not take parameters) and function-like (Can take parameters)// object-like macro\n#define \n// function-like macro \n#define () "
},
{
"code": null,
"e": 5675,
"s": 5591,
"text": "// object-like macro\n#define \n// function-like macro \n#define () "
},
{
"code": null,
"e": 5751,
"s": 5675,
"text": "You can delete a macro definition with #undef:// delete the macro\n# undef "
},
{
"code": null,
"e": 5781,
"s": 5751,
"text": "// delete the macro\n# undef "
},
{
"code": null,
"e": 6083,
"s": 5781,
"text": " We can write multi-line macro same like function, but each statement ends with β\\β. \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include <stdio.h> #define MACRO(num, str) {\\ printf(\"%d\", num);\\ printf(\" is\");\\ printf(\" %s number\", str);\\ printf(\"\\n\");\\ }\n\n\n\n\n\n\n"
},
{
"code": "#include <stdio.h> #define MACRO(num, str) {\\ printf(\"%d\", num);\\ printf(\" is\");\\ printf(\" %s number\", str);\\ printf(\"\\n\");\\ }\n",
"e": 6273,
"s": 6083,
"text": null
},
{
"code": null,
"e": 6567,
"s": 6273,
"text": "This article is contributed by Diksha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 6692,
"s": 6567,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 6715,
"s": 6692,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 6726,
"s": 6715,
"text": "C Language"
}
] |
SQL USE Database Statement
|
06 Sep, 2021
SQL(Structured Query Language) is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, and use command is one of them. The use command is used when there are multiple databases in the SQL and the user or programmer specifically wants to use a particular database. Thus, in simple terms, the use statement selects a specific database and then performs operations on it using the inbuilt commands of SQL.
Syntax:
USE database_name;
Example 1:
The user wants to works on the databases named βGEEKSβ. So the user will write:
USE candy;
Example 2:
Before using any database using the use command, itβs necessary to first create it. In order to create a database in SQL, the following command is used. Here, we create a database named βGFG1β:
CREATE DATABASE GFG1
Now, after the user has created a database named candy, we can use this database to perform the database operations. So, for that, the user has to type the USE command as follows:
USE GFG1
After performing desired operations on the database, if we do not want the database, We can drop the database using the DROP command:
DROP DATABASE GFG1
Remember, once a database is dropped, itβs removed permanently from the list of available databases, there is no way to retrieve the data of the table or the complete database in any possible way.
After using the drop command, if the user types β
USE GFG1
The SQL database will throw an error as the GFG1 database has been removed permanently from the database using the drop command.
abhijithoyur
Picked
Class 12
School Learning
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting Algorithms in Python
Querying Data from a Database using fetchone() and fetchall()
Cardinality in DBMS
Intrinsic Semiconductors and Extrinsic Semiconductors
Different Types of Wireless Communication Media
How to Align Text in HTML?
What are Different Output Devices?
Generations of Computers - Computer Fundamentals
What is a Storage Device? Definition, Types, Examples
Types of Internet Protocols
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 643,
"s": 28,
"text": "SQL(Structured Query Language) is a standard Database language that is used to create, maintain and retrieve the data from relational databases like MySQL, Oracle, etc. It is flexible and user-friendly. In SQL, to interact with the database, the users have to type queries that have certain syntax, and use command is one of them. The use command is used when there are multiple databases in the SQL and the user or programmer specifically wants to use a particular database. Thus, in simple terms, the use statement selects a specific database and then performs operations on it using the inbuilt commands of SQL."
},
{
"code": null,
"e": 651,
"s": 643,
"text": "Syntax:"
},
{
"code": null,
"e": 670,
"s": 651,
"text": "USE database_name;"
},
{
"code": null,
"e": 681,
"s": 670,
"text": "Example 1:"
},
{
"code": null,
"e": 761,
"s": 681,
"text": "The user wants to works on the databases named βGEEKSβ. So the user will write:"
},
{
"code": null,
"e": 772,
"s": 761,
"text": "USE candy;"
},
{
"code": null,
"e": 783,
"s": 772,
"text": "Example 2:"
},
{
"code": null,
"e": 977,
"s": 783,
"text": "Before using any database using the use command, itβs necessary to first create it. In order to create a database in SQL, the following command is used. Here, we create a database named βGFG1β:"
},
{
"code": null,
"e": 998,
"s": 977,
"text": "CREATE DATABASE GFG1"
},
{
"code": null,
"e": 1178,
"s": 998,
"text": "Now, after the user has created a database named candy, we can use this database to perform the database operations. So, for that, the user has to type the USE command as follows:"
},
{
"code": null,
"e": 1187,
"s": 1178,
"text": "USE GFG1"
},
{
"code": null,
"e": 1321,
"s": 1187,
"text": "After performing desired operations on the database, if we do not want the database, We can drop the database using the DROP command:"
},
{
"code": null,
"e": 1341,
"s": 1321,
"text": "DROP DATABASE GFG1"
},
{
"code": null,
"e": 1538,
"s": 1341,
"text": "Remember, once a database is dropped, itβs removed permanently from the list of available databases, there is no way to retrieve the data of the table or the complete database in any possible way."
},
{
"code": null,
"e": 1588,
"s": 1538,
"text": "After using the drop command, if the user types β"
},
{
"code": null,
"e": 1597,
"s": 1588,
"text": "USE GFG1"
},
{
"code": null,
"e": 1727,
"s": 1597,
"text": "The SQL database will throw an error as the GFG1 database has been removed permanently from the database using the drop command. "
},
{
"code": null,
"e": 1740,
"s": 1727,
"text": "abhijithoyur"
},
{
"code": null,
"e": 1747,
"s": 1740,
"text": "Picked"
},
{
"code": null,
"e": 1756,
"s": 1747,
"text": "Class 12"
},
{
"code": null,
"e": 1772,
"s": 1756,
"text": "School Learning"
},
{
"code": null,
"e": 1791,
"s": 1772,
"text": "School Programming"
},
{
"code": null,
"e": 1889,
"s": 1791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1918,
"s": 1889,
"text": "Sorting Algorithms in Python"
},
{
"code": null,
"e": 1980,
"s": 1918,
"text": "Querying Data from a Database using fetchone() and fetchall()"
},
{
"code": null,
"e": 2000,
"s": 1980,
"text": "Cardinality in DBMS"
},
{
"code": null,
"e": 2054,
"s": 2000,
"text": "Intrinsic Semiconductors and Extrinsic Semiconductors"
},
{
"code": null,
"e": 2102,
"s": 2054,
"text": "Different Types of Wireless Communication Media"
},
{
"code": null,
"e": 2129,
"s": 2102,
"text": "How to Align Text in HTML?"
},
{
"code": null,
"e": 2164,
"s": 2129,
"text": "What are Different Output Devices?"
},
{
"code": null,
"e": 2213,
"s": 2164,
"text": "Generations of Computers - Computer Fundamentals"
},
{
"code": null,
"e": 2267,
"s": 2213,
"text": "What is a Storage Device? Definition, Types, Examples"
}
] |
Create a User-Defined Data Type Alias in SQL Server
|
17 Mar, 2021
SQL Server has multiple data types e.g. integers, char, varchar, doubles, strings, etc. which are used for keeping specific values. Although built-in data types could store specific values, sometimes SQL DBA may need to store more specific values and create customized data types.
We can create a user-defined data type using below two methods β
Using T-SQL
Using SQL Server Management Studio
Create a User-Defined Data Type using T-SQL :
Syntax β
use DatabaseName
Create Type UserDefineDataTypeName
from datatype NOT NULL
Example βCreating a User-Defined Data Type named βCodeβ which stores only 4 letters.
use Database name
Create Type Code
from varchar(4) NOT NULL
Create a User-Defined Data Type using SQL Server Management Studio :
Connect to SQL Server
Expand Database
Expand Programmability
Expand Types
Select User Defined Data Types
ight-click on it and select βNew User-Defined Data Typeβ
Fill in the required information to create data type, Click OK.
Use custom datatype in a table or SQL query β
Note: User-Defined Data Types standalone does not have an advantage over built-in. But if rules are created to bind them with the custom data type you have recently created.
1. Create a rule β
Syntax β
Create Rule RuleName
as @UserDefineDataTypeName not like ruletype
Example β
Create Rule Code_Rule
as @Code not like '%D%'
In the above example, a rule that accepts every input except word with βDβ letter.
2. Bind the Rule and User-Defined Data Type βTo combine or bind the Rule and User-Defined Data Type: we could use the stored procedure βsp_bindruleβ:
Syntax β
sp_bindrule RuleName,'UserDefineDataTypeName'
Example β
sp_bindrule Code_Rule,'Code'
In the above example, Code_Rule will bind the rule to user-defined data type βCodeβ.
3. Unbind the rule from User-Defined Data Type β
To unbind the rule from User-Defined Data Type use βsp_unbindruleβ.
Syntax β
sp_unbindrule 'UserDefineDataTypeName'
Example β
sp_unbindrule 'Code'
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window functions in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
RANK() Function in SQL Server
What is Temporary Table in SQL?
SQL | DROP, TRUNCATE
SQL indexes
SQL using Python
SQL | MINUS Operator
Union and Union All in MS SQL Server
SQL | Query Processing
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 309,
"s": 28,
"text": "SQL Server has multiple data types e.g. integers, char, varchar, doubles, strings, etc. which are used for keeping specific values. Although built-in data types could store specific values, sometimes SQL DBA may need to store more specific values and create customized data types."
},
{
"code": null,
"e": 374,
"s": 309,
"text": "We can create a user-defined data type using below two methods β"
},
{
"code": null,
"e": 386,
"s": 374,
"text": "Using T-SQL"
},
{
"code": null,
"e": 421,
"s": 386,
"text": "Using SQL Server Management Studio"
},
{
"code": null,
"e": 467,
"s": 421,
"text": "Create a User-Defined Data Type using T-SQL :"
},
{
"code": null,
"e": 476,
"s": 467,
"text": "Syntax β"
},
{
"code": null,
"e": 555,
"s": 476,
"text": "use DatabaseName\nCreate Type UserDefineDataTypeName \nfrom datatype NOT NULL"
},
{
"code": null,
"e": 640,
"s": 555,
"text": "Example βCreating a User-Defined Data Type named βCodeβ which stores only 4 letters."
},
{
"code": null,
"e": 704,
"s": 640,
"text": "use Database name\nCreate Type Code \nfrom varchar(4) NOT NULL"
},
{
"code": null,
"e": 773,
"s": 704,
"text": "Create a User-Defined Data Type using SQL Server Management Studio :"
},
{
"code": null,
"e": 795,
"s": 773,
"text": "Connect to SQL Server"
},
{
"code": null,
"e": 811,
"s": 795,
"text": "Expand Database"
},
{
"code": null,
"e": 834,
"s": 811,
"text": "Expand Programmability"
},
{
"code": null,
"e": 847,
"s": 834,
"text": "Expand Types"
},
{
"code": null,
"e": 878,
"s": 847,
"text": "Select User Defined Data Types"
},
{
"code": null,
"e": 935,
"s": 878,
"text": "ight-click on it and select βNew User-Defined Data Typeβ"
},
{
"code": null,
"e": 999,
"s": 935,
"text": "Fill in the required information to create data type, Click OK."
},
{
"code": null,
"e": 1045,
"s": 999,
"text": "Use custom datatype in a table or SQL query β"
},
{
"code": null,
"e": 1219,
"s": 1045,
"text": "Note: User-Defined Data Types standalone does not have an advantage over built-in. But if rules are created to bind them with the custom data type you have recently created."
},
{
"code": null,
"e": 1238,
"s": 1219,
"text": "1. Create a rule β"
},
{
"code": null,
"e": 1247,
"s": 1238,
"text": "Syntax β"
},
{
"code": null,
"e": 1315,
"s": 1247,
"text": "Create Rule RuleName \nas @UserDefineDataTypeName not like ruletype"
},
{
"code": null,
"e": 1325,
"s": 1315,
"text": "Example β"
},
{
"code": null,
"e": 1373,
"s": 1325,
"text": "Create Rule Code_Rule \nas @Code not like '%D%'"
},
{
"code": null,
"e": 1457,
"s": 1373,
"text": "In the above example, a rule that accepts every input except word with βDβ letter. "
},
{
"code": null,
"e": 1607,
"s": 1457,
"text": "2. Bind the Rule and User-Defined Data Type βTo combine or bind the Rule and User-Defined Data Type: we could use the stored procedure βsp_bindruleβ:"
},
{
"code": null,
"e": 1616,
"s": 1607,
"text": "Syntax β"
},
{
"code": null,
"e": 1662,
"s": 1616,
"text": "sp_bindrule RuleName,'UserDefineDataTypeName'"
},
{
"code": null,
"e": 1672,
"s": 1662,
"text": "Example β"
},
{
"code": null,
"e": 1701,
"s": 1672,
"text": "sp_bindrule Code_Rule,'Code'"
},
{
"code": null,
"e": 1786,
"s": 1701,
"text": "In the above example, Code_Rule will bind the rule to user-defined data type βCodeβ."
},
{
"code": null,
"e": 1835,
"s": 1786,
"text": "3. Unbind the rule from User-Defined Data Type β"
},
{
"code": null,
"e": 1903,
"s": 1835,
"text": "To unbind the rule from User-Defined Data Type use βsp_unbindruleβ."
},
{
"code": null,
"e": 1912,
"s": 1903,
"text": "Syntax β"
},
{
"code": null,
"e": 1951,
"s": 1912,
"text": "sp_unbindrule 'UserDefineDataTypeName'"
},
{
"code": null,
"e": 1961,
"s": 1951,
"text": "Example β"
},
{
"code": null,
"e": 1982,
"s": 1961,
"text": "sp_unbindrule 'Code'"
},
{
"code": null,
"e": 1991,
"s": 1982,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2002,
"s": 1991,
"text": "SQL-Server"
},
{
"code": null,
"e": 2006,
"s": 2002,
"text": "SQL"
},
{
"code": null,
"e": 2010,
"s": 2006,
"text": "SQL"
},
{
"code": null,
"e": 2108,
"s": 2010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2132,
"s": 2108,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2198,
"s": 2132,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2228,
"s": 2198,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2260,
"s": 2228,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2281,
"s": 2260,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 2293,
"s": 2281,
"text": "SQL indexes"
},
{
"code": null,
"e": 2310,
"s": 2293,
"text": "SQL using Python"
},
{
"code": null,
"e": 2331,
"s": 2310,
"text": "SQL | MINUS Operator"
},
{
"code": null,
"e": 2368,
"s": 2331,
"text": "Union and Union All in MS SQL Server"
}
] |
Can Virtual Functions be Inlined in C++?
|
01 Dec, 2021
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding.
Inline functions are used to replace the function calling location with the definition of the inline function at compile time. They are used for efficiency. The whole idea behind the inline functions is that whenever an inline function is called code of the inline function gets inserted or substituted at the point of the inline function call at compile time. Inline functions are very useful when small functions are frequently used and called in a program many times.
By default, all the functions defined inside the class are implicitly or automatically considered as inline except virtual functions.
Note: inline is a request to the compiler and its compilers choice to do inlining or not.
Can virtual functions be inlined?
Whenever a virtual function is called using a base class reference or pointer it cannot be inlined because the call is resolved at runtime, but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.
C++
// CPP program to demonstrate that// virtual functions can be inlined#include <iostream>using namespace std; class Base {public: virtual void who() { cout << "I am Base\n"; }};class Derived : public Base {public: void who() { cout << "I am Derived\n"; }}; int main(){ // Part 1 Base b; b.who(); // Part 2 Base* ptr = new Derived(); ptr->who(); return 0;}
I am Base
I am Derived
Explanation: In Part 1, the virtual function who() is called through the object of the class. Since it will be resolved at compile-time, so it can be inlined. In Part 2, the virtual function is called through a pointer, so it cannot be inlined.
This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
CPP-Functions
cpp-virtual
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
std::string class in C++
Unordered Sets in C++ Standard Template Library
Memory Layout of C Programs
What is the purpose of a function prototype?
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 286,
"s": 54,
"text": "Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. "
},
{
"code": null,
"e": 758,
"s": 286,
"text": "Inline functions are used to replace the function calling location with the definition of the inline function at compile time. They are used for efficiency. The whole idea behind the inline functions is that whenever an inline function is called code of the inline function gets inserted or substituted at the point of the inline function call at compile time. Inline functions are very useful when small functions are frequently used and called in a program many times. "
},
{
"code": null,
"e": 893,
"s": 758,
"text": "By default, all the functions defined inside the class are implicitly or automatically considered as inline except virtual functions. "
},
{
"code": null,
"e": 983,
"s": 893,
"text": "Note: inline is a request to the compiler and its compilers choice to do inlining or not."
},
{
"code": null,
"e": 1017,
"s": 983,
"text": "Can virtual functions be inlined?"
},
{
"code": null,
"e": 1330,
"s": 1017,
"text": "Whenever a virtual function is called using a base class reference or pointer it cannot be inlined because the call is resolved at runtime, but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time. "
},
{
"code": null,
"e": 1334,
"s": 1330,
"text": "C++"
},
{
"code": "// CPP program to demonstrate that// virtual functions can be inlined#include <iostream>using namespace std; class Base {public: virtual void who() { cout << \"I am Base\\n\"; }};class Derived : public Base {public: void who() { cout << \"I am Derived\\n\"; }}; int main(){ // Part 1 Base b; b.who(); // Part 2 Base* ptr = new Derived(); ptr->who(); return 0;}",
"e": 1718,
"s": 1334,
"text": null
},
{
"code": null,
"e": 1741,
"s": 1718,
"text": "I am Base\nI am Derived"
},
{
"code": null,
"e": 1986,
"s": 1741,
"text": "Explanation: In Part 1, the virtual function who() is called through the object of the class. Since it will be resolved at compile-time, so it can be inlined. In Part 2, the virtual function is called through a pointer, so it cannot be inlined."
},
{
"code": null,
"e": 2156,
"s": 1986,
"text": "This article is contributed by Meet Pravasi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2170,
"s": 2156,
"text": "anshikajain26"
},
{
"code": null,
"e": 2184,
"s": 2170,
"text": "CPP-Functions"
},
{
"code": null,
"e": 2196,
"s": 2184,
"text": "cpp-virtual"
},
{
"code": null,
"e": 2207,
"s": 2196,
"text": "C Language"
},
{
"code": null,
"e": 2211,
"s": 2207,
"text": "C++"
},
{
"code": null,
"e": 2215,
"s": 2211,
"text": "CPP"
},
{
"code": null,
"e": 2313,
"s": 2215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2335,
"s": 2313,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 2360,
"s": 2335,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2408,
"s": 2360,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2436,
"s": 2408,
"text": "Memory Layout of C Programs"
},
{
"code": null,
"e": 2481,
"s": 2436,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 2499,
"s": 2481,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 2542,
"s": 2499,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2588,
"s": 2542,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 2631,
"s": 2588,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Java Program to Convert a Float value to String
|
30 Sep, 2021
Given a Float value in Java, the task is to write a Java program to convert this float value to string type.
Examples:
Input: 1.0
Output: "1.0"
Input: 3.14
Output: "3.14"
Strings β Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well.
Float β The float data type is a single-precision 32-bit IEEE 754 floating-point. Its value range is unlimited. Using a float (instead of double) is suggested if you need to save memory in large arrays of floating-point numbers. Its default value is 0.0F.
There are numerous approaches to convert a float value to a String in Java. These are β
Using + operator
Using String.valueOf() method
Using Float.toString() method
One method is to create a string variable and then append the float value to the string variable. This will directly convert the float value to a string and add it to the string variable.
Below is the implementation of the above approach:
Java
// Java Program to convert float value to String valueclass GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using + operator method String stringValue = "" + floatValue; return (stringValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1f; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + " after converting into string = " + stringValue); }}
1.0 after converting into string = 1.0
The simplest way to do so is using the valueOf() method of the String class in java.lang package. This method takes the float value to be parsed and returns the value in String type from it.
Syntax:
String.valueOf(floatValue);
Below is the implementation of the above approach:
Java
// Java Program to convert float value to String valueclass GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using valueOf() method return String.valueOf(floatValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + " after converting into string = " + stringValue); }}
1.0 after converting into string = 1.0
The Float.toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.
Syntax:
String str = Float.toString(val);
Below is the implementation of the above approach:
Java
// Java Program to convert float value to String valueimport java.util.*;class GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using valueOf() method return Float.toString(floatValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + " after converting into string = " + stringValue); }}
1.0 after converting into string = 1.0
nishkarshgandhi
Java-Data Types
Java-Float
Java-String-Programs
Java
Java Programs
Java
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": 137,
"s": 28,
"text": "Given a Float value in Java, the task is to write a Java program to convert this float value to string type."
},
{
"code": null,
"e": 148,
"s": 137,
"text": "Examples: "
},
{
"code": null,
"e": 201,
"s": 148,
"text": "Input: 1.0\nOutput: \"1.0\"\n\nInput: 3.14\nOutput: \"3.14\""
},
{
"code": null,
"e": 429,
"s": 201,
"text": "Strings β Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. "
},
{
"code": null,
"e": 685,
"s": 429,
"text": "Float β The float data type is a single-precision 32-bit IEEE 754 floating-point. Its value range is unlimited. Using a float (instead of double) is suggested if you need to save memory in large arrays of floating-point numbers. Its default value is 0.0F."
},
{
"code": null,
"e": 774,
"s": 685,
"text": "There are numerous approaches to convert a float value to a String in Java. These are β "
},
{
"code": null,
"e": 791,
"s": 774,
"text": "Using + operator"
},
{
"code": null,
"e": 821,
"s": 791,
"text": "Using String.valueOf() method"
},
{
"code": null,
"e": 851,
"s": 821,
"text": "Using Float.toString() method"
},
{
"code": null,
"e": 1040,
"s": 851,
"text": "One method is to create a string variable and then append the float value to the string variable. This will directly convert the float value to a string and add it to the string variable. "
},
{
"code": null,
"e": 1091,
"s": 1040,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1096,
"s": 1091,
"text": "Java"
},
{
"code": "// Java Program to convert float value to String valueclass GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using + operator method String stringValue = \"\" + floatValue; return (stringValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1f; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + \" after converting into string = \" + stringValue); }}",
"e": 1891,
"s": 1096,
"text": null
},
{
"code": null,
"e": 1930,
"s": 1891,
"text": "1.0 after converting into string = 1.0"
},
{
"code": null,
"e": 2122,
"s": 1930,
"text": "The simplest way to do so is using the valueOf() method of the String class in java.lang package. This method takes the float value to be parsed and returns the value in String type from it. "
},
{
"code": null,
"e": 2131,
"s": 2122,
"text": "Syntax: "
},
{
"code": null,
"e": 2159,
"s": 2131,
"text": "String.valueOf(floatValue);"
},
{
"code": null,
"e": 2210,
"s": 2159,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2215,
"s": 2210,
"text": "Java"
},
{
"code": "// Java Program to convert float value to String valueclass GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using valueOf() method return String.valueOf(floatValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + \" after converting into string = \" + stringValue); }}",
"e": 2988,
"s": 2215,
"text": null
},
{
"code": null,
"e": 3027,
"s": 2988,
"text": "1.0 after converting into string = 1.0"
},
{
"code": null,
"e": 3168,
"s": 3027,
"text": "The Float.toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class."
},
{
"code": null,
"e": 3176,
"s": 3168,
"text": "Syntax:"
},
{
"code": null,
"e": 3210,
"s": 3176,
"text": "String str = Float.toString(val);"
},
{
"code": null,
"e": 3261,
"s": 3210,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3266,
"s": 3261,
"text": "Java"
},
{
"code": "// Java Program to convert float value to String valueimport java.util.*;class GFG { // Function to convert float value to String value public static String convertFloatToString(float floatValue) { // Convert float value to String value // using valueOf() method return Float.toString(floatValue); } // Driver code public static void main(String[] args) { // The float value float floatValue = 1; // The expected string value String stringValue; // Convert float to string stringValue = convertFloatToString(floatValue); // Print the expected string value System.out.println( floatValue + \" after converting into string = \" + stringValue); }}",
"e": 4058,
"s": 3266,
"text": null
},
{
"code": null,
"e": 4097,
"s": 4058,
"text": "1.0 after converting into string = 1.0"
},
{
"code": null,
"e": 4113,
"s": 4097,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 4129,
"s": 4113,
"text": "Java-Data Types"
},
{
"code": null,
"e": 4140,
"s": 4129,
"text": "Java-Float"
},
{
"code": null,
"e": 4161,
"s": 4140,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 4166,
"s": 4161,
"text": "Java"
},
{
"code": null,
"e": 4180,
"s": 4166,
"text": "Java Programs"
},
{
"code": null,
"e": 4185,
"s": 4180,
"text": "Java"
}
] |
Program to convert given Binary to its equivalent ASCII character string
|
27 May, 2022
Given a binary string str, the task is to find its equivalent ASCII character string.
Examples:
Input: str = β0110000101100010βOutput: abExplanation: Dividing str into set of 8 bits as follows:
01100001 = 97, ASCII value of 97 is βaβ.
01100010 = 98, ASCII value of 98 is βbβ.
Therefore, the required ASCII character string is βabβ.
Input: str = β10000101100βOutput: Not PossibleExplanation: The given binary string is not a valid string as the number of characters is not a multiple of 8.
Approach: This problem is implementation-based problem. Follow the steps below to solve the given problem.
At first, check if s is divisible by 8 or notIf not divisible by 8 print βNot PossibleβOtherwise, move to the next step
If not divisible by 8 print βNot Possibleβ
Otherwise, move to the next step
Declare an empty string to store all the ASCII character string.
Traverses in a jump of 8 characters and in each step find the decimal equivalent value of the current set of 8 bits.
Convert the decimal value to its equivalent ASCII character and append it to the res string.
Return the res string.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation for above approach#include <bits/stdc++.h>using namespace std; // Function to convert binary to decimalint binaryToDecimal(string n){ string num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num[i] == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIstring setStringtoASCII(string str){ // To store size of s int N = int(str.size()); // If given string is not a // valid string if (N % 8 != 0) { return "Not Possible!"; } // To store final answer string res = ""; // Loop to iterate through string for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.substr(i, 8))); // Apprend the ASCII character // equivalent to current value res += char(decimal_value); } // Return Answer return res;} // Driver Codeint main(){ string s = "0110000101100010"; cout << setStringtoASCII(s); return 0;}
// Java implementation for above approachimport java.util.*; class GFG{ // Function to convert binary to decimalstatic int binaryToDecimal(String n){ String num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num.charAt(i) == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIstatic String setStringtoASCII(String str){ // To store size of s int N = (str.length()); // If given String is not a // valid String if (N % 8 != 0) { return "Not Possible!"; } // To store final answer String res = ""; // Loop to iterate through String for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.substring(i, 8+i))); // Apprend the ASCII character // equivalent to current value res += (char)(decimal_value); } // Return Answer return res;} // Driver Codepublic static void main(String[] args){ String s = "0110000101100010"; System.out.print(setStringtoASCII(s)); }} // This code is contributed by 29AjayKumar
# python implementation for above approach # Function to convert binary to decimaldef binaryToDecimal(n): num = n # Stores the decimal value dec_value = 0 # Initializing base value to 1 base = 1 le = len(num) for i in range(le - 1, -1, -1): # If the current bit is 1 if (num[i] == '1'): dec_value += base base = base * 2 # Return answer return dec_value # Function to convert binary to ASCIIdef setStringtoASCII(str): # To store size of s N = int(len(str)) # If given string is not a # valid string if (N % 8 != 0): return "Not Possible!" # To store final answer res = "" # Loop to iterate through string for i in range(0, N, 8): decimal_value = binaryToDecimal(str[i: i + 8]) # Apprend the ASCII character # equivalent to current value res += chr(decimal_value) # Return Answer return res # Driver Codeif __name__ == "__main__": s = "0110000101100010" print(setStringtoASCII(s)) # This code is contributed by rakeshsahni
// C# implementation for above approachusing System; class GFG { // Function to convert binary to decimal static int binaryToDecimal(string n) { string num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base1 = 1; int len = num.Length; for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num[i] == '1') dec_value += base1; base1 = base1 * 2; } // Return answer return dec_value; } // Function to convert binary to ASCII static string setStringtoASCII(string str) { // To store size of s int N = (str.Length); // If given String is not a // valid String if (N % 8 != 0) { return "Not Possible!"; } // To store final answer string res = ""; // Loop to iterate through String for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.Substring(i, 8))); // Apprend the ASCII character // equivalent to current value res += (char)(decimal_value); } // Return Answer return res; } // Driver Code public static void Main(string[] args) { string s = "0110000101100010"; Console.WriteLine(setStringtoASCII(s)); }} // This code is contributed by ukasp.
<script> // JavaScript implementation for above approach // Function to convert binary to decimalfunction binaryToDecimal(n){ let num = n; // Stores the decimal value let dec_value = 0; // Initializing base value to 1 let base = 1; let len = n.length; for(let i = len - 1; i >= 0; i--) { // If the current bit is 1 if (n[i] == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIfunction setStringtoASCII(str){ // To store size of s let N = str.length; // If given string is not a // valid string if (N % 8 != 0) { return "Not Possible!"; } // To store final answer let res = ""; // Loop to iterate through string for(let i = 0; i < N; i = i + 8) { let decimal_value = binaryToDecimal( (str.slice(i, i + 8))); // Apprend the ASCII character // equivalent to current value res = res + String.fromCharCode(decimal_value); } // Return Answer return res;} // Driver Codelet s = "0110000101100010";document.write(setStringtoASCII(s)); // This code is contributed by Potta Lokesh </script>
ab
Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(N)
lokeshpotta20
rakeshsahni
29AjayKumar
ukasp
rohitsingh07052
ASCII
binary-string
Bit Magic
School Programming
Searching
Strings
Searching
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if binary string multiple of 3 using DFA
Check for Integer Overflow
Maximum AND value of a pair in an array
Detect if two integers have opposite signs
Extract 'k' bits from a given position in a number.
C++ Classes and Objects
Python Dictionary
Object Oriented Programming in C++
Inheritance in C++
Arrays in C/C++
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 114,
"s": 28,
"text": "Given a binary string str, the task is to find its equivalent ASCII character string."
},
{
"code": null,
"e": 125,
"s": 114,
"text": "Examples: "
},
{
"code": null,
"e": 224,
"s": 125,
"text": "Input: str = β0110000101100010βOutput: abExplanation: Dividing str into set of 8 bits as follows: "
},
{
"code": null,
"e": 265,
"s": 224,
"text": "01100001 = 97, ASCII value of 97 is βaβ."
},
{
"code": null,
"e": 306,
"s": 265,
"text": "01100010 = 98, ASCII value of 98 is βbβ."
},
{
"code": null,
"e": 362,
"s": 306,
"text": "Therefore, the required ASCII character string is βabβ."
},
{
"code": null,
"e": 519,
"s": 362,
"text": "Input: str = β10000101100βOutput: Not PossibleExplanation: The given binary string is not a valid string as the number of characters is not a multiple of 8."
},
{
"code": null,
"e": 627,
"s": 519,
"text": "Approach: This problem is implementation-based problem. Follow the steps below to solve the given problem. "
},
{
"code": null,
"e": 747,
"s": 627,
"text": "At first, check if s is divisible by 8 or notIf not divisible by 8 print βNot PossibleβOtherwise, move to the next step"
},
{
"code": null,
"e": 790,
"s": 747,
"text": "If not divisible by 8 print βNot Possibleβ"
},
{
"code": null,
"e": 823,
"s": 790,
"text": "Otherwise, move to the next step"
},
{
"code": null,
"e": 888,
"s": 823,
"text": "Declare an empty string to store all the ASCII character string."
},
{
"code": null,
"e": 1005,
"s": 888,
"text": "Traverses in a jump of 8 characters and in each step find the decimal equivalent value of the current set of 8 bits."
},
{
"code": null,
"e": 1098,
"s": 1005,
"text": "Convert the decimal value to its equivalent ASCII character and append it to the res string."
},
{
"code": null,
"e": 1121,
"s": 1098,
"text": "Return the res string."
},
{
"code": null,
"e": 1172,
"s": 1121,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1178,
"s": 1172,
"text": "C++14"
},
{
"code": null,
"e": 1183,
"s": 1178,
"text": "Java"
},
{
"code": null,
"e": 1191,
"s": 1183,
"text": "Python3"
},
{
"code": null,
"e": 1194,
"s": 1191,
"text": "C#"
},
{
"code": null,
"e": 1205,
"s": 1194,
"text": "Javascript"
},
{
"code": "// C++ implementation for above approach#include <bits/stdc++.h>using namespace std; // Function to convert binary to decimalint binaryToDecimal(string n){ string num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num[i] == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIstring setStringtoASCII(string str){ // To store size of s int N = int(str.size()); // If given string is not a // valid string if (N % 8 != 0) { return \"Not Possible!\"; } // To store final answer string res = \"\"; // Loop to iterate through string for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.substr(i, 8))); // Apprend the ASCII character // equivalent to current value res += char(decimal_value); } // Return Answer return res;} // Driver Codeint main(){ string s = \"0110000101100010\"; cout << setStringtoASCII(s); return 0;}",
"e": 2413,
"s": 1205,
"text": null
},
{
"code": "// Java implementation for above approachimport java.util.*; class GFG{ // Function to convert binary to decimalstatic int binaryToDecimal(String n){ String num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num.charAt(i) == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIstatic String setStringtoASCII(String str){ // To store size of s int N = (str.length()); // If given String is not a // valid String if (N % 8 != 0) { return \"Not Possible!\"; } // To store final answer String res = \"\"; // Loop to iterate through String for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.substring(i, 8+i))); // Apprend the ASCII character // equivalent to current value res += (char)(decimal_value); } // Return Answer return res;} // Driver Codepublic static void main(String[] args){ String s = \"0110000101100010\"; System.out.print(setStringtoASCII(s)); }} // This code is contributed by 29AjayKumar",
"e": 3707,
"s": 2413,
"text": null
},
{
"code": "# python implementation for above approach # Function to convert binary to decimaldef binaryToDecimal(n): num = n # Stores the decimal value dec_value = 0 # Initializing base value to 1 base = 1 le = len(num) for i in range(le - 1, -1, -1): # If the current bit is 1 if (num[i] == '1'): dec_value += base base = base * 2 # Return answer return dec_value # Function to convert binary to ASCIIdef setStringtoASCII(str): # To store size of s N = int(len(str)) # If given string is not a # valid string if (N % 8 != 0): return \"Not Possible!\" # To store final answer res = \"\" # Loop to iterate through string for i in range(0, N, 8): decimal_value = binaryToDecimal(str[i: i + 8]) # Apprend the ASCII character # equivalent to current value res += chr(decimal_value) # Return Answer return res # Driver Codeif __name__ == \"__main__\": s = \"0110000101100010\" print(setStringtoASCII(s)) # This code is contributed by rakeshsahni",
"e": 4786,
"s": 3707,
"text": null
},
{
"code": "// C# implementation for above approachusing System; class GFG { // Function to convert binary to decimal static int binaryToDecimal(string n) { string num = n; // Stores the decimal value int dec_value = 0; // Initializing base value to 1 int base1 = 1; int len = num.Length; for (int i = len - 1; i >= 0; i--) { // If the current bit is 1 if (num[i] == '1') dec_value += base1; base1 = base1 * 2; } // Return answer return dec_value; } // Function to convert binary to ASCII static string setStringtoASCII(string str) { // To store size of s int N = (str.Length); // If given String is not a // valid String if (N % 8 != 0) { return \"Not Possible!\"; } // To store final answer string res = \"\"; // Loop to iterate through String for (int i = 0; i < N; i += 8) { int decimal_value = binaryToDecimal((str.Substring(i, 8))); // Apprend the ASCII character // equivalent to current value res += (char)(decimal_value); } // Return Answer return res; } // Driver Code public static void Main(string[] args) { string s = \"0110000101100010\"; Console.WriteLine(setStringtoASCII(s)); }} // This code is contributed by ukasp.",
"e": 6245,
"s": 4786,
"text": null
},
{
"code": "<script> // JavaScript implementation for above approach // Function to convert binary to decimalfunction binaryToDecimal(n){ let num = n; // Stores the decimal value let dec_value = 0; // Initializing base value to 1 let base = 1; let len = n.length; for(let i = len - 1; i >= 0; i--) { // If the current bit is 1 if (n[i] == '1') dec_value += base; base = base * 2; } // Return answer return dec_value;} // Function to convert binary to ASCIIfunction setStringtoASCII(str){ // To store size of s let N = str.length; // If given string is not a // valid string if (N % 8 != 0) { return \"Not Possible!\"; } // To store final answer let res = \"\"; // Loop to iterate through string for(let i = 0; i < N; i = i + 8) { let decimal_value = binaryToDecimal( (str.slice(i, i + 8))); // Apprend the ASCII character // equivalent to current value res = res + String.fromCharCode(decimal_value); } // Return Answer return res;} // Driver Codelet s = \"0110000101100010\";document.write(setStringtoASCII(s)); // This code is contributed by Potta Lokesh </script>",
"e": 7486,
"s": 6245,
"text": null
},
{
"code": null,
"e": 7489,
"s": 7486,
"text": "ab"
},
{
"code": null,
"e": 7606,
"s": 7489,
"text": "Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 7620,
"s": 7606,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 7632,
"s": 7620,
"text": "rakeshsahni"
},
{
"code": null,
"e": 7644,
"s": 7632,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7650,
"s": 7644,
"text": "ukasp"
},
{
"code": null,
"e": 7666,
"s": 7650,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 7672,
"s": 7666,
"text": "ASCII"
},
{
"code": null,
"e": 7686,
"s": 7672,
"text": "binary-string"
},
{
"code": null,
"e": 7696,
"s": 7686,
"text": "Bit Magic"
},
{
"code": null,
"e": 7715,
"s": 7696,
"text": "School Programming"
},
{
"code": null,
"e": 7725,
"s": 7715,
"text": "Searching"
},
{
"code": null,
"e": 7733,
"s": 7725,
"text": "Strings"
},
{
"code": null,
"e": 7743,
"s": 7733,
"text": "Searching"
},
{
"code": null,
"e": 7751,
"s": 7743,
"text": "Strings"
},
{
"code": null,
"e": 7761,
"s": 7751,
"text": "Bit Magic"
},
{
"code": null,
"e": 7859,
"s": 7761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7906,
"s": 7859,
"text": "Check if binary string multiple of 3 using DFA"
},
{
"code": null,
"e": 7933,
"s": 7906,
"text": "Check for Integer Overflow"
},
{
"code": null,
"e": 7973,
"s": 7933,
"text": "Maximum AND value of a pair in an array"
},
{
"code": null,
"e": 8016,
"s": 7973,
"text": "Detect if two integers have opposite signs"
},
{
"code": null,
"e": 8068,
"s": 8016,
"text": "Extract 'k' bits from a given position in a number."
},
{
"code": null,
"e": 8092,
"s": 8068,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 8110,
"s": 8092,
"text": "Python Dictionary"
},
{
"code": null,
"e": 8145,
"s": 8110,
"text": "Object Oriented Programming in C++"
},
{
"code": null,
"e": 8164,
"s": 8145,
"text": "Inheritance in C++"
}
] |
C# Example for MultiLevel Inheritance
|
Multilevel Inheritance occurs when a derived class is formed from another derived class.
Grandfather, father, and son are the perfect example to represent Multilevel Inheritance in C# β
The following is an example stating the usage of multilevel inheritance in C#.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class Son : Father {
public void DisplayTwo() {
Console.WriteLine("Son.. ");
}
static void Main(string[] args) {
Son s = new Son();
s.Display();
s.DisplayOne();
s.DisplayTwo();
Console.Read();
}
}
class Grandfather {
public void Display() {
Console.WriteLine("Grandfather...");
}
}
class Father : Grandfather {
public void DisplayOne() {
Console.WriteLine("Father...");
}
}
}
Grandfather...
Father...
Son..
|
[
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Multilevel Inheritance occurs when a derived class is formed from another derived class."
},
{
"code": null,
"e": 1248,
"s": 1151,
"text": "Grandfather, father, and son are the perfect example to represent Multilevel Inheritance in C# β"
},
{
"code": null,
"e": 1327,
"s": 1248,
"text": "The following is an example stating the usage of multilevel inheritance in C#."
},
{
"code": null,
"e": 1337,
"s": 1327,
"text": "Live Demo"
},
{
"code": null,
"e": 1954,
"s": 1337,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class Son : Father {\n public void DisplayTwo() {\n Console.WriteLine(\"Son.. \");\n }\n static void Main(string[] args) {\n Son s = new Son();\n s.Display();\n s.DisplayOne();\n s.DisplayTwo();\n Console.Read();\n }\n }\n class Grandfather {\n public void Display() {\n Console.WriteLine(\"Grandfather...\");\n }\n }\n class Father : Grandfather {\n public void DisplayOne() {\n Console.WriteLine(\"Father...\");\n }\n }\n}"
},
{
"code": null,
"e": 1986,
"s": 1954,
"text": "Grandfather...\nFather...\nSon.. "
}
] |
Smallest index in the given array that satisfies the given condition - GeeksforGeeks
|
04 Aug, 2021
Given an array arr[] of size N and an integer K, the task is to find the smallest index in the array such that:
floor(arr[i] / 1) + floor(arr[i + 1] / 2) + floor(arr[i + 2] / 2) + ..... + floor(arr[n β 1] / n β i ) β€ K
If no such index is found then print -1.
Examples:
Input: arr[] = {6, 5, 4, 2}, K = 8 Output: 1 (6 / 1) + (5 / 2) + (4 / 3) + (2 / 4) = 6 + 2 + 1 + 0 = 9 which is > K (5 / 1) + (4 / 2) + (2 / 3) = 5 + 2 + 0 = 7 < K Hence i = 1 is the required index.Input: arr[] = {5, 4, 2, 3, 9, 1, 8, 7}, K = 7 Output: 5
Approach: For every index i starting from 0, find the sum of the given series, and the first index which given a sum greater than or equal to K is our required index. If there is no such index then print -1.
Below is the implementation of the above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required indexint getIndex(int arr[], int n, int K){ // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1;} // Driver codeint main(){ int arr[] = { 6, 5, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 8; cout << getIndex(arr, n, K); return 0;}
// Java implementation of the approachclass GFG { // Function to return the required index static int getIndex(int arr[], int n, int K) { // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 6, 5, 4, 2 }; int n = arr.length; int K = 8; System.out.print(getIndex(arr, n, K)); }}
# Python3 implementation of the approachdef getIndex(array, k): n = len(array) for ind in range(n): sum = 0 div = 1 for item in array: sum += item//div div += 1 if sum > k: break if sum <= k: return ind return -1 # Driver codearr = [6, 5, 4, 2]K = 8print(getIndex(arr, K)) arr = [5, 4, 2, 3, 9, 1, 8, 7]K = 7print(getIndex(arr, K))
// C# implementation of the approachusing System; class GFG{ // Function to return the required index static int getIndex(int []arr, int n, int K) { // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } // Driver code static public void Main () { int []arr = { 6, 5, 4, 2 }; int n = arr.Length; int K = 8; Console.WriteLine(getIndex(arr, n, K)); }} // This Code is contributed by ajit.
<?php// PHP implementation of the approach // Function to return the required indexfunction getIndex($arr, $n, $K){ // Check all the indices, the first // index satisfying the condition is // the required index for ($i = 0; $i < $n; $i++) { // To store the sum of the series $sum = 0; // Denominator for the sum series $den = 1; // Find the sum of the series for ($j = $i; $j < $n; $j++) { $sum += floor($arr[$j] / $den); // Increment the denominator $den++; // If current sum is greater than K // no need to execute loop further if ($sum > $K) break; } // Found the first valid index if ($sum <= $K) return $i; } return -1;} // Driver code$arr = array( 6, 5, 4, 2 );$n = sizeof($arr);$K = 8; echo getIndex($arr, $n, $K); // This code is contributed by Ryuga?>
<script> // Javascript implementation of the approach // Function to return the required index function getIndex(arr, n, K) { // Check all the indices, the first index // satisfying the condition is // the required index for (let i = 0; i < n; i++) { // To store the sum of the series let sum = 0; // Denominator for the sum series let den = 1; // Find the sum of the series for (let j = i; j < n; j++) { sum += parseInt((arr[j] / den), 10); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } let arr = [ 6, 5, 4, 2 ]; let n = arr.length; let K = 8; document.write(getIndex(arr, n, K)); </script>
1
Time complexity: O(N2) Auxiliary space: O(1)
jit_t
ankthon
burlerosado
divyesh072019
kk9826225
Arrays
Competitive Programming
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Top 10 Algorithms and Data Structures for Competitive Programming
|
[
{
"code": null,
"e": 25258,
"s": 25230,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 25371,
"s": 25258,
"text": "Given an array arr[] of size N and an integer K, the task is to find the smallest index in the array such that: "
},
{
"code": null,
"e": 25478,
"s": 25371,
"text": "floor(arr[i] / 1) + floor(arr[i + 1] / 2) + floor(arr[i + 2] / 2) + ..... + floor(arr[n β 1] / n β i ) β€ K"
},
{
"code": null,
"e": 25519,
"s": 25478,
"text": "If no such index is found then print -1."
},
{
"code": null,
"e": 25531,
"s": 25519,
"text": "Examples: "
},
{
"code": null,
"e": 25786,
"s": 25531,
"text": "Input: arr[] = {6, 5, 4, 2}, K = 8 Output: 1 (6 / 1) + (5 / 2) + (4 / 3) + (2 / 4) = 6 + 2 + 1 + 0 = 9 which is > K (5 / 1) + (4 / 2) + (2 / 3) = 5 + 2 + 0 = 7 < K Hence i = 1 is the required index.Input: arr[] = {5, 4, 2, 3, 9, 1, 8, 7}, K = 7 Output: 5"
},
{
"code": null,
"e": 25994,
"s": 25786,
"text": "Approach: For every index i starting from 0, find the sum of the given series, and the first index which given a sum greater than or equal to K is our required index. If there is no such index then print -1."
},
{
"code": null,
"e": 26046,
"s": 25994,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26050,
"s": 26046,
"text": "C++"
},
{
"code": null,
"e": 26055,
"s": 26050,
"text": "Java"
},
{
"code": null,
"e": 26062,
"s": 26055,
"text": "Python"
},
{
"code": null,
"e": 26065,
"s": 26062,
"text": "C#"
},
{
"code": null,
"e": 26069,
"s": 26065,
"text": "PHP"
},
{
"code": null,
"e": 26080,
"s": 26069,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the required indexint getIndex(int arr[], int n, int K){ // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1;} // Driver codeint main(){ int arr[] = { 6, 5, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int K = 8; cout << getIndex(arr, n, K); return 0;}",
"e": 27092,
"s": 26080,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the required index static int getIndex(int arr[], int n, int K) { // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } // Driver code public static void main(String[] args) { int arr[] = { 6, 5, 4, 2 }; int n = arr.length; int K = 8; System.out.print(getIndex(arr, n, K)); }}",
"e": 28225,
"s": 27092,
"text": null
},
{
"code": "# Python3 implementation of the approachdef getIndex(array, k): n = len(array) for ind in range(n): sum = 0 div = 1 for item in array: sum += item//div div += 1 if sum > k: break if sum <= k: return ind return -1 # Driver codearr = [6, 5, 4, 2]K = 8print(getIndex(arr, K)) arr = [5, 4, 2, 3, 9, 1, 8, 7]K = 7print(getIndex(arr, K))",
"e": 28605,
"s": 28225,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the required index static int getIndex(int []arr, int n, int K) { // Check all the indices, the first index // satisfying the condition is // the required index for (int i = 0; i < n; i++) { // To store the sum of the series int sum = 0; // Denominator for the sum series int den = 1; // Find the sum of the series for (int j = i; j < n; j++) { sum += (arr[j] / den); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } // Driver code static public void Main () { int []arr = { 6, 5, 4, 2 }; int n = arr.Length; int K = 8; Console.WriteLine(getIndex(arr, n, K)); }} // This Code is contributed by ajit. ",
"e": 29806,
"s": 28605,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the required indexfunction getIndex($arr, $n, $K){ // Check all the indices, the first // index satisfying the condition is // the required index for ($i = 0; $i < $n; $i++) { // To store the sum of the series $sum = 0; // Denominator for the sum series $den = 1; // Find the sum of the series for ($j = $i; $j < $n; $j++) { $sum += floor($arr[$j] / $den); // Increment the denominator $den++; // If current sum is greater than K // no need to execute loop further if ($sum > $K) break; } // Found the first valid index if ($sum <= $K) return $i; } return -1;} // Driver code$arr = array( 6, 5, 4, 2 );$n = sizeof($arr);$K = 8; echo getIndex($arr, $n, $K); // This code is contributed by Ryuga?>",
"e": 30771,
"s": 29806,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the required index function getIndex(arr, n, K) { // Check all the indices, the first index // satisfying the condition is // the required index for (let i = 0; i < n; i++) { // To store the sum of the series let sum = 0; // Denominator for the sum series let den = 1; // Find the sum of the series for (let j = i; j < n; j++) { sum += parseInt((arr[j] / den), 10); // Increment the denominator den++; // If current sum is greater than K // no need to execute loop further if (sum > K) break; } // Found the first valid index if (sum <= K) return i; } return -1; } let arr = [ 6, 5, 4, 2 ]; let n = arr.length; let K = 8; document.write(getIndex(arr, n, K)); </script>",
"e": 31874,
"s": 30771,
"text": null
},
{
"code": null,
"e": 31876,
"s": 31874,
"text": "1"
},
{
"code": null,
"e": 31924,
"s": 31878,
"text": "Time complexity: O(N2) Auxiliary space: O(1) "
},
{
"code": null,
"e": 31930,
"s": 31924,
"text": "jit_t"
},
{
"code": null,
"e": 31938,
"s": 31930,
"text": "ankthon"
},
{
"code": null,
"e": 31950,
"s": 31938,
"text": "burlerosado"
},
{
"code": null,
"e": 31964,
"s": 31950,
"text": "divyesh072019"
},
{
"code": null,
"e": 31974,
"s": 31964,
"text": "kk9826225"
},
{
"code": null,
"e": 31981,
"s": 31974,
"text": "Arrays"
},
{
"code": null,
"e": 32005,
"s": 31981,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32018,
"s": 32005,
"text": "Mathematical"
},
{
"code": null,
"e": 32025,
"s": 32018,
"text": "Arrays"
},
{
"code": null,
"e": 32038,
"s": 32025,
"text": "Mathematical"
},
{
"code": null,
"e": 32136,
"s": 32038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32145,
"s": 32136,
"text": "Comments"
},
{
"code": null,
"e": 32158,
"s": 32145,
"text": "Old Comments"
},
{
"code": null,
"e": 32181,
"s": 32158,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 32213,
"s": 32181,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32281,
"s": 32213,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32326,
"s": 32281,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 32380,
"s": 32326,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 32423,
"s": 32380,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32464,
"s": 32423,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32507,
"s": 32464,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32534,
"s": 32507,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Print all odd nodes of Binary Search Tree
|
07 Feb, 2022
Given a binary search tree. The task is to print all odd nodes of the binary search tree.Examples:
Input :
5
/ \
3 7
/ \ / \
2 4 6 8
Output : 3 5 7
Input :
14
/ \
12 17
/ \ / \
8 13 16 19
Output : 13 17 19
Approach: Traverse the Binary Search tree using any of the tree traversals and check if current nodeβs value is odd. If yes then print it otherwise skip that node.Below is the implementation of the above Approach:
C++
Java
Python3
C#
Javascript
// C++ program to print all odd node of BST#include <bits/stdc++.h>using namespace std; // create Treestruct Node { int key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); printf("%d ", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesvoid oddNode(Node* root){ if (root != NULL) { oddNode(root->left); // if node is odd then print it if (root->key % 2 != 0) printf("%d ", root->key); oddNode(root->right); }} // Driver Codeint main(){ /* Let us create following BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ Node* root = NULL; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); return 0;}
// Java program to print all odd node of BSTclass GfG { // create Treestatic class Node { int key; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print(root.key + " "); inorder(root.right); }} /* A utility function to insert a new nodewith given key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesstatic void oddNode(Node root){ if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) System.out.print(root.key + " "); oddNode(root.right); }} // Driver Codepublic static void main(String[] args){ /* Let us create following BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ Node root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); }}
# Python3 program to print all odd# node of BST # create Tree# to create a new BST nodeclass newNode: # Construct to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do inorder# traversal of BSTdef inorder( root) : if (root != None): inorder(root.left) print(root.key, end = " ") inorder(root.right) """ A utility function to insert anew node with given key in BST """def insert(node, key): """ If the tree is empty, return a new node """ if (node == None): return newNode(key) """ Otherwise, recur down the tree """ if (key < node.key): node.left = insert(node.left, key) else: node.right = insert(node.right, key) """ return the (unchanged) node pointer """ return node # Function to print all even nodesdef oddNode(root) : if (root != None): oddNode(root.left) # if node is even then print it if (root.key % 2 != 0): print(root.key, end = " ") oddNode(root.right) # Driver Codeif __name__ == '__main__': """ Let us create following BST 5 / \ 3 7 / \ / \ 2 4 6 8 """ root = None root = insert(root, 5) root = insert(root, 3) root = insert(root, 2) root = insert(root, 4) root = insert(root, 7) root = insert(root, 6) root = insert(root, 8) oddNode(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to print all odd node of BSTusing System; public class GfG{ // create Treeclass Node{ public int key; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp;} // A utility function to do// inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + " "); inorder(root.right); }} /* A utility function to insert a new nodewith given key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesstatic void oddNode(Node root){ if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) Console.Write(root.key + " "); oddNode(root.right); }} // Driver Codepublic static void Main(String[] args){ /* Let us create following BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ Node root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); }} // This code has been contributed// by PrinciRaj1992
<script>// javascript program to print all odd node of BST // create Tree class Node { constructor(){ this.key = 0; this.left = this.right = null; } } // A utility function to create a new BST node function newNode(item) { var temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp; } // A utility function to do inorder traversal of BST function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + " "); inorder(root.right); } } /* * A utility function to insert a new node with given key in BST */ function insert(node, key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } // Function to print all odd nodes function oddNode(root) { if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) document.write(root.key + " "); oddNode(root.right); } } // Driver Code /* * Let us create following BST 5 / \ 3 7 / \ / \ 2 4 6 8 */ var root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); // This code is contributed by Rajput-Ji</script>
3 5 7
Time Complexity : O(n) where n is no. of nodes in the binary search tree.Auxiliary Space: O(n)
prerna saini
VishalBachchas
princiraj1992
SHUBHAMSINGH10
nidhi_biet
pankajsharmagfg
Rajput-Ji
sweetyty
Technical Scripter 2018
Binary Search Tree
Data Structures
Technical Scripter
Data Structures
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Feb, 2022"
},
{
"code": null,
"e": 155,
"s": 54,
"text": "Given a binary search tree. The task is to print all odd nodes of the binary search tree.Examples: "
},
{
"code": null,
"e": 368,
"s": 155,
"text": "Input : \n 5 \n / \\ \n 3 7 \n / \\ / \\ \n 2 4 6 8 \nOutput : 3 5 7\n\nInput :\n 14 \n / \\ \n 12 17 \n / \\ / \\ \n 8 13 16 19 \nOutput : 13 17 19"
},
{
"code": null,
"e": 584,
"s": 368,
"text": "Approach: Traverse the Binary Search tree using any of the tree traversals and check if current nodeβs value is odd. If yes then print it otherwise skip that node.Below is the implementation of the above Approach: "
},
{
"code": null,
"e": 588,
"s": 584,
"text": "C++"
},
{
"code": null,
"e": 593,
"s": 588,
"text": "Java"
},
{
"code": null,
"e": 601,
"s": 593,
"text": "Python3"
},
{
"code": null,
"e": 604,
"s": 601,
"text": "C#"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Javascript"
},
{
"code": "// C++ program to print all odd node of BST#include <bits/stdc++.h>using namespace std; // create Treestruct Node { int key; struct Node *left, *right;}; // A utility function to create a new BST nodeNode* newNode(int item){ Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A utility function to do inorder traversal of BSTvoid inorder(Node* root){ if (root != NULL) { inorder(root->left); printf(\"%d \", root->key); inorder(root->right); }} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesvoid oddNode(Node* root){ if (root != NULL) { oddNode(root->left); // if node is odd then print it if (root->key % 2 != 0) printf(\"%d \", root->key); oddNode(root->right); }} // Driver Codeint main(){ /* Let us create following BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ Node* root = NULL; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); return 0;}",
"e": 2195,
"s": 615,
"text": null
},
{
"code": "// Java program to print all odd node of BSTclass GfG { // create Treestatic class Node { int key; Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp;} // A utility function to do inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); System.out.print(root.key + \" \"); inorder(root.right); }} /* A utility function to insert a new nodewith given key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesstatic void oddNode(Node root){ if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) System.out.print(root.key + \" \"); oddNode(root.right); }} // Driver Codepublic static void main(String[] args){ /* Let us create following BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ Node root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); }}",
"e": 3773,
"s": 2195,
"text": null
},
{
"code": "# Python3 program to print all odd# node of BST # create Tree# to create a new BST nodeclass newNode: # Construct to create a new node def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to do inorder# traversal of BSTdef inorder( root) : if (root != None): inorder(root.left) print(root.key, end = \" \") inorder(root.right) \"\"\" A utility function to insert anew node with given key in BST \"\"\"def insert(node, key): \"\"\" If the tree is empty, return a new node \"\"\" if (node == None): return newNode(key) \"\"\" Otherwise, recur down the tree \"\"\" if (key < node.key): node.left = insert(node.left, key) else: node.right = insert(node.right, key) \"\"\" return the (unchanged) node pointer \"\"\" return node # Function to print all even nodesdef oddNode(root) : if (root != None): oddNode(root.left) # if node is even then print it if (root.key % 2 != 0): print(root.key, end = \" \") oddNode(root.right) # Driver Codeif __name__ == '__main__': \"\"\" Let us create following BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 \"\"\" root = None root = insert(root, 5) root = insert(root, 3) root = insert(root, 2) root = insert(root, 4) root = insert(root, 7) root = insert(root, 6) root = insert(root, 8) oddNode(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 5266,
"s": 3773,
"text": null
},
{
"code": "// C# program to print all odd node of BSTusing System; public class GfG{ // create Treeclass Node{ public int key; public Node left, right;} // A utility function to create a new BST nodestatic Node newNode(int item){ Node temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp;} // A utility function to do// inorder traversal of BSTstatic void inorder(Node root){ if (root != null) { inorder(root.left); Console.Write(root.key + \" \"); inorder(root.right); }} /* A utility function to insert a new nodewith given key in BST */static Node insert(Node node, int key){ /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node;} // Function to print all odd nodesstatic void oddNode(Node root){ if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) Console.Write(root.key + \" \"); oddNode(root.right); }} // Driver Codepublic static void Main(String[] args){ /* Let us create following BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ Node root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); }} // This code has been contributed// by PrinciRaj1992",
"e": 6923,
"s": 5266,
"text": null
},
{
"code": "<script>// javascript program to print all odd node of BST // create Tree class Node { constructor(){ this.key = 0; this.left = this.right = null; } } // A utility function to create a new BST node function newNode(item) { var temp = new Node(); temp.key = item; temp.left = null; temp.right = null; return temp; } // A utility function to do inorder traversal of BST function inorder(root) { if (root != null) { inorder(root.left); document.write(root.key + \" \"); inorder(root.right); } } /* * A utility function to insert a new node with given key in BST */ function insert(node, key) { /* If the tree is empty, return a new node */ if (node == null) return newNode(key); /* Otherwise, recur down the tree */ if (key < node.key) node.left = insert(node.left, key); else node.right = insert(node.right, key); /* return the (unchanged) node pointer */ return node; } // Function to print all odd nodes function oddNode(root) { if (root != null) { oddNode(root.left); // if node is odd then print it if (root.key % 2 != 0) document.write(root.key + \" \"); oddNode(root.right); } } // Driver Code /* * Let us create following BST 5 / \\ 3 7 / \\ / \\ 2 4 6 8 */ var root = null; root = insert(root, 5); root = insert(root, 3); root = insert(root, 2); root = insert(root, 4); root = insert(root, 7); root = insert(root, 6); root = insert(root, 8); oddNode(root); // This code is contributed by Rajput-Ji</script>",
"e": 8772,
"s": 6923,
"text": null
},
{
"code": null,
"e": 8778,
"s": 8772,
"text": "3 5 7"
},
{
"code": null,
"e": 8876,
"s": 8780,
"text": "Time Complexity : O(n) where n is no. of nodes in the binary search tree.Auxiliary Space: O(n) "
},
{
"code": null,
"e": 8889,
"s": 8876,
"text": "prerna saini"
},
{
"code": null,
"e": 8904,
"s": 8889,
"text": "VishalBachchas"
},
{
"code": null,
"e": 8918,
"s": 8904,
"text": "princiraj1992"
},
{
"code": null,
"e": 8933,
"s": 8918,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8944,
"s": 8933,
"text": "nidhi_biet"
},
{
"code": null,
"e": 8960,
"s": 8944,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8970,
"s": 8960,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8979,
"s": 8970,
"text": "sweetyty"
},
{
"code": null,
"e": 9003,
"s": 8979,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 9022,
"s": 9003,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 9038,
"s": 9022,
"text": "Data Structures"
},
{
"code": null,
"e": 9057,
"s": 9038,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9073,
"s": 9057,
"text": "Data Structures"
},
{
"code": null,
"e": 9092,
"s": 9073,
"text": "Binary Search Tree"
}
] |
Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
|
23 Jun, 2022
Given a binary string of 0s and 1s. The task is to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string. That is maximize ( number of 0s β number of 1s ) for any sub-string in the given binary string.
Examples:
Input : S = "11000010001"
Output : 6
From index 2 to index 9, there are 7
0s and 1 1s, so number of 0s - number
of 1s is 6.
Input : S = "1111"
Output : -1
We have discussed Dynamic Programming approach in below post :
Maximum difference of zeros and ones in binary string | Set 1. In the post we seen an efficient method that work in O(n) time and in O(1) extra space. Idea behind that if we convert all zeros into 1 and all ones into -1.now our problem reduces to find out the maximum sum sub_array Using Kadaneβs Algorithm.
Input : S = "11000010001"
After converting '0' into 1 and
'1' into -1 our S Look Like
S = -1 -1 1 1 1 1 -1 1 1 1 -1
Now we have to find out Maximum Sum sub_array
that is : 6 is that case
Output : 6
Below is the implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the length of// substring with maximum difference of// zeros and ones in binary string.#include <iostream>using namespace std; // Returns the length of substring with// maximum difference of zeroes and ones// in binary stringint findLength(string str, int n){ int current_sum = 0; int max_sum = 0; // traverse a binary string from left // to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) current_sum = 0; // update maximum sum max_sum = max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means all ones // otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driven Programint main(){ string s = "11000010001"; int n = 11; cout << findLength(s, n) << endl; return 0;}
// Java Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.import java.util.*;import java.lang.*;import java.io.*; class GFG { // Find the length of substring with maximum // difference of zeros and ones in binary // string public static int findLength(String str, int n) { int current_sum = 0; int max_sum = 0; // traverse a binary string from left to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str.charAt(i) == '0' ? 1 : -1); if (current_sum < 0) current_sum = 0; // update maximum sum max_sum = Math.max(current_sum, max_sum); } // return -1 if string does not contain any zero // that means string contains all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum; } public static void main(String[] args) { String str = "11000010001"; int n = str.length(); System.out.println(findLength(str, n)); }}
# Python Program to find the length of# substring with maximum difference of# zeros and ones in binary string. # Returns the length of substring with# maximum difference of zeroes and ones# in binary stringdef findLength(string, n): current_sum = 0 max_sum = 0 # traverse a binary string from left # to right for i in range(n): # add current value to the current_sum # according to the Character # if it's '0' add 1 else -1 current_sum += (1 if string[i] == '0' else -1) if current_sum < 0: current_sum = 0 # update maximum sum max_sum = max(current_sum, max_sum) # return -1 if string does not contain # any zero that means all ones # otherwise max_sum return max_sum if max_sum else 0 # Driven Programs = "11000010001"n = 11print(findLength(s, n)) # This code is contributed by Ansu Kumari.
// C# Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.using System; class GFG{ // Find the length of substring with// maximum difference of zeros and// ones in binary stringpublic static int findLength(string str, int n){ int current_sum = 0; int max_sum = 0; // traverse a binary string // from left to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) { current_sum = 0; } // update maximum sum max_sum = Math.Max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means string contains // all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driver Codepublic static void Main(string[] args){ string str = "11000010001"; int n = str.Length; Console.WriteLine(findLength(str, n));}} // This code is contributed by Shrikant13
<?php// PHP Program to find the length of// substring with maximum difference of// zeros and ones in binary string. // Returns the length of substring with// maximum difference of zeroes and ones// in binary stringfunction findLength($str, $n){ $current_sum = 0; $max_sum = 0; // traverse a binary string // from left to right for ($i = 0; $i < $n; $i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 $current_sum += ($str[$i] == '0' ? 1 : -1); if ($current_sum < 0) $current_sum = 0; // update maximum sum $max_sum = max($current_sum, $max_sum); } // return -1 if string does not contain // any zero that means all ones // otherwise max_sum return $max_sum == 0 ? -1 : $max_sum;} // Driver Code $s = "11000010001"; $n = 11; echo findLength($s, $n),"\n"; // This code is contributed by aj_36?>
<script> // JavaScript program to find the length of// substring with maximum difference of// zeroes and ones in binary string. // Find the length of substring with// maximum difference of zeros and// ones in binary stringfunction findLength(str, n){ let current_sum = 0; let max_sum = 0; // traverse a binary string // from left to right for (let i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) { current_sum = 0; } // update maximum sum max_sum = Math.max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means string contains // all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driver Code let str = "11000010001"; let n = str.length; document.write(findLength(str, n)); // This code is contributed by chinmoy1997pal.</script>
Output:
6
Time Complexity: O(n) Space complexity: O(n), since string gets copied when we pass it to a function.
jit_t
Sagar Pant 1
shrikanth13
chinmoy1997pal
sweetyty
anikaseth98
anikakapoor
rohitmishra051000
binary-string
Dynamic Programming
Strings
Strings
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Sieve of Eratosthenes
BellmanβFord Algorithm | DP-23
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 318,
"s": 54,
"text": "Given a binary string of 0s and 1s. The task is to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string. That is maximize ( number of 0s β number of 1s ) for any sub-string in the given binary string. "
},
{
"code": null,
"e": 329,
"s": 318,
"text": "Examples: "
},
{
"code": null,
"e": 485,
"s": 329,
"text": "Input : S = \"11000010001\"\nOutput : 6\nFrom index 2 to index 9, there are 7\n0s and 1 1s, so number of 0s - number\nof 1s is 6.\n\nInput : S = \"1111\"\nOutput : -1"
},
{
"code": null,
"e": 549,
"s": 485,
"text": "We have discussed Dynamic Programming approach in below post : "
},
{
"code": null,
"e": 858,
"s": 549,
"text": "Maximum difference of zeros and ones in binary string | Set 1. In the post we seen an efficient method that work in O(n) time and in O(1) extra space. Idea behind that if we convert all zeros into 1 and all ones into -1.now our problem reduces to find out the maximum sum sub_array Using Kadaneβs Algorithm. "
},
{
"code": null,
"e": 1083,
"s": 858,
"text": "Input : S = \"11000010001\"\n After converting '0' into 1 and\n '1' into -1 our S Look Like\n S = -1 -1 1 1 1 1 -1 1 1 1 -1\n Now we have to find out Maximum Sum sub_array \n that is : 6 is that case \n \nOutput : 6"
},
{
"code": null,
"e": 1128,
"s": 1083,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 1132,
"s": 1128,
"text": "C++"
},
{
"code": null,
"e": 1137,
"s": 1132,
"text": "Java"
},
{
"code": null,
"e": 1145,
"s": 1137,
"text": "Python3"
},
{
"code": null,
"e": 1148,
"s": 1145,
"text": "C#"
},
{
"code": null,
"e": 1152,
"s": 1148,
"text": "PHP"
},
{
"code": null,
"e": 1163,
"s": 1152,
"text": "Javascript"
},
{
"code": "// CPP Program to find the length of// substring with maximum difference of// zeros and ones in binary string.#include <iostream>using namespace std; // Returns the length of substring with// maximum difference of zeroes and ones// in binary stringint findLength(string str, int n){ int current_sum = 0; int max_sum = 0; // traverse a binary string from left // to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) current_sum = 0; // update maximum sum max_sum = max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means all ones // otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driven Programint main(){ string s = \"11000010001\"; int n = 11; cout << findLength(s, n) << endl; return 0;}",
"e": 2152,
"s": 1163,
"text": null
},
{
"code": "// Java Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.import java.util.*;import java.lang.*;import java.io.*; class GFG { // Find the length of substring with maximum // difference of zeros and ones in binary // string public static int findLength(String str, int n) { int current_sum = 0; int max_sum = 0; // traverse a binary string from left to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str.charAt(i) == '0' ? 1 : -1); if (current_sum < 0) current_sum = 0; // update maximum sum max_sum = Math.max(current_sum, max_sum); } // return -1 if string does not contain any zero // that means string contains all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum; } public static void main(String[] args) { String str = \"11000010001\"; int n = str.length(); System.out.println(findLength(str, n)); }}",
"e": 3327,
"s": 2152,
"text": null
},
{
"code": "# Python Program to find the length of# substring with maximum difference of# zeros and ones in binary string. # Returns the length of substring with# maximum difference of zeroes and ones# in binary stringdef findLength(string, n): current_sum = 0 max_sum = 0 # traverse a binary string from left # to right for i in range(n): # add current value to the current_sum # according to the Character # if it's '0' add 1 else -1 current_sum += (1 if string[i] == '0' else -1) if current_sum < 0: current_sum = 0 # update maximum sum max_sum = max(current_sum, max_sum) # return -1 if string does not contain # any zero that means all ones # otherwise max_sum return max_sum if max_sum else 0 # Driven Programs = \"11000010001\"n = 11print(findLength(s, n)) # This code is contributed by Ansu Kumari.",
"e": 4212,
"s": 3327,
"text": null
},
{
"code": "// C# Program to find the length of// substring with maximum difference of// zeroes and ones in binary string.using System; class GFG{ // Find the length of substring with// maximum difference of zeros and// ones in binary stringpublic static int findLength(string str, int n){ int current_sum = 0; int max_sum = 0; // traverse a binary string // from left to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) { current_sum = 0; } // update maximum sum max_sum = Math.Max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means string contains // all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driver Codepublic static void Main(string[] args){ string str = \"11000010001\"; int n = str.Length; Console.WriteLine(findLength(str, n));}} // This code is contributed by Shrikant13",
"e": 5337,
"s": 4212,
"text": null
},
{
"code": "<?php// PHP Program to find the length of// substring with maximum difference of// zeros and ones in binary string. // Returns the length of substring with// maximum difference of zeroes and ones// in binary stringfunction findLength($str, $n){ $current_sum = 0; $max_sum = 0; // traverse a binary string // from left to right for ($i = 0; $i < $n; $i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 $current_sum += ($str[$i] == '0' ? 1 : -1); if ($current_sum < 0) $current_sum = 0; // update maximum sum $max_sum = max($current_sum, $max_sum); } // return -1 if string does not contain // any zero that means all ones // otherwise max_sum return $max_sum == 0 ? -1 : $max_sum;} // Driver Code $s = \"11000010001\"; $n = 11; echo findLength($s, $n),\"\\n\"; // This code is contributed by aj_36?>",
"e": 6301,
"s": 5337,
"text": null
},
{
"code": "<script> // JavaScript program to find the length of// substring with maximum difference of// zeroes and ones in binary string. // Find the length of substring with// maximum difference of zeros and// ones in binary stringfunction findLength(str, n){ let current_sum = 0; let max_sum = 0; // traverse a binary string // from left to right for (let i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) { current_sum = 0; } // update maximum sum max_sum = Math.max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means string contains // all ones otherwise max_sum return max_sum == 0 ? -1 : max_sum;} // Driver Code let str = \"11000010001\"; let n = str.length; document.write(findLength(str, n)); // This code is contributed by chinmoy1997pal.</script>",
"e": 7363,
"s": 6301,
"text": null
},
{
"code": null,
"e": 7372,
"s": 7363,
"text": "Output: "
},
{
"code": null,
"e": 7375,
"s": 7372,
"text": "6 "
},
{
"code": null,
"e": 7478,
"s": 7375,
"text": "Time Complexity: O(n) Space complexity: O(n), since string gets copied when we pass it to a function. "
},
{
"code": null,
"e": 7484,
"s": 7478,
"text": "jit_t"
},
{
"code": null,
"e": 7497,
"s": 7484,
"text": "Sagar Pant 1"
},
{
"code": null,
"e": 7509,
"s": 7497,
"text": "shrikanth13"
},
{
"code": null,
"e": 7524,
"s": 7509,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 7533,
"s": 7524,
"text": "sweetyty"
},
{
"code": null,
"e": 7545,
"s": 7533,
"text": "anikaseth98"
},
{
"code": null,
"e": 7557,
"s": 7545,
"text": "anikakapoor"
},
{
"code": null,
"e": 7575,
"s": 7557,
"text": "rohitmishra051000"
},
{
"code": null,
"e": 7589,
"s": 7575,
"text": "binary-string"
},
{
"code": null,
"e": 7609,
"s": 7589,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 7617,
"s": 7609,
"text": "Strings"
},
{
"code": null,
"e": 7625,
"s": 7617,
"text": "Strings"
},
{
"code": null,
"e": 7645,
"s": 7625,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 7743,
"s": 7645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7781,
"s": 7743,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 7814,
"s": 7781,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 7836,
"s": 7814,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 7867,
"s": 7836,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 7935,
"s": 7867,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 7981,
"s": 7935,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8006,
"s": 7981,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8066,
"s": 8006,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8081,
"s": 8066,
"text": "C++ Data Types"
}
] |
Given a number, find the next smallest palindrome
|
21 Jun, 2022
Given a number, find the next smallest palindrome larger than this number. For example, if the input number is β2 3 5 4 5β, the output should be β2 3 6 3 2β. And if the input number is β9 9 9β, the output should be β1 0 0 1β. The input is assumed to be an array. Every entry in array represents a digit in input number. Let the array be βnum[]β and size of array be βnβ
There can be three different types of inputs that need to be handled separately. 1) The input number is palindrome and has all 9s. For example β9 9 9β. Output should be β1 0 0 1β 2) The input number is not palindrome. For example β1 2 3 4β. Output should be β1 3 3 1β 3) The input number is palindrome and doesnβt have all 9s. For example β1 2 2 1β. Output should be β1 3 3 1β.
Solution for input type 1 is easy. The output contains n + 1 digits where the corner digits are 1, and all digits between corner digits are 0.Now let us first talk about input type 2 and 3. How to convert a given number to a greater palindrome? To understand the solution, let us first define the following two terms:
Left Side: The left half of given number. Left side of β1 2 3 4 5 6β is β1 2 3β and left side of β1 2 3 4 5β is β1 2β
Right Side: The right half of given number. Right side of β1 2 3 4 5 6β is β4 5 6β and right side of β1 2 3 4 5β is β4 5β
To convert to palindrome, we can either take the mirror of its left side or take mirror of its right side. However, if we take the mirror of the right side, then the palindrome so formed is not guaranteed to be next larger palindrome. So, we must take the mirror of left side and copy it to right side. But there are some cases that must be handled in different ways. See the following steps.We will start with two indices i and j. i pointing to the two middle elements (or pointing to two elements around the middle element in case of n being odd). We one by one move i and j away from each other.
Step 1. Initially, ignore the part of left side which is same as the corresponding part of right side. For example, if the number is β8 3 4 2 2 4 6 9β²β², we ignore the middle four elements. i now points to element 3 and j now points to element 6.
Step 2. After step 1, following cases arise:Case 1: Indices i & j cross the boundary. This case occurs when the input number is palindrome. In this case, we just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side. For example, if the given number is β1 2 9 2 1β, we increment 9 to 10 and propagate the carry. So the number becomes β1 3 0 3 1β
Case 2: There are digits left between left side and right side which are not same. So, we just mirror the left side to the right side & try to minimize the number formed to guarantee the next smallest palindrome. In this case, there can be two sub-cases.
2.1) Copying the left side to the right side is sufficient, we donβt need to increment any digits and the result is just mirror of left side. Following are some examples of this sub-case. Next palindrome for β7 8 3 3 2 2β²β² is β7 8 3 3 8 7β Next palindrome for β1 2 5 3 2 2β²β² is β1 2 5 5 2 1β Next palindrome for β1 4 5 8 7 6 7 8 3 2 2β²β² is β1 4 5 8 7 6 7 8 5 4 1β How do we check for this sub-case? All we need to check is the digit just after the ignored part in step 1. This digit is highlighted in above examples. If this digit is greater than the corresponding digit in right side digit, then copying the left side to the right side is sufficient and we donβt need to do anything else.
2.2) Copying the left side to the right side is NOT sufficient. This happens when the above defined digit of left side is smaller. Following are some examples of this case. Next palindrome for β7 1 3 3 2 2β²β² is β7 1 4 4 1 7β Next palindrome for β1 2 3 4 6 2 8β²β² is β1 2 3 5 3 2 1β Next palindrome for β9 4 1 8 7 9 7 8 3 2 2β²β² is β9 4 1 8 8 0 8 8 1 4 9β We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side.
Approach 1: Basic Approach for Finding the next smallest Palindrome Number.
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;// Function to check whether number is palindrome or notint isPalindrome(int num){ // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store in // rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; }}int main(){ // Take any number to find its next palindrome number int num = 9687; // If number is not Palindrome we go to the next number // using while loop while (!isPalindrome(num)) { num = num + 1; } // now we get the next Palindrome so let's print it cout << "Next Palindrome :"; cout << num; return 0;}// Contribute by :- Tejas Bhavsar
import java.io.*; class GFG{ // Function to check whether number is palindrome or not static int isPalindrome(int num) { // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver code public static void main(String[] args) { // Take any number to find its next palindrome // number int num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it System.out.print("Next Palindrome :"); System.out.print(num); }} // This code is contributed by subhammahato348.
# Program to print find next palindrome# number greater than given number. # function to check a number is# palindrome or notdef isPalindrome(num): # Declaring variables # storing num in n so that we can compare it later n = num rev = 0 # while num is not 0 we find its reverse and store # in rev while (num > 0): k = num % 10 rev = (rev * 10) + k num = num // 10 # check if num and its reverse are same if (n == rev): return True else: return False # input numbernum = 9687 # start check from next num;num = num + 1 # Loop checks all numbers from given no.# (num + 1) to next palindrome no.while (True): if (isPalindrome(num)): break num = num + 1 # printing the next palindromeprint("Next Palindrome :")print(num) # This code is contributed by sidharthsingh7898.
using System;class GFG { // Function to check whether number is palindrome or not static int isPalindrome(int num) { // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver code public static void Main() { // Take any number to find its next palindrome // number int num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it Console.Write("Next Palindrome :"); Console.Write(num); }} // This code is contributed by subhammahato348.
<script> // Javascript program for the above approach // Function to check whether number is palindrome or not function isPalindrome(num) { // Declaring variables let n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = Math.floor(num / 10); } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver Code // Take any number to find its next palindrome // number let num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it document.write("Next Palindrome :"); document.write(num); // This code is contributed by splevel62.</script>
Next Palindrome :9779
Time Complexity: O(num * |num|)
Space Complexity: O(1)
C++
C
Java
Python3
C#
PHP
Javascript
#include <iostream>using namespace std; // Utility that prints out an array on a linevoid printArray(int arr[], int n){ int i; for(i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // A utility function to check if num has all 9sint AreAll9s(int* num, int n ){ int i; for(i = 0; i < n; ++i) if (num[i] != 9) return 0; return 1;} // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){ // Find the index of mid digit int mid = n / 2; // A bool variable to check if copy of left // side to right is sufficient or not bool leftsmaller = false; // End of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2) ? mid + 1 : mid; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) i--, j++; // Find if the middle digit(s) need to be // incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) leftsmaller = true; // Copy the mirror of left to tight while (i >= 0) { num[j] = num[i]; j++; i--; } // Handle the case where middle digit(s) must // be incremented. This part of code is for // CASE 1 and CASE 2.2 if (leftsmaller == true) { int carry = 1; i = mid - 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += carry; carry = num[mid] / 10; num[mid] %= 10; j = mid + 1; } else j = mid; // Add 1 to the rightmost digit of the // left side, propagate the carry towards // MSB digit and simultaneously copying // mirror of the left side to the right side. while (i >= 0) { num[i] += carry; carry = num[i] / 10; num[i] %= 10; // Copy mirror to right num[j++] = num[i--]; } }} // The function that prints next palindrome// of a given number num[] with n digits.void generateNextPalindrome(int num[], int n){ int i; printf("Next palindrome is:"); // Input type 1: All the digits are 9, simply o/p 1 // followed by n-1 0's followed by 1. if (AreAll9s(num, n)) { printf("1 "); for(i = 1; i < n; i++) printf("0 "); printf("1"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); // print the result printArray (num, n); }} // Driver codeint main(){ int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; int n = sizeof(num) / sizeof(num[0]); generateNextPalindrome(num, n); return 0;} // This code is contributed by rohan07
#include <stdio.h> // A utility function to print an arrayvoid printArray (int arr[], int n); // A utility function to check if num has all 9sint AreAll9s (int num[], int n ); // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){ // find the index of mid digit int mid = n/2; // A bool variable to check if copy of left side to right is sufficient or not bool leftsmaller = false; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends if n is odd or even int j = (n % 2)? mid + 1 : mid; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) i--,j++; // Find if the middle digit(s) need to be incremented or not (or copying left // side is not sufficient) if ( i < 0 || num[i] < num[j]) leftsmaller = true; // Copy the mirror of left to tight while (i >= 0) { num[j] = num[i]; j++; i--; } // Handle the case where middle digit(s) must be incremented. // This part of code is for CASE 1 and CASE 2.2 if (leftsmaller == true) { int carry = 1; i = mid - 1; // If there are odd digits, then increment // the middle digit and store the carry if (n%2 == 1) { num[mid] += carry; carry = num[mid] / 10; num[mid] %= 10; j = mid + 1; } else j = mid; // Add 1 to the rightmost digit of the left side, propagate the carry // towards MSB digit and simultaneously copying mirror of the left side // to the right side. while (i >= 0) { num[i] += carry; carry = num[i] / 10; num[i] %= 10; num[j++] = num[i--]; // copy mirror to right } }} // The function that prints next palindrome of a given number num[]// with n digits.void generateNextPalindrome( int num[], int n ){ int i; printf("Next palindrome is:"); // Input type 1: All the digits are 9, simply o/p 1 // followed by n-1 0's followed by 1. if( AreAll9s( num, n ) ) { printf( "1 "); for( i = 1; i < n; i++ ) printf( "0 " ); printf( "1" ); } // Input type 2 and 3 else { generateNextPalindromeUtil ( num, n ); // print the result printArray (num, n); }} // A utility function to check if num has all 9sint AreAll9s( int* num, int n ){ int i; for( i = 0; i < n; ++i ) if( num[i] != 9 ) return 0; return 1;} /* Utility that prints out an array on a line */void printArray(int arr[], int n){ int i; for (i=0; i < n; i++) printf("%d ", arr[i]); printf("\n");} // Driver Program to test above functionint main(){ int num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2}; int n = sizeof (num)/ sizeof(num[0]); generateNextPalindrome( num, n ); return 0;}
// Java program to find next smallest// palindrome public class nextplaindrome{ // Returns next palindrome of a given // number num[]. This function is for // input type 2 and 3 static void generateNextPalindromeUtil(int num[], int n) { int mid = n / 2; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not boolean leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { int carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = num[mid] / 10; num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. //when carry is zero no need to loop through till i>=0 while (i >= 0 && carry>0) { num[i] = num[i] + carry; carry = num[i] / 10; num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } } } // The function that prints next palindrome // of a given number num[] with n digits. static void generateNextPalindrome(int num[], int n) { System.out.println("Next Palindrome is:"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { System.out.print("1"); for (int i = 0; i < n - 1; i++) System.out.print("0"); System.out.println("1"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); } } // A utility function to check if num has all 9s static boolean isAll9(int num[], int n) { for (int i = 0; i < n; i++) if (num[i] != 9) return false; return true; } /* Utility that prints out an array on a line */ static void printarray(int num[]) { for (int i = 0; i < num.length; i++) System.out.print(num[i]); System.out.println(); } public static void main(String[] args) { int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; generateNextPalindrome(num, num.length); }}
# Returns next palindrome of a given number num[].# This function is for input type 2 and 3def generateNextPalindromeUtil (num, n) : # find the index of mid digit mid = int(n/2 ) # A bool variable to check if copy of left # side to right is sufficient or not leftsmaller = False # end of left side is always 'mid -1' i = mid - 1 # Beginning of right side depends # if n is odd or even j = mid + 1 if (n % 2) else mid # Initially, ignore the middle same digits while (i >= 0 and num[i] == num[j]) : i-=1 j+=1 # Find if the middle digit(s) need to be # incremented or not (or copying left # side is not sufficient) if ( i < 0 or num[i] < num[j]): leftsmaller = True # Copy the mirror of left to tight while (i >= 0) : num[j] = num[i] j+=1 i-=1 # Handle the case where middle # digit(s) must be incremented. # This part of code is for CASE 1 and CASE 2.2 if (leftsmaller == True) : carry = 1 i = mid - 1 # If there are odd digits, then increment # the middle digit and store the carry if (n%2 == 1) : num[mid] += carry carry = int(num[mid] / 10 ) num[mid] %= 10 j = mid + 1 else: j = mid # Add 1 to the rightmost digit of the # left side, propagate the carry # towards MSB digit and simultaneously # copying mirror of the left side # to the right side. while (i >= 0) : num[i] += carry carry = int(num[i] / 10) num[i] %= 10 num[j] = num[i] # copy mirror to right j+=1 i-=1 # The function that prints next# palindrome of a given number num[]# with n digits.def generateNextPalindrome(num, n ) : print("\nNext palindrome is:") # Input type 1: All the digits are 9, simply o/p 1 # followed by n-1 0's followed by 1. if( AreAll9s( num, n ) == True) : print( "1") for i in range(1, n): print( "0" ) print( "1") # Input type 2 and 3 else: generateNextPalindromeUtil ( num, n ) # print the result printArray (num, n) # A utility function to check if num has all 9sdef AreAll9s(num, n ): for i in range(1, n): if( num[i] != 9 ) : return 0 return 1 # Utility that prints out an array on a linedef printArray(arr, n): for i in range(0, n): print(int(arr[i]),end=" ") print() # Driver Program to test above functionif __name__ == "__main__": num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2] n = len(num) generateNextPalindrome( num, n ) # This code is contributed by Smitha Dinesh Semwal
// C# program to find next smallest palindromeusing System;public class GFG { // Returns next palindrome of a given // number num[]. This function is for // input type 2 and 3 static void generateNextPalindromeUtil(int []num, int n) { int mid = n / 2; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not bool leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { int carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = num[mid] / 10; num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. while (i >= 0) { num[i] = num[i] + carry; carry = num[i] / 10; num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } } } // The function that prints next palindrome // of a given number num[] with n digits. static void generateNextPalindrome(int []num, int n) { Console.WriteLine("Next Palindrome is:"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { Console.Write("1"); for (int i = 0; i < n - 1; i++) Console.Write("0"); Console.Write("1"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); } } // A utility function to check if num has all 9s static bool isAll9(int[] num, int n) { for (int i = 0; i < n; i++) if (num[i] != 9) return false; return true; } /* Utility that prints out an array on a line */ static void printarray(int []num) { for (int i = 0; i < num.Length; i++) Console.Write(num[i]+ " "); Console.Write(" "); } // Driver code public static void Main() { int []num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; generateNextPalindrome(num, num.Length); }} // This code is contributed by Smitha.
<?php// PHP program to find next// smallest palindrome // Returns next palindrome// of a given number num[].// This function is for// input type 2 and 3function generateNextPalindromeUtil($num, $n){ $mid = (int)($n / 2); // end of left side // is always 'mid -1' $i = $mid - 1; // Beginning of right // side depends if n // is odd or even $j = ($n % 2 == 0) ? $mid : ($mid + 1); // A bool variable to check // if copy of left side to // right is sufficient or not $leftsmaller = false; // Initially, ignore the // middle same digits while ($i >= 0 && $num[$i] == $num[$j]) { $i--; $j++; } // Find if the middle digit(s) // need to be incremented or // not (or copying left side // is not sufficient) if ($i < 0 || $num[$i] < $num[$j]) { $leftsmaller = true; } // Copy the mirror // of left to tight while ($i >= 0) { $num[$j++] = $num[$i--]; } // Handle the case where // middle digit(s) must be // incremented. This part // of code is for CASE 1 // and CASE 2.2 if ($leftsmaller) { $carry = 1; // If there are odd digits, // then increment the middle // digit and store the carry if ($n % 2 == 1) { $num[$mid] += 1; $carry = (int)($num[$mid] / 10); $num[$mid] %= 10; } $i = $mid - 1; $j = ($n % 2 == 0 ? $mid : $mid + 1); // Add 1 to the rightmost digit // of the left side, propagate // the carry towards MSB digit // and simultaneously copying // mirror of the left side to // the right side. while ($i >= 0) { $num[$i] = $num[$i] + $carry; $carry = (int)($num[$i] / 10); $num[$i] %= 10; // copy mirror to right $num[$j] = $num[$i]; $i--; $j++; } }return $num;} // The function that prints// next palindrome of a given// number num[] with n digits.function generateNextPalindrome($num, $n){ echo "Next Palindrome is:\n"; // Input type 1: All the // digits are 9, simply // o/p 1 followed by n-1 // 0's followed by 1. if (isAll9($num, $n)) { echo "1"; for ($i = 0; $i < $n - 1; $i++) echo "0"; echo "1"; } // Input type 2 and 3 else { $num = generateNextPalindromeUtil($num, $n); printarray($num); }} // A utility function to// check if num has all 9sfunction isAll9($num, $n){ for ($i = 0; $i < $n; $i++) if ($num[$i] != 9) return false; return true;} /* Utility that prints outan array on a line */function printarray($num){ for ($i = 0; $i < count($num); $i++) echo $num[$i]; echo "\n";} // Driver code$num = array(9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2);generateNextPalindrome($num, count($num)); // This code is contributed by mits.?>
<script> // JavaScript program to find next smallest// palindrome // Returns next palindrome of a given// number num. This function is for// input type 2 and 3function generateNextPalindromeUtil(num , n){ var mid = parseInt(n / 2); // end of left side is always 'mid -1' var i = mid - 1; // Beginning of right side depends // if n is odd or even var j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { var carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = parseInt(num[mid] / 10); num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. //when carry is zero no need to loop through till i>=0 while (i >= 0 && carry>0) { num[i] = num[i] + carry; carry = parseInt(num[i] / 10); num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } }} // The function that prints next palindrome// of a given number num with n digits.function generateNextPalindrome(num , n){ document.write("Next Palindrome is: <br>"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { document.write("1"); for (i = 0; i < n - 1; i++) document.write("0"); document.write("1"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); }} // A utility function to check if num has all 9sfunction isAll9(num , n) { for (i = 0; i < n; i++) if (num[i] != 9) return false; return true;} /* Utility that prints out an array on a line */function printarray(num) { for (i = 0; i < num.length; i++) document.write(num[i]+"\n");} var num = [ 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 ];generateNextPalindrome(num, num.length); // This code is contributed by 29AjayKumar </script>
Next palindrome is:9 4 1 8 8 0 8 8 1 4 9
Time Complexity: O(num)
Space Complexity: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
Mithun Kumar
hritikgupta
ankush_953
Akanksha_Rai
rohit768
ashraf61242
29AjayKumar
rohan07
tejasbhavsar06
subhammahato348
siddharthsingh7898
rishavmahato348
surindertarika1234
splevel62
amartyaghoshgfg
khushboogoyal499
geekygirl2001
Amazon
FactSet
MakeMyTrip
Microsoft
palindrome
Prime Number
Yahoo
Arrays
Mathematical
Sorting
Strings
Amazon
Microsoft
FactSet
MakeMyTrip
Yahoo
Arrays
Strings
Mathematical
Sorting
Prime Number
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 422,
"s": 52,
"text": "Given a number, find the next smallest palindrome larger than this number. For example, if the input number is β2 3 5 4 5β, the output should be β2 3 6 3 2β. And if the input number is β9 9 9β, the output should be β1 0 0 1β. The input is assumed to be an array. Every entry in array represents a digit in input number. Let the array be βnum[]β and size of array be βnβ"
},
{
"code": null,
"e": 800,
"s": 422,
"text": "There can be three different types of inputs that need to be handled separately. 1) The input number is palindrome and has all 9s. For example β9 9 9β. Output should be β1 0 0 1β 2) The input number is not palindrome. For example β1 2 3 4β. Output should be β1 3 3 1β 3) The input number is palindrome and doesnβt have all 9s. For example β1 2 2 1β. Output should be β1 3 3 1β."
},
{
"code": null,
"e": 1119,
"s": 800,
"text": "Solution for input type 1 is easy. The output contains n + 1 digits where the corner digits are 1, and all digits between corner digits are 0.Now let us first talk about input type 2 and 3. How to convert a given number to a greater palindrome? To understand the solution, let us first define the following two terms: "
},
{
"code": null,
"e": 1238,
"s": 1119,
"text": "Left Side: The left half of given number. Left side of β1 2 3 4 5 6β is β1 2 3β and left side of β1 2 3 4 5β is β1 2β "
},
{
"code": null,
"e": 1361,
"s": 1238,
"text": "Right Side: The right half of given number. Right side of β1 2 3 4 5 6β is β4 5 6β and right side of β1 2 3 4 5β is β4 5β "
},
{
"code": null,
"e": 1960,
"s": 1361,
"text": "To convert to palindrome, we can either take the mirror of its left side or take mirror of its right side. However, if we take the mirror of the right side, then the palindrome so formed is not guaranteed to be next larger palindrome. So, we must take the mirror of left side and copy it to right side. But there are some cases that must be handled in different ways. See the following steps.We will start with two indices i and j. i pointing to the two middle elements (or pointing to two elements around the middle element in case of n being odd). We one by one move i and j away from each other."
},
{
"code": null,
"e": 2206,
"s": 1960,
"text": "Step 1. Initially, ignore the part of left side which is same as the corresponding part of right side. For example, if the number is β8 3 4 2 2 4 6 9β²β², we ignore the middle four elements. i now points to element 3 and j now points to element 6."
},
{
"code": null,
"e": 2671,
"s": 2206,
"text": "Step 2. After step 1, following cases arise:Case 1: Indices i & j cross the boundary. This case occurs when the input number is palindrome. In this case, we just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side. For example, if the given number is β1 2 9 2 1β, we increment 9 to 10 and propagate the carry. So the number becomes β1 3 0 3 1β"
},
{
"code": null,
"e": 2927,
"s": 2671,
"text": "Case 2: There are digits left between left side and right side which are not same. So, we just mirror the left side to the right side & try to minimize the number formed to guarantee the next smallest palindrome. In this case, there can be two sub-cases. "
},
{
"code": null,
"e": 3617,
"s": 2927,
"text": "2.1) Copying the left side to the right side is sufficient, we donβt need to increment any digits and the result is just mirror of left side. Following are some examples of this sub-case. Next palindrome for β7 8 3 3 2 2β²β² is β7 8 3 3 8 7β Next palindrome for β1 2 5 3 2 2β²β² is β1 2 5 5 2 1β Next palindrome for β1 4 5 8 7 6 7 8 3 2 2β²β² is β1 4 5 8 7 6 7 8 5 4 1β How do we check for this sub-case? All we need to check is the digit just after the ignored part in step 1. This digit is highlighted in above examples. If this digit is greater than the corresponding digit in right side digit, then copying the left side to the right side is sufficient and we donβt need to do anything else."
},
{
"code": null,
"e": 4188,
"s": 3617,
"text": "2.2) Copying the left side to the right side is NOT sufficient. This happens when the above defined digit of left side is smaller. Following are some examples of this case. Next palindrome for β7 1 3 3 2 2β²β² is β7 1 4 4 1 7β Next palindrome for β1 2 3 4 6 2 8β²β² is β1 2 3 5 3 2 1β Next palindrome for β9 4 1 8 7 9 7 8 3 2 2β²β² is β9 4 1 8 8 0 8 8 1 4 9β We handle this subcase like Case 1. We just add 1 to the middle digit (or digits in case n is even) propagate the carry towards MSB digit of left side and simultaneously copy mirror of the left side to the right side."
},
{
"code": null,
"e": 4264,
"s": 4188,
"text": "Approach 1: Basic Approach for Finding the next smallest Palindrome Number."
},
{
"code": null,
"e": 4268,
"s": 4264,
"text": "C++"
},
{
"code": null,
"e": 4273,
"s": 4268,
"text": "Java"
},
{
"code": null,
"e": 4281,
"s": 4273,
"text": "Python3"
},
{
"code": null,
"e": 4284,
"s": 4281,
"text": "C#"
},
{
"code": null,
"e": 4295,
"s": 4284,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;// Function to check whether number is palindrome or notint isPalindrome(int num){ // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store in // rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; }}int main(){ // Take any number to find its next palindrome number int num = 9687; // If number is not Palindrome we go to the next number // using while loop while (!isPalindrome(num)) { num = num + 1; } // now we get the next Palindrome so let's print it cout << \"Next Palindrome :\"; cout << num; return 0;}// Contribute by :- Tejas Bhavsar",
"e": 5201,
"s": 4295,
"text": null
},
{
"code": "import java.io.*; class GFG{ // Function to check whether number is palindrome or not static int isPalindrome(int num) { // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver code public static void main(String[] args) { // Take any number to find its next palindrome // number int num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it System.out.print(\"Next Palindrome :\"); System.out.print(num); }} // This code is contributed by subhammahato348.",
"e": 6374,
"s": 5201,
"text": null
},
{
"code": "# Program to print find next palindrome# number greater than given number. # function to check a number is# palindrome or notdef isPalindrome(num): # Declaring variables # storing num in n so that we can compare it later n = num rev = 0 # while num is not 0 we find its reverse and store # in rev while (num > 0): k = num % 10 rev = (rev * 10) + k num = num // 10 # check if num and its reverse are same if (n == rev): return True else: return False # input numbernum = 9687 # start check from next num;num = num + 1 # Loop checks all numbers from given no.# (num + 1) to next palindrome no.while (True): if (isPalindrome(num)): break num = num + 1 # printing the next palindromeprint(\"Next Palindrome :\")print(num) # This code is contributed by sidharthsingh7898.",
"e": 7222,
"s": 6374,
"text": null
},
{
"code": "using System;class GFG { // Function to check whether number is palindrome or not static int isPalindrome(int num) { // Declaring variables int n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = num / 10; } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver code public static void Main() { // Take any number to find its next palindrome // number int num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it Console.Write(\"Next Palindrome :\"); Console.Write(num); }} // This code is contributed by subhammahato348.",
"e": 8328,
"s": 7222,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to check whether number is palindrome or not function isPalindrome(num) { // Declaring variables let n, k, rev = 0; // storing num in n so that we can compare it later n = num; // while num is not 0 we find its reverse and store // in rev while (num != 0) { k = num % 10; rev = (rev * 10) + k; num = Math.floor(num / 10); } // check if num and its reverse are same if (n == rev) { return 1; } else { return 0; } } // Driver Code // Take any number to find its next palindrome // number let num = 9687; // If number is not Palindrome we go to the next // number using while loop while (isPalindrome(num) == 0) { num = num + 1; } // now we get the next Palindrome so let's print it document.write(\"Next Palindrome :\"); document.write(num); // This code is contributed by splevel62.</script>",
"e": 9462,
"s": 8328,
"text": null
},
{
"code": null,
"e": 9484,
"s": 9462,
"text": "Next Palindrome :9779"
},
{
"code": null,
"e": 9516,
"s": 9484,
"text": "Time Complexity: O(num * |num|)"
},
{
"code": null,
"e": 9539,
"s": 9516,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 9543,
"s": 9539,
"text": "C++"
},
{
"code": null,
"e": 9545,
"s": 9543,
"text": "C"
},
{
"code": null,
"e": 9550,
"s": 9545,
"text": "Java"
},
{
"code": null,
"e": 9558,
"s": 9550,
"text": "Python3"
},
{
"code": null,
"e": 9561,
"s": 9558,
"text": "C#"
},
{
"code": null,
"e": 9565,
"s": 9561,
"text": "PHP"
},
{
"code": null,
"e": 9576,
"s": 9565,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; // Utility that prints out an array on a linevoid printArray(int arr[], int n){ int i; for(i = 0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // A utility function to check if num has all 9sint AreAll9s(int* num, int n ){ int i; for(i = 0; i < n; ++i) if (num[i] != 9) return 0; return 1;} // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){ // Find the index of mid digit int mid = n / 2; // A bool variable to check if copy of left // side to right is sufficient or not bool leftsmaller = false; // End of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2) ? mid + 1 : mid; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) i--, j++; // Find if the middle digit(s) need to be // incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) leftsmaller = true; // Copy the mirror of left to tight while (i >= 0) { num[j] = num[i]; j++; i--; } // Handle the case where middle digit(s) must // be incremented. This part of code is for // CASE 1 and CASE 2.2 if (leftsmaller == true) { int carry = 1; i = mid - 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += carry; carry = num[mid] / 10; num[mid] %= 10; j = mid + 1; } else j = mid; // Add 1 to the rightmost digit of the // left side, propagate the carry towards // MSB digit and simultaneously copying // mirror of the left side to the right side. while (i >= 0) { num[i] += carry; carry = num[i] / 10; num[i] %= 10; // Copy mirror to right num[j++] = num[i--]; } }} // The function that prints next palindrome// of a given number num[] with n digits.void generateNextPalindrome(int num[], int n){ int i; printf(\"Next palindrome is:\"); // Input type 1: All the digits are 9, simply o/p 1 // followed by n-1 0's followed by 1. if (AreAll9s(num, n)) { printf(\"1 \"); for(i = 1; i < n; i++) printf(\"0 \"); printf(\"1\"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); // print the result printArray (num, n); }} // Driver codeint main(){ int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; int n = sizeof(num) / sizeof(num[0]); generateNextPalindrome(num, n); return 0;} // This code is contributed by rohan07",
"e": 12522,
"s": 9576,
"text": null
},
{
"code": "#include <stdio.h> // A utility function to print an arrayvoid printArray (int arr[], int n); // A utility function to check if num has all 9sint AreAll9s (int num[], int n ); // Returns next palindrome of a given number num[].// This function is for input type 2 and 3void generateNextPalindromeUtil (int num[], int n ){ // find the index of mid digit int mid = n/2; // A bool variable to check if copy of left side to right is sufficient or not bool leftsmaller = false; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends if n is odd or even int j = (n % 2)? mid + 1 : mid; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) i--,j++; // Find if the middle digit(s) need to be incremented or not (or copying left // side is not sufficient) if ( i < 0 || num[i] < num[j]) leftsmaller = true; // Copy the mirror of left to tight while (i >= 0) { num[j] = num[i]; j++; i--; } // Handle the case where middle digit(s) must be incremented. // This part of code is for CASE 1 and CASE 2.2 if (leftsmaller == true) { int carry = 1; i = mid - 1; // If there are odd digits, then increment // the middle digit and store the carry if (n%2 == 1) { num[mid] += carry; carry = num[mid] / 10; num[mid] %= 10; j = mid + 1; } else j = mid; // Add 1 to the rightmost digit of the left side, propagate the carry // towards MSB digit and simultaneously copying mirror of the left side // to the right side. while (i >= 0) { num[i] += carry; carry = num[i] / 10; num[i] %= 10; num[j++] = num[i--]; // copy mirror to right } }} // The function that prints next palindrome of a given number num[]// with n digits.void generateNextPalindrome( int num[], int n ){ int i; printf(\"Next palindrome is:\"); // Input type 1: All the digits are 9, simply o/p 1 // followed by n-1 0's followed by 1. if( AreAll9s( num, n ) ) { printf( \"1 \"); for( i = 1; i < n; i++ ) printf( \"0 \" ); printf( \"1\" ); } // Input type 2 and 3 else { generateNextPalindromeUtil ( num, n ); // print the result printArray (num, n); }} // A utility function to check if num has all 9sint AreAll9s( int* num, int n ){ int i; for( i = 0; i < n; ++i ) if( num[i] != 9 ) return 0; return 1;} /* Utility that prints out an array on a line */void printArray(int arr[], int n){ int i; for (i=0; i < n; i++) printf(\"%d \", arr[i]); printf(\"\\n\");} // Driver Program to test above functionint main(){ int num[] = {9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2}; int n = sizeof (num)/ sizeof(num[0]); generateNextPalindrome( num, n ); return 0;}",
"e": 15509,
"s": 12522,
"text": null
},
{
"code": "// Java program to find next smallest// palindrome public class nextplaindrome{ // Returns next palindrome of a given // number num[]. This function is for // input type 2 and 3 static void generateNextPalindromeUtil(int num[], int n) { int mid = n / 2; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not boolean leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { int carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = num[mid] / 10; num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. //when carry is zero no need to loop through till i>=0 while (i >= 0 && carry>0) { num[i] = num[i] + carry; carry = num[i] / 10; num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } } } // The function that prints next palindrome // of a given number num[] with n digits. static void generateNextPalindrome(int num[], int n) { System.out.println(\"Next Palindrome is:\"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { System.out.print(\"1\"); for (int i = 0; i < n - 1; i++) System.out.print(\"0\"); System.out.println(\"1\"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); } } // A utility function to check if num has all 9s static boolean isAll9(int num[], int n) { for (int i = 0; i < n; i++) if (num[i] != 9) return false; return true; } /* Utility that prints out an array on a line */ static void printarray(int num[]) { for (int i = 0; i < num.length; i++) System.out.print(num[i]); System.out.println(); } public static void main(String[] args) { int num[] = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; generateNextPalindrome(num, num.length); }}",
"e": 18954,
"s": 15509,
"text": null
},
{
"code": "# Returns next palindrome of a given number num[].# This function is for input type 2 and 3def generateNextPalindromeUtil (num, n) : # find the index of mid digit mid = int(n/2 ) # A bool variable to check if copy of left # side to right is sufficient or not leftsmaller = False # end of left side is always 'mid -1' i = mid - 1 # Beginning of right side depends # if n is odd or even j = mid + 1 if (n % 2) else mid # Initially, ignore the middle same digits while (i >= 0 and num[i] == num[j]) : i-=1 j+=1 # Find if the middle digit(s) need to be # incremented or not (or copying left # side is not sufficient) if ( i < 0 or num[i] < num[j]): leftsmaller = True # Copy the mirror of left to tight while (i >= 0) : num[j] = num[i] j+=1 i-=1 # Handle the case where middle # digit(s) must be incremented. # This part of code is for CASE 1 and CASE 2.2 if (leftsmaller == True) : carry = 1 i = mid - 1 # If there are odd digits, then increment # the middle digit and store the carry if (n%2 == 1) : num[mid] += carry carry = int(num[mid] / 10 ) num[mid] %= 10 j = mid + 1 else: j = mid # Add 1 to the rightmost digit of the # left side, propagate the carry # towards MSB digit and simultaneously # copying mirror of the left side # to the right side. while (i >= 0) : num[i] += carry carry = int(num[i] / 10) num[i] %= 10 num[j] = num[i] # copy mirror to right j+=1 i-=1 # The function that prints next# palindrome of a given number num[]# with n digits.def generateNextPalindrome(num, n ) : print(\"\\nNext palindrome is:\") # Input type 1: All the digits are 9, simply o/p 1 # followed by n-1 0's followed by 1. if( AreAll9s( num, n ) == True) : print( \"1\") for i in range(1, n): print( \"0\" ) print( \"1\") # Input type 2 and 3 else: generateNextPalindromeUtil ( num, n ) # print the result printArray (num, n) # A utility function to check if num has all 9sdef AreAll9s(num, n ): for i in range(1, n): if( num[i] != 9 ) : return 0 return 1 # Utility that prints out an array on a linedef printArray(arr, n): for i in range(0, n): print(int(arr[i]),end=\" \") print() # Driver Program to test above functionif __name__ == \"__main__\": num = [9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2] n = len(num) generateNextPalindrome( num, n ) # This code is contributed by Smitha Dinesh Semwal",
"e": 21735,
"s": 18954,
"text": null
},
{
"code": "// C# program to find next smallest palindromeusing System;public class GFG { // Returns next palindrome of a given // number num[]. This function is for // input type 2 and 3 static void generateNextPalindromeUtil(int []num, int n) { int mid = n / 2; // end of left side is always 'mid -1' int i = mid - 1; // Beginning of right side depends // if n is odd or even int j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not bool leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { int carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = num[mid] / 10; num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. while (i >= 0) { num[i] = num[i] + carry; carry = num[i] / 10; num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } } } // The function that prints next palindrome // of a given number num[] with n digits. static void generateNextPalindrome(int []num, int n) { Console.WriteLine(\"Next Palindrome is:\"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { Console.Write(\"1\"); for (int i = 0; i < n - 1; i++) Console.Write(\"0\"); Console.Write(\"1\"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); } } // A utility function to check if num has all 9s static bool isAll9(int[] num, int n) { for (int i = 0; i < n; i++) if (num[i] != 9) return false; return true; } /* Utility that prints out an array on a line */ static void printarray(int []num) { for (int i = 0; i < num.Length; i++) Console.Write(num[i]+ \" \"); Console.Write(\" \"); } // Driver code public static void Main() { int []num = { 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 }; generateNextPalindrome(num, num.Length); }} // This code is contributed by Smitha.",
"e": 25132,
"s": 21735,
"text": null
},
{
"code": "<?php// PHP program to find next// smallest palindrome // Returns next palindrome// of a given number num[].// This function is for// input type 2 and 3function generateNextPalindromeUtil($num, $n){ $mid = (int)($n / 2); // end of left side // is always 'mid -1' $i = $mid - 1; // Beginning of right // side depends if n // is odd or even $j = ($n % 2 == 0) ? $mid : ($mid + 1); // A bool variable to check // if copy of left side to // right is sufficient or not $leftsmaller = false; // Initially, ignore the // middle same digits while ($i >= 0 && $num[$i] == $num[$j]) { $i--; $j++; } // Find if the middle digit(s) // need to be incremented or // not (or copying left side // is not sufficient) if ($i < 0 || $num[$i] < $num[$j]) { $leftsmaller = true; } // Copy the mirror // of left to tight while ($i >= 0) { $num[$j++] = $num[$i--]; } // Handle the case where // middle digit(s) must be // incremented. This part // of code is for CASE 1 // and CASE 2.2 if ($leftsmaller) { $carry = 1; // If there are odd digits, // then increment the middle // digit and store the carry if ($n % 2 == 1) { $num[$mid] += 1; $carry = (int)($num[$mid] / 10); $num[$mid] %= 10; } $i = $mid - 1; $j = ($n % 2 == 0 ? $mid : $mid + 1); // Add 1 to the rightmost digit // of the left side, propagate // the carry towards MSB digit // and simultaneously copying // mirror of the left side to // the right side. while ($i >= 0) { $num[$i] = $num[$i] + $carry; $carry = (int)($num[$i] / 10); $num[$i] %= 10; // copy mirror to right $num[$j] = $num[$i]; $i--; $j++; } }return $num;} // The function that prints// next palindrome of a given// number num[] with n digits.function generateNextPalindrome($num, $n){ echo \"Next Palindrome is:\\n\"; // Input type 1: All the // digits are 9, simply // o/p 1 followed by n-1 // 0's followed by 1. if (isAll9($num, $n)) { echo \"1\"; for ($i = 0; $i < $n - 1; $i++) echo \"0\"; echo \"1\"; } // Input type 2 and 3 else { $num = generateNextPalindromeUtil($num, $n); printarray($num); }} // A utility function to// check if num has all 9sfunction isAll9($num, $n){ for ($i = 0; $i < $n; $i++) if ($num[$i] != 9) return false; return true;} /* Utility that prints outan array on a line */function printarray($num){ for ($i = 0; $i < count($num); $i++) echo $num[$i]; echo \"\\n\";} // Driver code$num = array(9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2);generateNextPalindrome($num, count($num)); // This code is contributed by mits.?>",
"e": 28208,
"s": 25132,
"text": null
},
{
"code": "<script> // JavaScript program to find next smallest// palindrome // Returns next palindrome of a given// number num. This function is for// input type 2 and 3function generateNextPalindromeUtil(num , n){ var mid = parseInt(n / 2); // end of left side is always 'mid -1' var i = mid - 1; // Beginning of right side depends // if n is odd or even var j = (n % 2 == 0) ? mid : mid + 1; // A bool variable to check if copy of left // side to right // is sufficient or not leftsmaller = false; // Initially, ignore the middle same digits while (i >= 0 && num[i] == num[j]) { i--; j++; } // Find if the middle digit(s) need to // be incremented or not (or copying left // side is not sufficient) if (i < 0 || num[i] < num[j]) { leftsmaller = true; } // Copy the mirror of left to tight while (i >= 0) { num[j++] = num[i--]; } // Handle the case where middle digit(s) // must be incremented. This part of code // is for CASE 1 and CASE 2.2 if (leftsmaller) { var carry = 1; // If there are odd digits, then increment // the middle digit and store the carry if (n % 2 == 1) { num[mid] += 1; carry = parseInt(num[mid] / 10); num[mid] %= 10; } i = mid - 1; j = (n % 2 == 0 ? mid : mid + 1); // Add 1 to the rightmost digit of the left // side, propagate the carry towards MSB digit // and simultaneously copying mirror of the // left side to the right side. //when carry is zero no need to loop through till i>=0 while (i >= 0 && carry>0) { num[i] = num[i] + carry; carry = parseInt(num[i] / 10); num[i] %= 10; num[j] = num[i];// copy mirror to right i--; j++; } }} // The function that prints next palindrome// of a given number num with n digits.function generateNextPalindrome(num , n){ document.write(\"Next Palindrome is: <br>\"); // Input type 1: All the digits are 9, // simply o/p 1 followed by n-1 0's // followed by 1. if (isAll9(num, n)) { document.write(\"1\"); for (i = 0; i < n - 1; i++) document.write(\"0\"); document.write(\"1\"); } // Input type 2 and 3 else { generateNextPalindromeUtil(num, n); printarray(num); }} // A utility function to check if num has all 9sfunction isAll9(num , n) { for (i = 0; i < n; i++) if (num[i] != 9) return false; return true;} /* Utility that prints out an array on a line */function printarray(num) { for (i = 0; i < num.length; i++) document.write(num[i]+\"\\n\");} var num = [ 9, 4, 1, 8, 7, 9, 7, 8, 3, 2, 2 ];generateNextPalindrome(num, num.length); // This code is contributed by 29AjayKumar </script>",
"e": 31130,
"s": 28208,
"text": null
},
{
"code": null,
"e": 31172,
"s": 31130,
"text": "Next palindrome is:9 4 1 8 8 0 8 8 1 4 9 "
},
{
"code": null,
"e": 31196,
"s": 31172,
"text": "Time Complexity: O(num)"
},
{
"code": null,
"e": 31219,
"s": 31196,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 31345,
"s": 31219,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31366,
"s": 31345,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 31379,
"s": 31366,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 31391,
"s": 31379,
"text": "hritikgupta"
},
{
"code": null,
"e": 31402,
"s": 31391,
"text": "ankush_953"
},
{
"code": null,
"e": 31415,
"s": 31402,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31424,
"s": 31415,
"text": "rohit768"
},
{
"code": null,
"e": 31436,
"s": 31424,
"text": "ashraf61242"
},
{
"code": null,
"e": 31448,
"s": 31436,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31456,
"s": 31448,
"text": "rohan07"
},
{
"code": null,
"e": 31471,
"s": 31456,
"text": "tejasbhavsar06"
},
{
"code": null,
"e": 31487,
"s": 31471,
"text": "subhammahato348"
},
{
"code": null,
"e": 31506,
"s": 31487,
"text": "siddharthsingh7898"
},
{
"code": null,
"e": 31522,
"s": 31506,
"text": "rishavmahato348"
},
{
"code": null,
"e": 31541,
"s": 31522,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31551,
"s": 31541,
"text": "splevel62"
},
{
"code": null,
"e": 31567,
"s": 31551,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 31584,
"s": 31567,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 31598,
"s": 31584,
"text": "geekygirl2001"
},
{
"code": null,
"e": 31605,
"s": 31598,
"text": "Amazon"
},
{
"code": null,
"e": 31613,
"s": 31605,
"text": "FactSet"
},
{
"code": null,
"e": 31624,
"s": 31613,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 31634,
"s": 31624,
"text": "Microsoft"
},
{
"code": null,
"e": 31645,
"s": 31634,
"text": "palindrome"
},
{
"code": null,
"e": 31658,
"s": 31645,
"text": "Prime Number"
},
{
"code": null,
"e": 31664,
"s": 31658,
"text": "Yahoo"
},
{
"code": null,
"e": 31671,
"s": 31664,
"text": "Arrays"
},
{
"code": null,
"e": 31684,
"s": 31671,
"text": "Mathematical"
},
{
"code": null,
"e": 31692,
"s": 31684,
"text": "Sorting"
},
{
"code": null,
"e": 31700,
"s": 31692,
"text": "Strings"
},
{
"code": null,
"e": 31707,
"s": 31700,
"text": "Amazon"
},
{
"code": null,
"e": 31717,
"s": 31707,
"text": "Microsoft"
},
{
"code": null,
"e": 31725,
"s": 31717,
"text": "FactSet"
},
{
"code": null,
"e": 31736,
"s": 31725,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 31742,
"s": 31736,
"text": "Yahoo"
},
{
"code": null,
"e": 31749,
"s": 31742,
"text": "Arrays"
},
{
"code": null,
"e": 31757,
"s": 31749,
"text": "Strings"
},
{
"code": null,
"e": 31770,
"s": 31757,
"text": "Mathematical"
},
{
"code": null,
"e": 31778,
"s": 31770,
"text": "Sorting"
},
{
"code": null,
"e": 31791,
"s": 31778,
"text": "Prime Number"
},
{
"code": null,
"e": 31802,
"s": 31791,
"text": "palindrome"
},
{
"code": null,
"e": 31900,
"s": 31802,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31968,
"s": 31900,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32012,
"s": 31968,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 32044,
"s": 32012,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 32092,
"s": 32044,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 32106,
"s": 32092,
"text": "Linear Search"
},
{
"code": null,
"e": 32136,
"s": 32106,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32179,
"s": 32136,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 32239,
"s": 32179,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32254,
"s": 32239,
"text": "C++ Data Types"
}
] |
How to remove outline around text input boxes in chrome using CSS?
|
16 Oct, 2021
Generally in the case of Google Chrome Browser, when the input field gets focus then the blue outline occurred on the border of the Input fields. The Task can be done by using the CSS outline property.
Example:
html
<html><head> <title> How to remove outline around text input boxes in chrome using CSS? </title><style>textarea:focus{ outline: none; } </style> <body> <h2> GeeksFprGeeks </h2> <h2> How to remove outline around text input boxes in chrome using CSS? </h2><br> <h4><b> Before using the outline Property</b></h4> <input type="text"> <h4><b>After using the Outline Property</b></h4> <textarea rows="4"></textarea> </body></head></html>
Output
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
surindertarika1234
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "Generally in the case of Google Chrome Browser, when the input field gets focus then the blue outline occurred on the border of the Input fields. The Task can be done by using the CSS outline property. "
},
{
"code": null,
"e": 243,
"s": 232,
"text": "Example: "
},
{
"code": null,
"e": 248,
"s": 243,
"text": "html"
},
{
"code": "<html><head> <title> How to remove outline around text input boxes in chrome using CSS? </title><style>textarea:focus{ outline: none; } </style> <body> <h2> GeeksFprGeeks </h2> <h2> How to remove outline around text input boxes in chrome using CSS? </h2><br> <h4><b> Before using the outline Property</b></h4> <input type=\"text\"> <h4><b>After using the Outline Property</b></h4> <textarea rows=\"4\"></textarea> </body></head></html>",
"e": 791,
"s": 248,
"text": null
},
{
"code": null,
"e": 799,
"s": 791,
"text": "Output "
},
{
"code": null,
"e": 836,
"s": 799,
"text": "Supported Browsers are listed below:"
},
{
"code": null,
"e": 850,
"s": 836,
"text": "Google Chrome"
},
{
"code": null,
"e": 868,
"s": 850,
"text": "Internet Explorer"
},
{
"code": null,
"e": 876,
"s": 868,
"text": "Firefox"
},
{
"code": null,
"e": 882,
"s": 876,
"text": "Opera"
},
{
"code": null,
"e": 901,
"s": 882,
"text": "surindertarika1234"
},
{
"code": null,
"e": 911,
"s": 901,
"text": "HTML-Misc"
},
{
"code": null,
"e": 916,
"s": 911,
"text": "HTML"
},
{
"code": null,
"e": 933,
"s": 916,
"text": "Web Technologies"
},
{
"code": null,
"e": 938,
"s": 933,
"text": "HTML"
},
{
"code": null,
"e": 1036,
"s": 938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1060,
"s": 1036,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1099,
"s": 1060,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1138,
"s": 1099,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1175,
"s": 1138,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1195,
"s": 1175,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1228,
"s": 1195,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1289,
"s": 1228,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1332,
"s": 1289,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1404,
"s": 1332,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to make first letter of a string uppercase in JavaScript ?
|
20 Mar, 2019
There are number of ways to capitalize the first letter of the string in JavaScript. Following are the ways:
toUpperCase():This function applies on a string and change the all letters to uppercase.Syntax:string.toUpperCase()
Return Value: This function returns the capitalized string.slice():This function applies on a string and slice it according to the passed parameter.Syntax:string.slice(start, end)
start: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.Return Value: This function returns the sliced string.charAt():This charAt() function returns the character at given position in string.Syntax:string.charAt(index)
Return Value: This function returns the character at specified position in string.replace():This is an built-in function in JavaScript which is used to replace a slice of a string with another string or a regular expression. Original string will not affected.Syntax:str.replace(A, B)
Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items.Example 1: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 3: This example uses string.replace() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes
arrow_drop_upSave
toUpperCase():This function applies on a string and change the all letters to uppercase.Syntax:string.toUpperCase()
Return Value: This function returns the capitalized string.
string.toUpperCase()
Return Value: This function returns the capitalized string.
slice():This function applies on a string and slice it according to the passed parameter.Syntax:string.slice(start, end)
start: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.Return Value: This function returns the sliced string.
string.slice(start, end)
start: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.
end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.
Return Value: This function returns the sliced string.
charAt():This charAt() function returns the character at given position in string.Syntax:string.charAt(index)
Return Value: This function returns the character at specified position in string.
string.charAt(index)
Return Value: This function returns the character at specified position in string.
replace():This is an built-in function in JavaScript which is used to replace a slice of a string with another string or a regular expression. Original string will not affected.Syntax:str.replace(A, B)
Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items.
str.replace(A, B)
Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items.
Example 1: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 3: This example uses string.replace() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes
arrow_drop_upSave
<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 2: This example uses slice() method to make first letter of a string uppercase.
<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
Example 3: This example uses string.replace() method to make first letter of a string uppercase.
<!DOCTYPE html> <html> <head> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id = "div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>
Output:
Before clicking the button:
After clicking the button:
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 137,
"s": 28,
"text": "There are number of ways to capitalize the first letter of the string in JavaScript. Following are the ways:"
},
{
"code": null,
"e": 4148,
"s": 137,
"text": "toUpperCase():This function applies on a string and change the all letters to uppercase.Syntax:string.toUpperCase()\nReturn Value: This function returns the capitalized string.slice():This function applies on a string and slice it according to the passed parameter.Syntax:string.slice(start, end)\nstart: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.Return Value: This function returns the sliced string.charAt():This charAt() function returns the character at given position in string.Syntax:string.charAt(index)\nReturn Value: This function returns the character at specified position in string.replace():This is an built-in function in JavaScript which is used to replace a slice of a string with another string or a regular expression. Original string will not affected.Syntax:str.replace(A, B)\nParameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items.Example 1: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 3: This example uses string.replace() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4324,
"s": 4148,
"text": "toUpperCase():This function applies on a string and change the all letters to uppercase.Syntax:string.toUpperCase()\nReturn Value: This function returns the capitalized string."
},
{
"code": null,
"e": 4346,
"s": 4324,
"text": "string.toUpperCase()\n"
},
{
"code": null,
"e": 4406,
"s": 4346,
"text": "Return Value: This function returns the capitalized string."
},
{
"code": null,
"e": 4885,
"s": 4406,
"text": "slice():This function applies on a string and slice it according to the passed parameter.Syntax:string.slice(start, end)\nstart: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0.end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start.Return Value: This function returns the sliced string."
},
{
"code": null,
"e": 4911,
"s": 4885,
"text": "string.slice(start, end)\n"
},
{
"code": null,
"e": 5031,
"s": 4911,
"text": "start: This parameter is required. It specifies the position where to begin the slicing. Indexing starts at position 0."
},
{
"code": null,
"e": 5216,
"s": 5031,
"text": "end: This is optional parameter. It specifies the position from where to end the slicing(without including the end). If this parameter is omitted, It selects all characters from start."
},
{
"code": null,
"e": 5271,
"s": 5216,
"text": "Return Value: This function returns the sliced string."
},
{
"code": null,
"e": 5464,
"s": 5271,
"text": "charAt():This charAt() function returns the character at given position in string.Syntax:string.charAt(index)\nReturn Value: This function returns the character at specified position in string."
},
{
"code": null,
"e": 5486,
"s": 5464,
"text": "string.charAt(index)\n"
},
{
"code": null,
"e": 5569,
"s": 5486,
"text": "Return Value: This function returns the character at specified position in string."
},
{
"code": null,
"e": 5954,
"s": 5569,
"text": "replace():This is an built-in function in JavaScript which is used to replace a slice of a string with another string or a regular expression. Original string will not affected.Syntax:str.replace(A, B)\nParameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items."
},
{
"code": null,
"e": 5973,
"s": 5954,
"text": "str.replace(A, B)\n"
},
{
"code": null,
"e": 6156,
"s": 5973,
"text": "Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.Return Value: It returns a new string with replaced items."
},
{
"code": null,
"e": 8938,
"s": 6156,
"text": "Example 1: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 2: This example uses slice() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>Output:Before clicking the button:After clicking the button:Example 3: This example uses string.replace() method to make first letter of a string uppercase.<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>Output:Before clicking the button:After clicking the button:My Personal Notes\narrow_drop_upSave"
},
{
"code": "<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script> </body> </html>",
"e": 9701,
"s": 8938,
"text": null
},
{
"code": null,
"e": 9709,
"s": 9701,
"text": "Output:"
},
{
"code": null,
"e": 9737,
"s": 9709,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 9764,
"s": 9737,
"text": "After clicking the button:"
},
{
"code": null,
"e": 9852,
"s": 9764,
"text": "Example 2: This example uses slice() method to make first letter of a string uppercase."
},
{
"code": "<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>",
"e": 10622,
"s": 9852,
"text": null
},
{
"code": null,
"e": 10630,
"s": 10622,
"text": "Output:"
},
{
"code": null,
"e": 10658,
"s": 10630,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 10685,
"s": 10658,
"text": "After clicking the button:"
},
{
"code": null,
"e": 10782,
"s": 10685,
"text": "Example 3: This example uses string.replace() method to make first letter of a string uppercase."
},
{
"code": "<!DOCTYPE html> <html> <head> <title></title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"capitalizeFLetter()\"> Click to capitalize </button> <h3 id = \"div\" style=\"color: green\"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script> </body> </html>",
"e": 11548,
"s": 10782,
"text": null
},
{
"code": null,
"e": 11556,
"s": 11548,
"text": "Output:"
},
{
"code": null,
"e": 11584,
"s": 11556,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 11611,
"s": 11584,
"text": "After clicking the button:"
},
{
"code": null,
"e": 11629,
"s": 11611,
"text": "javascript-string"
},
{
"code": null,
"e": 11636,
"s": 11629,
"text": "Picked"
},
{
"code": null,
"e": 11647,
"s": 11636,
"text": "JavaScript"
},
{
"code": null,
"e": 11664,
"s": 11647,
"text": "Web Technologies"
},
{
"code": null,
"e": 11762,
"s": 11664,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11823,
"s": 11762,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 11895,
"s": 11823,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 11935,
"s": 11895,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 11977,
"s": 11935,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 12018,
"s": 11977,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 12051,
"s": 12018,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 12113,
"s": 12051,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 12174,
"s": 12113,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 12224,
"s": 12174,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Maximum Subarray Sum in a given Range
|
30 Jun, 2021
Given an array of n numbers, the task is to answer the following queries:
maximumSubarraySum(start, end) : Find the maximum
subarray sum in the range from array index 'start'
to 'end'.
Also see : Range Query With Update RequiredExamples:
Input : arr[] = {1, 3, -4, 5, -2}
Query 1: start = 0, end = 4
Query 2: start = 0, end = 2
Output : 5
4
Explanation:
For Query 1, [1, 3, -4, 5] or ( [5] )
represent the maximum sum sub arrays
with sum = 5.
For Query 2, [1, 3] represents the
maximum sum subarray in the query range
with sum = 4
Segment Trees can be used to solve this problem.Here, we need to keep information regarding various cumulative sums.At every Node we store the following: 1) Maximum Prefix Sum, 2) Maximum Suffix Sum, 3) Total Sum, 4) Maximum Subarray SumA classical Segment Tree with each Node storing the above information should be enough to answer each query. The only focus here is on how the left and the right Nodes of the tree are merged together. Now, we will discuss how each of the information is constructed in each of the segment tree Nodes using the information of its left and right child. Constructing the Maximum Prefix Sum using Left and Right childThere can be two cases for maximum prefix sum of a Node:
The maximum prefix sum occurs in the left child,
The maximum prefix sum occurs in the left child,
In this Case,
Maximum Prefix Sum = Maximum Prefix Sum of Left Child
The maximum prefix sum contains every array element of the left child and the elements contributing to the maximum prefix sum of the right child,
The maximum prefix sum contains every array element of the left child and the elements contributing to the maximum prefix sum of the right child,
In this Case,
Maximum Prefix Sum = Total Sum of Left Child +
Maximum Prefix Sum of Right Child
Constructing the Maximum Suffix Sum using Left and Right childThere can be two cases for maximum suffix sum of a Node:
The maximum suffix sum occurs in the right child,
The maximum suffix sum occurs in the right child,
In this Case,
Maximum Suffix Sum = Maximum Suffix Sum of Right Child
The maximum suffix sum contains every array element of the Right child and the elements contributing to the maximum suffix sum of the left child,
The maximum suffix sum contains every array element of the Right child and the elements contributing to the maximum suffix sum of the left child,
In this Case,
Maximum Suffix Sum = Total Sum of Right Child +
Maximum Suffix Sum of Left Child
Constructing the Maximum Subarray Sum using Left and Right childThere can be three cases for the maximum sub-array sum of a Node:
The maximum sub-array sum occurs in the left child,
The maximum sub-array sum occurs in the left child,
In this Case,
Maximum Sub-array Sum = Maximum Subarray Sum of Left Child
The maximum sub-array sum occurs in the right child,
The maximum sub-array sum occurs in the right child,
In this Case,
Maximum Sub-array Sum = Maximum Subarray Sum of Right Child
The maximum subarray sum, contains array elements of the right child contributing to the maximum prefix sum of the right child, and the array elements of the Left child contributing to the maximum suffix sum of the left child,
The maximum subarray sum, contains array elements of the right child contributing to the maximum prefix sum of the right child, and the array elements of the Left child contributing to the maximum suffix sum of the left child,
In this Case,
Maximum Subarray Sum = Maximum Prefix Sum of Right Child
+
Maximum Suffix Sum of Left Child
CPP
// C++ Program to Implement Maximum Sub-Array Sum in a range#include <bits/stdc++.h>using namespace std; #define inf 0x3f3f /* Node of the segment tree consisting of:1. Maximum Prefix Sum,2. Maximum Suffix Sum,3. Total Sum,4. Maximum Sub-Array Sum */struct Node { int maxPrefixSum; int maxSuffixSum; int totalSum; int maxSubarraySum; Node() { maxPrefixSum = maxSuffixSum = maxSubarraySum = -inf; totalSum = -inf; }}; // Returns Parent Node after merging its left and right childNode merge(Node leftChild, Node rightChild){ Node parentNode; parentNode.maxPrefixSum = max(leftChild.maxPrefixSum, leftChild.totalSum + rightChild.maxPrefixSum); parentNode.maxSuffixSum = max(rightChild.maxSuffixSum, rightChild.totalSum + leftChild.maxSuffixSum); parentNode.totalSum = leftChild.totalSum + rightChild.totalSum; parentNode.maxSubarraySum = max({leftChild.maxSubarraySum, rightChild.maxSubarraySum, leftChild.maxSuffixSum + rightChild.maxPrefixSum}); return parentNode;} // Builds the Segment tree recursivelyvoid constructTreeUtil(Node* tree, int arr[], int start, int end, int index){ /* Leaf Node */ if (start == end) { // single element is covered under this range tree[index].totalSum = arr[start]; tree[index].maxSuffixSum = arr[start]; tree[index].maxPrefixSum = arr[start]; tree[index].maxSubarraySum = arr[start]; return; } // Recursively Build left and right children int mid = (start + end) / 2; constructTreeUtil(tree, arr, start, mid, 2 * index); constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1); // Merge left and right child into the Parent Node tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructTreeUtil() to fill the allocated memory */Node* constructTree(int arr[], int n){ // Allocate memory for segment tree int x = (int)(ceil(log2(n))); // Height of the tree // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; Node* tree = new Node[max_size]; // Fill the allocated memory tree constructTreeUtil(tree, arr, 0, n - 1, 1); // Return the constructed segment tree return tree;} /* A Recursive function to get the desired Maximum Sum Sub-Array,The following are parameters of the function- tree --> Pointer to segment treeindex --> Index of the segment tree Nodess & se --> Starting and ending indexes of the segment represented by current Node, i.e., tree[index]qs & qe --> Starting and ending indexes of query range */Node queryUtil(Node* tree, int ss, int se, int qs, int qe, int index){ // No overlap if (ss > qe || se < qs) { // returns a Node for out of bounds condition Node nullNode; return nullNode; } // Complete overlap if (ss >= qs && se <= qe) { return tree[index]; } // Partial Overlap Merge results of Left // and Right subtrees int mid = (ss + se) / 2; Node left = queryUtil(tree, ss, mid, qs, qe, 2 * index); Node right = queryUtil(tree, mid + 1, se, qs, qe, 2 * index + 1); // merge left and right subtree query results Node res = merge(left, right); return res;} /* Returns the Maximum Subarray Sum between start and end It mainly uses queryUtil(). */int query(Node* tree, int start, int end, int n){ Node res = queryUtil(tree, 0, n - 1, start, end, 1); return res.maxSubarraySum;} int main(){ int arr[] = { 1, 3, -4, 5, -2 }; int n = sizeof(arr) / sizeof(arr[0]); // Construct Segment Tree Node* Tree = constructTree(arr, n); int start, end, maxSubarraySum; // Answering query 1: start = 0; end = 4; maxSubarraySum = query(Tree, start, end, n); cout << "Maximum Sub-Array Sum between " << start << " and " << end << " = " << maxSubarraySum << "\n"; // Answering query 2: start = 0; end = 2; maxSubarraySum = query(Tree, start, end, n); cout << "Maximum Sub-Array Sum between " << start << " and " << end << " = " << maxSubarraySum << "\n"; return 0;}
Maximum Sub-Array Sum between 0 and 4 = 5
Maximum Sub-Array Sum between 0 and 2 = 4
Time Complexity: O(logn) for each query.
atulim
sagar0719kumar
Segment-Tree
subarray
subarray-sum
Advanced Data Structure
Arrays
Arrays
Segment-Tree
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)
Count of strings whose prefix match with the given string to a given length k
Binary Indexed Tree or Fenwick Tree
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Arrays in C/C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 128,
"s": 52,
"text": "Given an array of n numbers, the task is to answer the following queries: "
},
{
"code": null,
"e": 241,
"s": 128,
"text": "maximumSubarraySum(start, end) : Find the maximum \nsubarray sum in the range from array index 'start' \nto 'end'."
},
{
"code": null,
"e": 296,
"s": 241,
"text": "Also see : Range Query With Update RequiredExamples: "
},
{
"code": null,
"e": 618,
"s": 296,
"text": "Input : arr[] = {1, 3, -4, 5, -2}\n Query 1: start = 0, end = 4\n Query 2: start = 0, end = 2\nOutput : 5\n 4\nExplanation:\nFor Query 1, [1, 3, -4, 5] or ( [5] ) \nrepresent the maximum sum sub arrays \nwith sum = 5.\n\nFor Query 2, [1, 3] represents the \nmaximum sum subarray in the query range\nwith sum = 4"
},
{
"code": null,
"e": 1326,
"s": 618,
"text": "Segment Trees can be used to solve this problem.Here, we need to keep information regarding various cumulative sums.At every Node we store the following: 1) Maximum Prefix Sum, 2) Maximum Suffix Sum, 3) Total Sum, 4) Maximum Subarray SumA classical Segment Tree with each Node storing the above information should be enough to answer each query. The only focus here is on how the left and the right Nodes of the tree are merged together. Now, we will discuss how each of the information is constructed in each of the segment tree Nodes using the information of its left and right child. Constructing the Maximum Prefix Sum using Left and Right childThere can be two cases for maximum prefix sum of a Node: "
},
{
"code": null,
"e": 1377,
"s": 1326,
"text": "The maximum prefix sum occurs in the left child, "
},
{
"code": null,
"e": 1428,
"s": 1377,
"text": "The maximum prefix sum occurs in the left child, "
},
{
"code": null,
"e": 1500,
"s": 1432,
"text": "In this Case,\nMaximum Prefix Sum = Maximum Prefix Sum of Left Child"
},
{
"code": null,
"e": 1648,
"s": 1500,
"text": "The maximum prefix sum contains every array element of the left child and the elements contributing to the maximum prefix sum of the right child, "
},
{
"code": null,
"e": 1796,
"s": 1648,
"text": "The maximum prefix sum contains every array element of the left child and the elements contributing to the maximum prefix sum of the right child, "
},
{
"code": null,
"e": 1911,
"s": 1800,
"text": "In this Case,\nMaximum Prefix Sum = Total Sum of Left Child + \n Maximum Prefix Sum of Right Child"
},
{
"code": null,
"e": 2032,
"s": 1911,
"text": "Constructing the Maximum Suffix Sum using Left and Right childThere can be two cases for maximum suffix sum of a Node: "
},
{
"code": null,
"e": 2084,
"s": 2032,
"text": "The maximum suffix sum occurs in the right child, "
},
{
"code": null,
"e": 2136,
"s": 2084,
"text": "The maximum suffix sum occurs in the right child, "
},
{
"code": null,
"e": 2209,
"s": 2140,
"text": "In this Case,\nMaximum Suffix Sum = Maximum Suffix Sum of Right Child"
},
{
"code": null,
"e": 2357,
"s": 2209,
"text": "The maximum suffix sum contains every array element of the Right child and the elements contributing to the maximum suffix sum of the left child, "
},
{
"code": null,
"e": 2505,
"s": 2357,
"text": "The maximum suffix sum contains every array element of the Right child and the elements contributing to the maximum suffix sum of the left child, "
},
{
"code": null,
"e": 2620,
"s": 2509,
"text": "In this Case,\nMaximum Suffix Sum = Total Sum of Right Child + \n Maximum Suffix Sum of Left Child"
},
{
"code": null,
"e": 2752,
"s": 2620,
"text": "Constructing the Maximum Subarray Sum using Left and Right childThere can be three cases for the maximum sub-array sum of a Node: "
},
{
"code": null,
"e": 2806,
"s": 2752,
"text": "The maximum sub-array sum occurs in the left child, "
},
{
"code": null,
"e": 2860,
"s": 2806,
"text": "The maximum sub-array sum occurs in the left child, "
},
{
"code": null,
"e": 2937,
"s": 2864,
"text": "In this Case,\nMaximum Sub-array Sum = Maximum Subarray Sum of Left Child"
},
{
"code": null,
"e": 2992,
"s": 2937,
"text": "The maximum sub-array sum occurs in the right child, "
},
{
"code": null,
"e": 3047,
"s": 2992,
"text": "The maximum sub-array sum occurs in the right child, "
},
{
"code": null,
"e": 3125,
"s": 3051,
"text": "In this Case,\nMaximum Sub-array Sum = Maximum Subarray Sum of Right Child"
},
{
"code": null,
"e": 3354,
"s": 3125,
"text": "The maximum subarray sum, contains array elements of the right child contributing to the maximum prefix sum of the right child, and the array elements of the Left child contributing to the maximum suffix sum of the left child, "
},
{
"code": null,
"e": 3583,
"s": 3354,
"text": "The maximum subarray sum, contains array elements of the right child contributing to the maximum prefix sum of the right child, and the array elements of the Left child contributing to the maximum suffix sum of the left child, "
},
{
"code": null,
"e": 3794,
"s": 3587,
"text": "In this Case,\nMaximum Subarray Sum = Maximum Prefix Sum of Right Child \n + \n Maximum Suffix Sum of Left Child"
},
{
"code": null,
"e": 3800,
"s": 3796,
"text": "CPP"
},
{
"code": "// C++ Program to Implement Maximum Sub-Array Sum in a range#include <bits/stdc++.h>using namespace std; #define inf 0x3f3f /* Node of the segment tree consisting of:1. Maximum Prefix Sum,2. Maximum Suffix Sum,3. Total Sum,4. Maximum Sub-Array Sum */struct Node { int maxPrefixSum; int maxSuffixSum; int totalSum; int maxSubarraySum; Node() { maxPrefixSum = maxSuffixSum = maxSubarraySum = -inf; totalSum = -inf; }}; // Returns Parent Node after merging its left and right childNode merge(Node leftChild, Node rightChild){ Node parentNode; parentNode.maxPrefixSum = max(leftChild.maxPrefixSum, leftChild.totalSum + rightChild.maxPrefixSum); parentNode.maxSuffixSum = max(rightChild.maxSuffixSum, rightChild.totalSum + leftChild.maxSuffixSum); parentNode.totalSum = leftChild.totalSum + rightChild.totalSum; parentNode.maxSubarraySum = max({leftChild.maxSubarraySum, rightChild.maxSubarraySum, leftChild.maxSuffixSum + rightChild.maxPrefixSum}); return parentNode;} // Builds the Segment tree recursivelyvoid constructTreeUtil(Node* tree, int arr[], int start, int end, int index){ /* Leaf Node */ if (start == end) { // single element is covered under this range tree[index].totalSum = arr[start]; tree[index].maxSuffixSum = arr[start]; tree[index].maxPrefixSum = arr[start]; tree[index].maxSubarraySum = arr[start]; return; } // Recursively Build left and right children int mid = (start + end) / 2; constructTreeUtil(tree, arr, start, mid, 2 * index); constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1); // Merge left and right child into the Parent Node tree[index] = merge(tree[2 * index], tree[2 * index + 1]);} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructTreeUtil() to fill the allocated memory */Node* constructTree(int arr[], int n){ // Allocate memory for segment tree int x = (int)(ceil(log2(n))); // Height of the tree // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; Node* tree = new Node[max_size]; // Fill the allocated memory tree constructTreeUtil(tree, arr, 0, n - 1, 1); // Return the constructed segment tree return tree;} /* A Recursive function to get the desired Maximum Sum Sub-Array,The following are parameters of the function- tree --> Pointer to segment treeindex --> Index of the segment tree Nodess & se --> Starting and ending indexes of the segment represented by current Node, i.e., tree[index]qs & qe --> Starting and ending indexes of query range */Node queryUtil(Node* tree, int ss, int se, int qs, int qe, int index){ // No overlap if (ss > qe || se < qs) { // returns a Node for out of bounds condition Node nullNode; return nullNode; } // Complete overlap if (ss >= qs && se <= qe) { return tree[index]; } // Partial Overlap Merge results of Left // and Right subtrees int mid = (ss + se) / 2; Node left = queryUtil(tree, ss, mid, qs, qe, 2 * index); Node right = queryUtil(tree, mid + 1, se, qs, qe, 2 * index + 1); // merge left and right subtree query results Node res = merge(left, right); return res;} /* Returns the Maximum Subarray Sum between start and end It mainly uses queryUtil(). */int query(Node* tree, int start, int end, int n){ Node res = queryUtil(tree, 0, n - 1, start, end, 1); return res.maxSubarraySum;} int main(){ int arr[] = { 1, 3, -4, 5, -2 }; int n = sizeof(arr) / sizeof(arr[0]); // Construct Segment Tree Node* Tree = constructTree(arr, n); int start, end, maxSubarraySum; // Answering query 1: start = 0; end = 4; maxSubarraySum = query(Tree, start, end, n); cout << \"Maximum Sub-Array Sum between \" << start << \" and \" << end << \" = \" << maxSubarraySum << \"\\n\"; // Answering query 2: start = 0; end = 2; maxSubarraySum = query(Tree, start, end, n); cout << \"Maximum Sub-Array Sum between \" << start << \" and \" << end << \" = \" << maxSubarraySum << \"\\n\"; return 0;}",
"e": 8433,
"s": 3800,
"text": null
},
{
"code": null,
"e": 8517,
"s": 8433,
"text": "Maximum Sub-Array Sum between 0 and 4 = 5\nMaximum Sub-Array Sum between 0 and 2 = 4"
},
{
"code": null,
"e": 8561,
"s": 8519,
"text": "Time Complexity: O(logn) for each query. "
},
{
"code": null,
"e": 8568,
"s": 8561,
"text": "atulim"
},
{
"code": null,
"e": 8583,
"s": 8568,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 8596,
"s": 8583,
"text": "Segment-Tree"
},
{
"code": null,
"e": 8605,
"s": 8596,
"text": "subarray"
},
{
"code": null,
"e": 8618,
"s": 8605,
"text": "subarray-sum"
},
{
"code": null,
"e": 8642,
"s": 8618,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 8649,
"s": 8642,
"text": "Arrays"
},
{
"code": null,
"e": 8656,
"s": 8649,
"text": "Arrays"
},
{
"code": null,
"e": 8669,
"s": 8656,
"text": "Segment-Tree"
},
{
"code": null,
"e": 8767,
"s": 8669,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8801,
"s": 8767,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 8841,
"s": 8801,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 8883,
"s": 8841,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 8961,
"s": 8883,
"text": "Count of strings whose prefix match with the given string to a given length k"
},
{
"code": null,
"e": 8997,
"s": 8961,
"text": "Binary Indexed Tree or Fenwick Tree"
},
{
"code": null,
"e": 9012,
"s": 8997,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9058,
"s": 9012,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 9126,
"s": 9058,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9170,
"s": 9126,
"text": "Top 50 Array Coding Problems for Interviews"
}
] |
Google Interview Experience | Set 7 (For Software Engineering Intern)
|
03 Dec, 2017
Round 1: Coding Sample
In this coding sample, I was given 90 minutes to answer 2 coding questions.
Question 1: Given a string A consisting of n characters and a string B consisting of m characters, write a function that will return the number of times A must be stated such that B is a substring of the repeated A. If B can never be a substring, return -1.
Example:A = βabcdβB = βcdabcdabβThe function should return 3 because after stating A 3 times, getting βabcdabcdabcdβ, B is now a substring of A.
You can assume that n and m are integers in the range [1, 1000].
Question 2: Consider an undirected tree with N nodes, numbered from 1 to N. Each node has a label associated with it, which is an integer value. Different nodes can have the same label. Write a function that, given a zero indexed array A of length N, where A[j] is the label value of the (j + 1)-th node in the tree and a zero-indexed array E of length K = (N β 1) * 2 in which the edges of the tree are described, returns the length of the longest path such that all the nodes on that path have the same label. The length is the number of edges in that path.
Example:
A = [1, 1, 1, 2, 2]E = [1, 2, 1, 3, 2, 4, 2, 5]
This tree is shown below. A node follows the form label, value.
----------1, 1
-----1, 2 1, 3
2, 4 2, 5
The function should return 2, because the longest path is 2->1->3, and there are 2 edges in this path.
Assume that 1 <= N <= 1000 and each element of the array A is an integer in the range [1, 1000000000].
Round 2: Phone Interview
In this phone interview I was given one question.
Question: Write a function that takes a list L and returns a random sublist of size N of that list. Assume that the indexes must be in increasing order. That is, you cannot go backwards.
Example:
L = [1, 2, 3, 4, 5]N = 3
The function should return one of these lists:
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
Round 3: Phone Interview
I was again asked only one question.
Question: Given a list L of video names and their watch rates, write a function that will return the videos with the top 10 watch rates. Video names may appear more than once.
Example:
L = [(βabcβ, 10), (βdefβ, 15), (βghiβ, 10), (βabcβ, 12), ..., (βxyzβ, 100)]
The function should return [βxyzβ, βabcβ, ..., βdefβ, βghiβ]Experience:
I solved all the questions but, unfortunately, I was not selected. Though I was not selected, I had a very positive experience. My interviewers and recruiters were all pleasant to work with. I will definitely try again next year and hopefully, I will clear it and get selected for a full time job.
Tips for Interview:
Ask questions. The interviewer will purposely give you a vague question in hopes of you asking the necessary questions to clarify it for yourself.
Donβt panic. I know it can be nerve racking to go on an interview, especially if itβs your first. But, nerves are only going to make it worse. Collect yourself, and if you donβt know the answer, itβs okay. Think through it for a few minutes and Iβm sure anyone can come up with a solution. These questions are designed for you to be able to solve in the allocated time for an interview.
THINK OUT LOUD! I canβt stress this one enough. You are also being judged on your thought process. If your interviewer doesnβt know what you are thinking, they canβt throw you hints or correct you in any way. And believe me, they want to see you succeed. They are there to help you and guide you through the problem.
Other than that, study, study, study. Do as many algorithmically challenging problems as you can. Cracking the Coding Interview and Geeks for Geeks will be your best friends through the study process. Take advantage of these resources.
Google
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Dec, 2017"
},
{
"code": null,
"e": 77,
"s": 54,
"text": "Round 1: Coding Sample"
},
{
"code": null,
"e": 153,
"s": 77,
"text": "In this coding sample, I was given 90 minutes to answer 2 coding questions."
},
{
"code": null,
"e": 411,
"s": 153,
"text": "Question 1: Given a string A consisting of n characters and a string B consisting of m characters, write a function that will return the number of times A must be stated such that B is a substring of the repeated A. If B can never be a substring, return -1."
},
{
"code": null,
"e": 556,
"s": 411,
"text": "Example:A = βabcdβB = βcdabcdabβThe function should return 3 because after stating A 3 times, getting βabcdabcdabcdβ, B is now a substring of A."
},
{
"code": null,
"e": 621,
"s": 556,
"text": "You can assume that n and m are integers in the range [1, 1000]."
},
{
"code": null,
"e": 1183,
"s": 623,
"text": "Question 2: Consider an undirected tree with N nodes, numbered from 1 to N. Each node has a label associated with it, which is an integer value. Different nodes can have the same label. Write a function that, given a zero indexed array A of length N, where A[j] is the label value of the (j + 1)-th node in the tree and a zero-indexed array E of length K = (N β 1) * 2 in which the edges of the tree are described, returns the length of the longest path such that all the nodes on that path have the same label. The length is the number of edges in that path."
},
{
"code": null,
"e": 1192,
"s": 1183,
"text": "Example:"
},
{
"code": null,
"e": 1240,
"s": 1192,
"text": "A = [1, 1, 1, 2, 2]E = [1, 2, 1, 3, 2, 4, 2, 5]"
},
{
"code": null,
"e": 1304,
"s": 1240,
"text": "This tree is shown below. A node follows the form label, value."
},
{
"code": null,
"e": 1358,
"s": 1304,
"text": "----------1, 1\n\n-----1, 2 1, 3\n\n2, 4 2, 5"
},
{
"code": null,
"e": 1461,
"s": 1358,
"text": "The function should return 2, because the longest path is 2->1->3, and there are 2 edges in this path."
},
{
"code": null,
"e": 1564,
"s": 1461,
"text": "Assume that 1 <= N <= 1000 and each element of the array A is an integer in the range [1, 1000000000]."
},
{
"code": null,
"e": 1591,
"s": 1566,
"text": "Round 2: Phone Interview"
},
{
"code": null,
"e": 1641,
"s": 1591,
"text": "In this phone interview I was given one question."
},
{
"code": null,
"e": 1828,
"s": 1641,
"text": "Question: Write a function that takes a list L and returns a random sublist of size N of that list. Assume that the indexes must be in increasing order. That is, you cannot go backwards."
},
{
"code": null,
"e": 1837,
"s": 1828,
"text": "Example:"
},
{
"code": null,
"e": 1862,
"s": 1837,
"text": "L = [1, 2, 3, 4, 5]N = 3"
},
{
"code": null,
"e": 1909,
"s": 1862,
"text": "The function should return one of these lists:"
},
{
"code": null,
"e": 2009,
"s": 1909,
"text": "[1, 2, 3]\n[1, 2, 4]\n[1, 2, 5]\n[1, 3, 4]\n[1, 3, 5]\n[1, 4, 5]\n[2, 3, 4]\n[2, 3, 5]\n[2, 4, 5]\n[3, 4, 5]"
},
{
"code": null,
"e": 2036,
"s": 2011,
"text": "Round 3: Phone Interview"
},
{
"code": null,
"e": 2073,
"s": 2036,
"text": "I was again asked only one question."
},
{
"code": null,
"e": 2249,
"s": 2073,
"text": "Question: Given a list L of video names and their watch rates, write a function that will return the videos with the top 10 watch rates. Video names may appear more than once."
},
{
"code": null,
"e": 2258,
"s": 2249,
"text": "Example:"
},
{
"code": null,
"e": 2334,
"s": 2258,
"text": "L = [(βabcβ, 10), (βdefβ, 15), (βghiβ, 10), (βabcβ, 12), ..., (βxyzβ, 100)]"
},
{
"code": null,
"e": 2406,
"s": 2334,
"text": "The function should return [βxyzβ, βabcβ, ..., βdefβ, βghiβ]Experience:"
},
{
"code": null,
"e": 2704,
"s": 2406,
"text": "I solved all the questions but, unfortunately, I was not selected. Though I was not selected, I had a very positive experience. My interviewers and recruiters were all pleasant to work with. I will definitely try again next year and hopefully, I will clear it and get selected for a full time job."
},
{
"code": null,
"e": 2726,
"s": 2706,
"text": "Tips for Interview:"
},
{
"code": null,
"e": 2873,
"s": 2726,
"text": "Ask questions. The interviewer will purposely give you a vague question in hopes of you asking the necessary questions to clarify it for yourself."
},
{
"code": null,
"e": 3260,
"s": 2873,
"text": "Donβt panic. I know it can be nerve racking to go on an interview, especially if itβs your first. But, nerves are only going to make it worse. Collect yourself, and if you donβt know the answer, itβs okay. Think through it for a few minutes and Iβm sure anyone can come up with a solution. These questions are designed for you to be able to solve in the allocated time for an interview."
},
{
"code": null,
"e": 3577,
"s": 3260,
"text": "THINK OUT LOUD! I canβt stress this one enough. You are also being judged on your thought process. If your interviewer doesnβt know what you are thinking, they canβt throw you hints or correct you in any way. And believe me, they want to see you succeed. They are there to help you and guide you through the problem."
},
{
"code": null,
"e": 3813,
"s": 3577,
"text": "Other than that, study, study, study. Do as many algorithmically challenging problems as you can. Cracking the Coding Interview and Geeks for Geeks will be your best friends through the study process. Take advantage of these resources."
},
{
"code": null,
"e": 3820,
"s": 3813,
"text": "Google"
},
{
"code": null,
"e": 3831,
"s": 3820,
"text": "Internship"
},
{
"code": null,
"e": 3853,
"s": 3831,
"text": "Interview Experiences"
},
{
"code": null,
"e": 3860,
"s": 3853,
"text": "Google"
}
] |
C# | LinkedList Class
|
20 Dec, 2018
LinkedList<T> Class is present in System.Collections.Generic namespace. This generic type allows fast inserting and removing of elements. It implements a classic linked list. Each object is separately allocated. In the LinkedList, certain operations do not require the whole collection to be copied. But in many common cases LinkedList hinders performance.
Characteristics of LinkedList Class:
LinkedList<T> is a general-purpose linked list. It supports enumerators.
Insertion and removal are O(1) operations.
You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional objects allocated on the heap.
Because the list also maintains an internal count, getting the Count property is an O(1) operation.
Each node in a LinkedList<T> object is of the type LinkedListNode<T>.
The LinkedList class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.
If the LinkedList is empty, the First and Last properties contain null.
The LinkedList is doubly linked, therefore, each node points forward to the Next node and backward to the Previous node.
Example:
// C# code to create a LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("Geeks"); myList.AddLast("for"); myList.AddLast("Data Structures"); myList.AddLast("Noida"); // To check if LinkedList is empty or not if (myList.Count > 0) Console.WriteLine("LinkedList is not empty"); else Console.WriteLine("LinkedList is empty"); }}
Output:
LinkedList is not empty
Example:
// C# code to illustrate the// LinkedList<T> class propertiesusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("GeeksforGeeks"); myList.AddLast("GFG"); myList.AddLast("Data Structures"); myList.AddLast("Noida"); // ------- Count Property ------- // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine("LinkedList is empty"); // ------- Last Property ------- // To get the last node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Last.Value); else Console.WriteLine("LinkedList is empty"); }}
Output:
GeeksforGeeks
Noida
Example:
// C# code to check if a// value is in LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast("A"); myList.AddLast("B"); myList.AddLast("C"); myList.AddLast("D"); myList.AddLast("E"); // To check if a value is in LinkedList Console.WriteLine(myList.Contains("B")); }}
Output:
True
Example:
// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Removing the first node from the LinkedList myList.Remove(myList.First); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine("Total nodes in myList are : " + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}
Output:
Total nodes in myList are : 4
2
4
6
8
Total nodes in myList are : 3
4
6
8
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.7.2
CSharp-Generic-Namespace
CSharp-LinkedList
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Encapsulation
C# | Replace() Method
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Dec, 2018"
},
{
"code": null,
"e": 410,
"s": 53,
"text": "LinkedList<T> Class is present in System.Collections.Generic namespace. This generic type allows fast inserting and removing of elements. It implements a classic linked list. Each object is separately allocated. In the LinkedList, certain operations do not require the whole collection to be copied. But in many common cases LinkedList hinders performance."
},
{
"code": null,
"e": 447,
"s": 410,
"text": "Characteristics of LinkedList Class:"
},
{
"code": null,
"e": 520,
"s": 447,
"text": "LinkedList<T> is a general-purpose linked list. It supports enumerators."
},
{
"code": null,
"e": 563,
"s": 520,
"text": "Insertion and removal are O(1) operations."
},
{
"code": null,
"e": 709,
"s": 563,
"text": "You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional objects allocated on the heap."
},
{
"code": null,
"e": 809,
"s": 709,
"text": "Because the list also maintains an internal count, getting the Count property is an O(1) operation."
},
{
"code": null,
"e": 879,
"s": 809,
"text": "Each node in a LinkedList<T> object is of the type LinkedListNode<T>."
},
{
"code": null,
"e": 1014,
"s": 879,
"text": "The LinkedList class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state."
},
{
"code": null,
"e": 1086,
"s": 1014,
"text": "If the LinkedList is empty, the First and Last properties contain null."
},
{
"code": null,
"e": 1207,
"s": 1086,
"text": "The LinkedList is doubly linked, therefore, each node points forward to the Next node and backward to the Previous node."
},
{
"code": null,
"e": 1216,
"s": 1207,
"text": "Example:"
},
{
"code": "// C# code to create a LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"Geeks\"); myList.AddLast(\"for\"); myList.AddLast(\"Data Structures\"); myList.AddLast(\"Noida\"); // To check if LinkedList is empty or not if (myList.Count > 0) Console.WriteLine(\"LinkedList is not empty\"); else Console.WriteLine(\"LinkedList is empty\"); }}",
"e": 1877,
"s": 1216,
"text": null
},
{
"code": null,
"e": 1885,
"s": 1877,
"text": "Output:"
},
{
"code": null,
"e": 1910,
"s": 1885,
"text": "LinkedList is not empty\n"
},
{
"code": null,
"e": 1919,
"s": 1910,
"text": "Example:"
},
{
"code": "// C# code to illustrate the// LinkedList<T> class propertiesusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"GeeksforGeeks\"); myList.AddLast(\"GFG\"); myList.AddLast(\"Data Structures\"); myList.AddLast(\"Noida\"); // ------- Count Property ------- // To get the first node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.First.Value); else Console.WriteLine(\"LinkedList is empty\"); // ------- Last Property ------- // To get the last node of the LinkedList if (myList.Count > 0) Console.WriteLine(myList.Last.Value); else Console.WriteLine(\"LinkedList is empty\"); }}",
"e": 2935,
"s": 1919,
"text": null
},
{
"code": null,
"e": 2943,
"s": 2935,
"text": "Output:"
},
{
"code": null,
"e": 2964,
"s": 2943,
"text": "GeeksforGeeks\nNoida\n"
},
{
"code": null,
"e": 2973,
"s": 2964,
"text": "Example:"
},
{
"code": "// C# code to check if a// value is in LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Strings LinkedList<String> myList = new LinkedList<String>(); // Adding nodes in LinkedList myList.AddLast(\"A\"); myList.AddLast(\"B\"); myList.AddLast(\"C\"); myList.AddLast(\"D\"); myList.AddLast(\"E\"); // To check if a value is in LinkedList Console.WriteLine(myList.Contains(\"B\")); }}",
"e": 3547,
"s": 2973,
"text": null
},
{
"code": null,
"e": 3555,
"s": 3547,
"text": "Output:"
},
{
"code": null,
"e": 3561,
"s": 3555,
"text": "True\n"
},
{
"code": null,
"e": 3570,
"s": 3561,
"text": "Example:"
},
{
"code": "// C# code to remove the specified// node from the LinkedListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a LinkedList of Integers LinkedList<int> myList = new LinkedList<int>(); // Adding nodes in LinkedList myList.AddLast(2); myList.AddLast(4); myList.AddLast(6); myList.AddLast(8); // To get the count of nodes in LinkedList // before removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } // Removing the first node from the LinkedList myList.Remove(myList.First); // To get the count of nodes in LinkedList // after removing all the nodes Console.WriteLine(\"Total nodes in myList are : \" + myList.Count); // Displaying the nodes in LinkedList foreach(int i in myList) { Console.WriteLine(i); } }}",
"e": 4701,
"s": 3570,
"text": null
},
{
"code": null,
"e": 4709,
"s": 4701,
"text": "Output:"
},
{
"code": null,
"e": 4784,
"s": 4709,
"text": "Total nodes in myList are : 4\n2\n4\n6\n8\nTotal nodes in myList are : 3\n4\n6\n8\n"
},
{
"code": null,
"e": 4795,
"s": 4784,
"text": "Reference:"
},
{
"code": null,
"e": 4903,
"s": 4795,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.7.2"
},
{
"code": null,
"e": 4928,
"s": 4903,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 4946,
"s": 4928,
"text": "CSharp-LinkedList"
},
{
"code": null,
"e": 4949,
"s": 4946,
"text": "C#"
},
{
"code": null,
"e": 5047,
"s": 4949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5078,
"s": 5047,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 5093,
"s": 5078,
"text": "C# | Delegates"
},
{
"code": null,
"e": 5136,
"s": 5093,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 5185,
"s": 5136,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 5201,
"s": 5185,
"text": "C# | Data Types"
},
{
"code": null,
"e": 5219,
"s": 5201,
"text": "C# | Constructors"
},
{
"code": null,
"e": 5241,
"s": 5219,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 5264,
"s": 5241,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 5283,
"s": 5264,
"text": "C# | Encapsulation"
}
] |
Highly Composite Numbers
|
23 Mar, 2021
A number N is called highly composite if it has more divisors than any of the smaller numbers than N.Few Highly composite numbers are:
1, 2, 4, 6, 12, 24, 36, 48, 60, 120....
Given a number N, the task is to check if N is a Highly Composite Number or not. If N is a Highly Composite Number than print βYesβ else print βNoβ.Examples:
Input: N = 60 Output: Yes 60 is a highly composite because it has 12 divisors and none of the numbers up to 59 has 12 or more divisors.
Input: N = 18 Output: No
Approach:
Find the count of divisors of NNow in a loop from 1 to less than N, check for every i that if a number of divisors of i are more than the count of divisors of N, then return falseOtherwise, return true at the end.
Find the count of divisors of N
Now in a loop from 1 to less than N, check for every i that if a number of divisors of i are more than the count of divisors of N, then return false
Otherwise, return true at the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation for checking// Highly Composite Number #include <bits/stdc++.h>using namespace std; // Function to count the number// of divisors of the Nint divCount(int n){ // sieve method for prime calculation bool hash[n + 1]; memset(hash, true, sizeof(hash)); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberbool isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codeint main(){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation for checking// Highly Composite Numberimport java.util.*;class GFG{ // Function to count the number// of divisors of the Nstatic int divCount(int n){ // sieve method for prime calculation boolean []hash = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberstatic boolean isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codepublic static void main(String[] args){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by gauravrajput1
# Python3 implementation for checking# Highly Composite Number # Function to count the number# of divisors of the Ndef divCount(n): # Sieve method for prime calculation Hash = [True for i in range(n + 1)] p = 2 while ((p * p) < n): if bool(Hash[p]): i = p * 2 while i < n: Hash[i] = False i += p p += 1 # Traversing through # all prime numbers total = 1 for P in range(2, n + 1): if (bool(Hash[P])): # Calculate number of divisor # with formula total div = # (p1+1) * (p2+1) *.....* (pn+1) # where n = (a1^p1)*(a2^p2).... # *(an^pn) ai being prime divisor # for n and pi are their respective # power in factorization count = 0 if (n % P == 0): while (n % P == 0): n = n // P count += 1 total = total * (count + 1) return total # Function to check if a number# is a highly composite numberdef isHighlyCompositeNumber(N): # Count number of factors of N NdivCount = divCount(N) # Loop to count number of factors of # every number less than N for i in range(N): idivCount = divCount(i) # If any number less than N has # more factors than N, # then return false if (idivCount >= NdivCount): return bool(False) return bool(True) # Driver code # Given Number NN = 12 # Function Callif (bool(isHighlyCompositeNumber(N))): print("Yes")else: print("No") # This code is contributed by divyeshrabadiya07
// C# implementation for checking// Highly Composite Numberusing System;class GFG{ // Function to count the number// of divisors of the Nstatic int divCount(int n){ // sieve method for prime calculation bool []hash = new bool[n + 1]; for(int i = 0; i < n + 1; i++) hash[i] = true; for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberstatic bool isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codepublic static void Main(String[] args){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by shikhasingrajput
<script> // Javascript implementation for checking// Highly Composite Number // Function to count the number // of divisors of the N function divCount( n) { // sieve method for prime calculation let hash = Array(n+1).fill(true); for ( let p = 2; p * p < n; p++) if (hash[p] == true) for ( i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers let total = 1; for ( p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization let count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } // Function to check if a number // is a highly composite number function isHighlyCompositeNumber( N) { // count number of factors of N let NdivCount = divCount(N); // loop to count number of factors of // every number less than N for ( let i = 1; i < N; i++) { let idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true; } // Driver code // Given Number N let N = 12; // Function Call if (isHighlyCompositeNumber(N)) document.write("Yes"); else document.write("No"); // This code contributed by Rajput-Ji </script>
Yes
Time Complexity: O(n) Reference: http://www.numbersaplenty.com/set/highly_composite_number/
GauravRajput1
shikhasingrajput
divyeshrabadiya07
Rajput-Ji
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Check if a number is Palindrome
Count ways to reach the n'th stair
Product of Array except itself
Find Union and Intersection of two unsorted arrays
Median of two sorted arrays of same size
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Mar, 2021"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "A number N is called highly composite if it has more divisors than any of the smaller numbers than N.Few Highly composite numbers are: "
},
{
"code": null,
"e": 207,
"s": 165,
"text": "1, 2, 4, 6, 12, 24, 36, 48, 60, 120.... "
},
{
"code": null,
"e": 367,
"s": 207,
"text": "Given a number N, the task is to check if N is a Highly Composite Number or not. If N is a Highly Composite Number than print βYesβ else print βNoβ.Examples: "
},
{
"code": null,
"e": 503,
"s": 367,
"text": "Input: N = 60 Output: Yes 60 is a highly composite because it has 12 divisors and none of the numbers up to 59 has 12 or more divisors."
},
{
"code": null,
"e": 530,
"s": 503,
"text": "Input: N = 18 Output: No "
},
{
"code": null,
"e": 542,
"s": 530,
"text": "Approach: "
},
{
"code": null,
"e": 756,
"s": 542,
"text": "Find the count of divisors of NNow in a loop from 1 to less than N, check for every i that if a number of divisors of i are more than the count of divisors of N, then return falseOtherwise, return true at the end."
},
{
"code": null,
"e": 788,
"s": 756,
"text": "Find the count of divisors of N"
},
{
"code": null,
"e": 937,
"s": 788,
"text": "Now in a loop from 1 to less than N, check for every i that if a number of divisors of i are more than the count of divisors of N, then return false"
},
{
"code": null,
"e": 972,
"s": 937,
"text": "Otherwise, return true at the end."
},
{
"code": null,
"e": 1024,
"s": 972,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1028,
"s": 1024,
"text": "C++"
},
{
"code": null,
"e": 1033,
"s": 1028,
"text": "Java"
},
{
"code": null,
"e": 1041,
"s": 1033,
"text": "Python3"
},
{
"code": null,
"e": 1044,
"s": 1041,
"text": "C#"
},
{
"code": null,
"e": 1055,
"s": 1044,
"text": "Javascript"
},
{
"code": "// C++ implementation for checking// Highly Composite Number #include <bits/stdc++.h>using namespace std; // Function to count the number// of divisors of the Nint divCount(int n){ // sieve method for prime calculation bool hash[n + 1]; memset(hash, true, sizeof(hash)); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberbool isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codeint main(){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 2832,
"s": 1055,
"text": null
},
{
"code": "// Java implementation for checking// Highly Composite Numberimport java.util.*;class GFG{ // Function to count the number// of divisors of the Nstatic int divCount(int n){ // sieve method for prime calculation boolean []hash = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberstatic boolean isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codepublic static void main(String[] args){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by gauravrajput1",
"e": 4748,
"s": 2832,
"text": null
},
{
"code": "# Python3 implementation for checking# Highly Composite Number # Function to count the number# of divisors of the Ndef divCount(n): # Sieve method for prime calculation Hash = [True for i in range(n + 1)] p = 2 while ((p * p) < n): if bool(Hash[p]): i = p * 2 while i < n: Hash[i] = False i += p p += 1 # Traversing through # all prime numbers total = 1 for P in range(2, n + 1): if (bool(Hash[P])): # Calculate number of divisor # with formula total div = # (p1+1) * (p2+1) *.....* (pn+1) # where n = (a1^p1)*(a2^p2).... # *(an^pn) ai being prime divisor # for n and pi are their respective # power in factorization count = 0 if (n % P == 0): while (n % P == 0): n = n // P count += 1 total = total * (count + 1) return total # Function to check if a number# is a highly composite numberdef isHighlyCompositeNumber(N): # Count number of factors of N NdivCount = divCount(N) # Loop to count number of factors of # every number less than N for i in range(N): idivCount = divCount(i) # If any number less than N has # more factors than N, # then return false if (idivCount >= NdivCount): return bool(False) return bool(True) # Driver code # Given Number NN = 12 # Function Callif (bool(isHighlyCompositeNumber(N))): print(\"Yes\")else: print(\"No\") # This code is contributed by divyeshrabadiya07",
"e": 6458,
"s": 4748,
"text": null
},
{
"code": "// C# implementation for checking// Highly Composite Numberusing System;class GFG{ // Function to count the number// of divisors of the Nstatic int divCount(int n){ // sieve method for prime calculation bool []hash = new bool[n + 1]; for(int i = 0; i < n + 1; i++) hash[i] = true; for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total;} // Function to check if a number// is a highly composite numberstatic bool isHighlyCompositeNumber(int N){ // count number of factors of N int NdivCount = divCount(N); // loop to count number of factors of // every number less than N for (int i = 1; i < N; i++) { int idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true;} // Driver codepublic static void Main(String[] args){ // Given Number N int N = 12; // Function Call if (isHighlyCompositeNumber(N)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by shikhasingrajput",
"e": 8383,
"s": 6458,
"text": null
},
{
"code": "<script> // Javascript implementation for checking// Highly Composite Number // Function to count the number // of divisors of the N function divCount( n) { // sieve method for prime calculation let hash = Array(n+1).fill(true); for ( let p = 2; p * p < n; p++) if (hash[p] == true) for ( i = p * 2; i < n; i += p) hash[i] = false; // Traversing through // all prime numbers let total = 1; for ( p = 2; p <= n; p++) { if (hash[p]) { // calculate number of divisor // with formula total div = // (p1+1) * (p2+1) *.....* (pn+1) // where n = (a1^p1)*(a2^p2).... // *(an^pn) ai being prime divisor // for n and pi are their respective // power in factorization let count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } // Function to check if a number // is a highly composite number function isHighlyCompositeNumber( N) { // count number of factors of N let NdivCount = divCount(N); // loop to count number of factors of // every number less than N for ( let i = 1; i < N; i++) { let idivCount = divCount(i); // If any number less than N has // more factors than N, // then return false if (idivCount >= NdivCount) return false; } return true; } // Driver code // Given Number N let N = 12; // Function Call if (isHighlyCompositeNumber(N)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by Rajput-Ji </script>",
"e": 10397,
"s": 8383,
"text": null
},
{
"code": null,
"e": 10401,
"s": 10397,
"text": "Yes"
},
{
"code": null,
"e": 10496,
"s": 10403,
"text": "Time Complexity: O(n) Reference: http://www.numbersaplenty.com/set/highly_composite_number/ "
},
{
"code": null,
"e": 10512,
"s": 10498,
"text": "GauravRajput1"
},
{
"code": null,
"e": 10529,
"s": 10512,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 10547,
"s": 10529,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10557,
"s": 10547,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10564,
"s": 10557,
"text": "series"
},
{
"code": null,
"e": 10577,
"s": 10564,
"text": "Mathematical"
},
{
"code": null,
"e": 10590,
"s": 10577,
"text": "Mathematical"
},
{
"code": null,
"e": 10597,
"s": 10590,
"text": "series"
},
{
"code": null,
"e": 10695,
"s": 10597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10727,
"s": 10695,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 10771,
"s": 10727,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 10817,
"s": 10771,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 10859,
"s": 10817,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 10884,
"s": 10859,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 10916,
"s": 10884,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 10951,
"s": 10916,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 10982,
"s": 10951,
"text": "Product of Array except itself"
},
{
"code": null,
"e": 11033,
"s": 10982,
"text": "Find Union and Intersection of two unsorted arrays"
}
] |
CSS | animation-iteration-count Property
|
06 Aug, 2019
The animation-iteration-count property in CSS is used to specify the number of times the animation will be repeated. It can specify as infinite to repeat the animation indefinitely.
Syntax:
animation-iteration-count: number|infinite|initial|inherit;
Property Value:
number: This property value is used to define the number of times an animation should be played. The default value is 1.
infinite: This property value specifies that the animation should be played infinite times (for ever).
initial: This property value is used to set this property to its default value.
inherit: This value is used to inherit this property from its parent element.
Example: HTML program to illustrate animation-iteration-count
<!DOCTYPE html> <html> <head> <title> CSS | animation-iteration-count Property </title> <style> .geeks { font-size: 40px; text-align:center; font-weight:bold; color:#090; padding-bottom:5px; font-family:Times New Roman; } .geeks1 { font-size:17px; font-weight:bold; text-align:center; font-family:Times New Roman; } #one { animation-name: example; animation-duration: 2s; /* Animation will be repeated twice */ animation-iteration-count: 2; } #two { animation-name: example; animation-duration: 2s; /* Animation will be repeated infinitely */ animation-iteration-count: infinite; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style> </head> <body> <div class = "geeks"> GeeksforGeeks </div> <div class = "geeks1"> A computer science portal for geeks </div> <!-- Animation of the text inside the h2 tag below will be repeated twice only --> <h2 id="one"> This text changes its color two times. </h2> <!-- Animation of the text inside the h2 tag below will be repeated infinitely --> <h2 id="two"> This text changes its color infinite times. </h2> </body> </html>
Supported Browser: The browser supported by animation-iteration-count property are listed below:
Google Chrome 43.0
Internet Explorer 10.0
Firefox 16.0
Opera 30.0
Safari 9.0
CSS-Properties
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
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": 28,
"s": 0,
"text": "\n06 Aug, 2019"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "The animation-iteration-count property in CSS is used to specify the number of times the animation will be repeated. It can specify as infinite to repeat the animation indefinitely."
},
{
"code": null,
"e": 218,
"s": 210,
"text": "Syntax:"
},
{
"code": null,
"e": 278,
"s": 218,
"text": "animation-iteration-count: number|infinite|initial|inherit;"
},
{
"code": null,
"e": 294,
"s": 278,
"text": "Property Value:"
},
{
"code": null,
"e": 415,
"s": 294,
"text": "number: This property value is used to define the number of times an animation should be played. The default value is 1."
},
{
"code": null,
"e": 518,
"s": 415,
"text": "infinite: This property value specifies that the animation should be played infinite times (for ever)."
},
{
"code": null,
"e": 598,
"s": 518,
"text": "initial: This property value is used to set this property to its default value."
},
{
"code": null,
"e": 676,
"s": 598,
"text": "inherit: This value is used to inherit this property from its parent element."
},
{
"code": null,
"e": 738,
"s": 676,
"text": "Example: HTML program to illustrate animation-iteration-count"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> CSS | animation-iteration-count Property </title> <style> .geeks { font-size: 40px; text-align:center; font-weight:bold; color:#090; padding-bottom:5px; font-family:Times New Roman; } .geeks1 { font-size:17px; font-weight:bold; text-align:center; font-family:Times New Roman; } #one { animation-name: example; animation-duration: 2s; /* Animation will be repeated twice */ animation-iteration-count: 2; } #two { animation-name: example; animation-duration: 2s; /* Animation will be repeated infinitely */ animation-iteration-count: infinite; } @keyframes example { from { background-color: orange; } to { background-color: white; } } </style> </head> <body> <div class = \"geeks\"> GeeksforGeeks </div> <div class = \"geeks1\"> A computer science portal for geeks </div> <!-- Animation of the text inside the h2 tag below will be repeated twice only --> <h2 id=\"one\"> This text changes its color two times. </h2> <!-- Animation of the text inside the h2 tag below will be repeated infinitely --> <h2 id=\"two\"> This text changes its color infinite times. </h2> </body> </html> ",
"e": 2722,
"s": 738,
"text": null
},
{
"code": null,
"e": 2819,
"s": 2722,
"text": "Supported Browser: The browser supported by animation-iteration-count property are listed below:"
},
{
"code": null,
"e": 2838,
"s": 2819,
"text": "Google Chrome 43.0"
},
{
"code": null,
"e": 2861,
"s": 2838,
"text": "Internet Explorer 10.0"
},
{
"code": null,
"e": 2874,
"s": 2861,
"text": "Firefox 16.0"
},
{
"code": null,
"e": 2885,
"s": 2874,
"text": "Opera 30.0"
},
{
"code": null,
"e": 2896,
"s": 2885,
"text": "Safari 9.0"
},
{
"code": null,
"e": 2911,
"s": 2896,
"text": "CSS-Properties"
},
{
"code": null,
"e": 2915,
"s": 2911,
"text": "CSS"
},
{
"code": null,
"e": 2920,
"s": 2915,
"text": "HTML"
},
{
"code": null,
"e": 2937,
"s": 2920,
"text": "Web Technologies"
},
{
"code": null,
"e": 2942,
"s": 2937,
"text": "HTML"
},
{
"code": null,
"e": 3040,
"s": 2942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3088,
"s": 3040,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3150,
"s": 3088,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3200,
"s": 3150,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3258,
"s": 3200,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 3308,
"s": 3258,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3356,
"s": 3308,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3418,
"s": 3356,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3468,
"s": 3418,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3492,
"s": 3468,
"text": "REST API (Introduction)"
}
] |
Dynamically Resize Buttons When Resizing a Window using Tkinter
|
04 Sep, 2021
Prerequisite: Python GUI β tkinter
Button size is static, which means the size of a button cannot be changed once it is defined by the user. The problem here is while resizing the window size, it can affect the button size problem. So the solution here is, make a dynamic button, which means the button size will change as per window size.
Letβs understand with step-by-step implementation:
Step 1#: Create Normal Tkinter Window
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop()
Output:-
Step 2#: Add Buttons and set the grid.
Syntax:
Button(Object Name,text="Enter Text")
What is grid?
The grid() geometry manager organizes widgets in a table-like structure in the parent widget. The master widget is split into rows and columns, and each part of the table can hold a widget. It uses column, column span, ipadx, ipady, padx, pady, row, row span, and sticky.
Syntax:
Object_name.grid(row=row value,column=column value,**attributes)
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("500x500") # Create Buttonsbutton_1 = Button(root,text="Button 1")button_2 = Button(root,text="Button 2") # Set gridbutton_1.grid(row=0,column=0)button_2.grid(row=1,column=0) # Execute tkinterroot.mainloop()
Output:
Add Two Buttons
Step 3#: Set Columnconfigure & Rowconfigure for resize.
For the user interface to resize then, weβll need to specify a positive weight to the columns that weβd like to expand. This is done using the Columnconfigure and Rowconfigure methods of the grid. This weight is relative. If two columns have the same weight, theyβll expand at the same rate.
What to do if the cell is larger than widget. By default, with sticky=β, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.
βNSEWβ means N+S+E+W
Code:-
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("500x500") # Specify GridGrid.rowconfigure(root,0,weight=1)Grid.columnconfigure(root,0,weight=1) Grid.rowconfigure(root,1,weight=1) # Create Buttonsbutton_1 = Button(root,text="Button 1")button_2 = Button(root,text="Button 2") # Set gridbutton_1.grid(row=0,column=0,sticky="NSEW")button_2.grid(row=1,column=0,sticky="NSEW") # Execute tkinterroot.mainloop()
Output:
saurabh1990aror
akshaysingh98088
Python-tkinter
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": "\n04 Sep, 2021"
},
{
"code": null,
"e": 63,
"s": 28,
"text": "Prerequisite: Python GUI β tkinter"
},
{
"code": null,
"e": 368,
"s": 63,
"text": "Button size is static, which means the size of a button cannot be changed once it is defined by the user. The problem here is while resizing the window size, it can affect the button size problem. So the solution here is, make a dynamic button, which means the button size will change as per window size."
},
{
"code": null,
"e": 419,
"s": 368,
"text": "Letβs understand with step-by-step implementation:"
},
{
"code": null,
"e": 457,
"s": 419,
"text": "Step 1#: Create Normal Tkinter Window"
},
{
"code": null,
"e": 465,
"s": 457,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"400x400\") # Execute tkinterroot.mainloop()",
"e": 606,
"s": 465,
"text": null
},
{
"code": null,
"e": 615,
"s": 606,
"text": "Output:-"
},
{
"code": null,
"e": 654,
"s": 615,
"text": "Step 2#: Add Buttons and set the grid."
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Syntax:"
},
{
"code": null,
"e": 700,
"s": 662,
"text": "Button(Object Name,text=\"Enter Text\")"
},
{
"code": null,
"e": 714,
"s": 700,
"text": "What is grid?"
},
{
"code": null,
"e": 986,
"s": 714,
"text": "The grid() geometry manager organizes widgets in a table-like structure in the parent widget. The master widget is split into rows and columns, and each part of the table can hold a widget. It uses column, column span, ipadx, ipady, padx, pady, row, row span, and sticky."
},
{
"code": null,
"e": 994,
"s": 986,
"text": "Syntax:"
},
{
"code": null,
"e": 1059,
"s": 994,
"text": "Object_name.grid(row=row value,column=column value,**attributes)"
},
{
"code": null,
"e": 1067,
"s": 1059,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"500x500\") # Create Buttonsbutton_1 = Button(root,text=\"Button 1\")button_2 = Button(root,text=\"Button 2\") # Set gridbutton_1.grid(row=0,column=0)button_2.grid(row=1,column=0) # Execute tkinterroot.mainloop()",
"e": 1366,
"s": 1067,
"text": null
},
{
"code": null,
"e": 1374,
"s": 1366,
"text": "Output:"
},
{
"code": null,
"e": 1390,
"s": 1374,
"text": "Add Two Buttons"
},
{
"code": null,
"e": 1446,
"s": 1390,
"text": "Step 3#: Set Columnconfigure & Rowconfigure for resize."
},
{
"code": null,
"e": 1738,
"s": 1446,
"text": "For the user interface to resize then, weβll need to specify a positive weight to the columns that weβd like to expand. This is done using the Columnconfigure and Rowconfigure methods of the grid. This weight is relative. If two columns have the same weight, theyβll expand at the same rate."
},
{
"code": null,
"e": 2022,
"s": 1738,
"text": "What to do if the cell is larger than widget. By default, with sticky=β, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks. "
},
{
"code": null,
"e": 2043,
"s": 2022,
"text": "βNSEWβ means N+S+E+W"
},
{
"code": null,
"e": 2051,
"s": 2043,
"text": "Code:- "
},
{
"code": null,
"e": 2059,
"s": 2051,
"text": "Python3"
},
{
"code": "# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry(\"500x500\") # Specify GridGrid.rowconfigure(root,0,weight=1)Grid.columnconfigure(root,0,weight=1) Grid.rowconfigure(root,1,weight=1) # Create Buttonsbutton_1 = Button(root,text=\"Button 1\")button_2 = Button(root,text=\"Button 2\") # Set gridbutton_1.grid(row=0,column=0,sticky=\"NSEW\")button_2.grid(row=1,column=0,sticky=\"NSEW\") # Execute tkinterroot.mainloop()",
"e": 2507,
"s": 2059,
"text": null
},
{
"code": null,
"e": 2515,
"s": 2507,
"text": "Output:"
},
{
"code": null,
"e": 2533,
"s": 2517,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 2550,
"s": 2533,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2565,
"s": 2550,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2572,
"s": 2565,
"text": "Python"
},
{
"code": null,
"e": 2670,
"s": 2572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2702,
"s": 2670,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2729,
"s": 2702,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2750,
"s": 2729,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2781,
"s": 2750,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2837,
"s": 2781,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2860,
"s": 2837,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2902,
"s": 2860,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2944,
"s": 2902,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2983,
"s": 2944,
"text": "Python | datetime.timedelta() function"
}
] |
get_attribute() element method β Selenium Python
|
17 Nov, 2021
Seleniumβs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout β Navigating links using get method β Selenium Python. Just being able to go to places isnβt terribly useful. What weβd really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout β Locating StrategiesThis article revolves around how to use get_attribute method in Selenium. get_attribute method is used to get attributes of an element, such as getting href attribute of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesnβt exist, it returns the value of the attribute with the same name. If thereβs no attribute with that name, None is returned.Syntax β
element.get_attribute("attribute name")
Example β
html
<a href="https://www.geeksforgeeks.org/" id="link" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use β
elements = driver.find_elements_by_id("link")
Now one can get attribute of this field with
element.get_attribute('href')
Letβs use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href attribute of courses tab in navigation bar at geeksforgeeks. Program β
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_link_text("Courses") # get href attributeprint(element.get_attribute('href'))
Output-
Terminal Output β
kashishsoda
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 1043,
"s": 53,
"text": "Seleniumβs Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout β Navigating links using get method β Selenium Python. Just being able to go to places isnβt terribly useful. What weβd really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout β Locating StrategiesThis article revolves around how to use get_attribute method in Selenium. get_attribute method is used to get attributes of an element, such as getting href attribute of anchor tag. This method will first try to return the value of a property with the given name. If a property with that name doesnβt exist, it returns the value of the attribute with the same name. If thereβs no attribute with that name, None is returned.Syntax β "
},
{
"code": null,
"e": 1083,
"s": 1043,
"text": "element.get_attribute(\"attribute name\")"
},
{
"code": null,
"e": 1095,
"s": 1083,
"text": "Example β "
},
{
"code": null,
"e": 1100,
"s": 1095,
"text": "html"
},
{
"code": "<a href=\"https://www.geeksforgeeks.org/\" id=\"link\" />",
"e": 1154,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1154,
"text": "To find an element one needs to use one of the locating strategies, For example, "
},
{
"code": null,
"e": 1338,
"s": 1236,
"text": "element = driver.find_element_by_id(\"link\")\nelement = driver.find_element_by_xpath(\"//a[@id='link']\")"
},
{
"code": null,
"e": 1386,
"s": 1338,
"text": "Also, to find multiple elements, we can use β "
},
{
"code": null,
"e": 1432,
"s": 1386,
"text": "elements = driver.find_elements_by_id(\"link\")"
},
{
"code": null,
"e": 1479,
"s": 1432,
"text": "Now one can get attribute of this field with "
},
{
"code": null,
"e": 1509,
"s": 1479,
"text": "element.get_attribute('href')"
},
{
"code": null,
"e": 1689,
"s": 1511,
"text": "Letβs use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we get href attribute of courses tab in navigation bar at geeksforgeeks. Program β "
},
{
"code": null,
"e": 1697,
"s": 1689,
"text": "Python3"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_link_text(\"Courses\") # get href attributeprint(element.get_attribute('href'))",
"e": 2043,
"s": 1697,
"text": null
},
{
"code": null,
"e": 2053,
"s": 2043,
"text": "Output- "
},
{
"code": null,
"e": 2073,
"s": 2053,
"text": "Terminal Output β "
},
{
"code": null,
"e": 2087,
"s": 2075,
"text": "kashishsoda"
},
{
"code": null,
"e": 2103,
"s": 2087,
"text": "Python-selenium"
},
{
"code": null,
"e": 2112,
"s": 2103,
"text": "selenium"
},
{
"code": null,
"e": 2119,
"s": 2112,
"text": "Python"
},
{
"code": null,
"e": 2217,
"s": 2119,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2235,
"s": 2217,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2277,
"s": 2235,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2299,
"s": 2277,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2334,
"s": 2299,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2360,
"s": 2334,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2392,
"s": 2360,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2421,
"s": 2392,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2448,
"s": 2421,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2478,
"s": 2448,
"text": "Iterate over a list in Python"
}
] |
Introduction to PyTorch BigGraph β with Examples | by Sven Balnojan | Towards Data Science
|
PyTorch BigGraph is a tool to create and handle large graph embeddings for machine learning. Currently there are two approaches in graph-based neural networks:
Directly use the graph structure and feed it to a neural network. The graph structure is then preserved at every layer. graphCNNs use that approach, see for instance my post or this paper on that.
But most graphs are too large for that. So itβs also reasonable to create a large embedding of the graph. And then use it as features in a traditional neural network.
PyTorch BigGraph handles the second approach, and we will do so as well below. Just for reference letβs talk about the size aspect for a second. Graphs are usually encoded by their adjacency matrix. If you have a graph with 3,000 nodes and an edge between each node, you end up with around 10,000,000 entries in your matrix. Even if thatβs sparse, apparently this bursts most GPUs according to the paper linked above.
If you think about the usual graphs used in recommendation systems, youβll realise they are typically much larger than that. Now there are already some excellent posts about the how and why of BigGraph, so I wonβt spend more time on that. Iβm interested in applying BigGraph to my machine learning problem and for that I like to take the simplest examples and getting things to work. I constructed two examples which we will walk through step by step.
The whole code is refactored and available at GitHub. Itβs adapted from the example found at the BigGraph repository.
The first example is part of the LiveJournal graph and the data looks like this:
# FromNodeId ToNodeId0 10 20 3...0 100 110 12...0 461 0...
The second example are simply 8 nodes with edges:
# FromNodeId ToNodeId0 10 20 30 41 01 21 31 42 12 32 43 13 23 43 74 15 16 27 3
BigGraph is made to work around the memory limit of machines, so itβs completely file based. Youβll have to trigger processes to create the appropriate file structure. And if you want run an example again, youβll have to delete the checkpoints. We also have to split into train and test beforehand, again on file basis. The file format is TSV, tab separated values.
Letβs dive right into it. The first code snippet declares two helper functions, take from the BigGraph source, sets some constants and runs the file split.
This splits the edges into a test and train set by creating the two files data/example_1/test.txt and train.txt. Next we use BigGraphs converters to create the file based structure for our datasets. We will βpartitionβ into 1 partition. For that we already need parts of the config file. Hereβs the relevant part of the config file, the I/O data part and the graph structure.
entities_base = 'data/example_1' def get_torchbiggraph_config(): config = dict( # I/O data entity_path=entities_base, edge_paths=[], checkpoint_path='model/example_1', # Graph structure entities={ 'user_id': {'num_partitions': 1}, }, relations=[{ 'name': 'follow', 'lhs': 'user_id', 'rhs': 'user_id', 'operator': 'none', }],...
This tells BigGraph where to find our data and how to interpret our tab separated values. With this config we can run the next Python snippet.
The results should be a bunch of new files in the data dir, namely:
two folders test_partitioned, train_partitioned
one file per folder for the edges in h5 format for quick partial reads
the dictionary.json file containing the mapping between βuser_idsβ and new assigned ids.
entity_count_user_id_0.txt contains the entity count, in this case 47.
The dictionary.json is important to later map results of the BigGraph model to the actual embedding we want to have. Enough preparation, letβs train the embedding. Take a look at the config_1.py, it contains three relevant sections.
# Scoring model - the embedding size dimension=1024, global_emb=False, # Training - the epochs to train and the learning rate num_epochs=10, lr=0.001, # Misc - not important hogwild_delay=2, ) return config
To train we run the following Python code.
We can evaluate the model based on some preinstalled metrics on our test set via this code piece.
Now letβs try to retrieve the actual embedding. Again as everything is file based, it should now be located as h5 in the models/ folder. We can load the embedding of user 0 by looking up his mapping in the dictionary like so:
Now letβs switch to our second example, a constructed one on which we hopefully can do something partially useful. The liveJournal data is simply too huge to run through in a reasonable amount of time.
Alright, we will repeat the steps for the second example, except we will produce an embedding of dimension 10, so we can view it and work with it. Besides dimension 10 seems to me more than enough for 8 vertices. We set upthose things in the config_2.py.
entities_base = 'data/example_2' def get_torchbiggraph_config(): config = dict( # I/O data entity_path=entities_base, edge_paths=[], checkpoint_path='model/example_2', # Graph structure entities={ 'user_id': {'num_partitions': 1}, }, relations=[{ 'name': 'follow', 'lhs': 'user_id', 'rhs': 'user_id', 'operator': 'none', }], # Scoring model dimension=10, global_emb=False, # Training num_epochs=10, lr=0.001, # Misc hogwild_delay=2, ) return config
Then we run the same code as before but in one go, taking care of different file paths and format. In this case we only have 3 lines of comments on top of the datafile:
As final output you should get a bunch of things and in particular all embeddings. Letβs do some basic tasks with the embedding. Of course we could now use it and load it into any framework we like, keras, tensorflow, but BigGraph already brings some implementations for common tasks like link prediction and ranking. So letβs try them out. The first task is link prediction. We predict the scores for the entities 0-7 and for 0β1 as we know from our data that 0β1 should be much more likely.
As comparator we loaded the βDotComparatorβ which computes the dot product or scalar product of the two 10-dimensional vectors. Turns out the outputted numbers are tiny, but at least score_2 is much higher than score_1 as we expected.
Finally as the last piece of code we can produce a ranking of similar items, which uses the same mechanism as before. We use the scalar product to compute the distances of embeddings to all other entities and then rank them.
The top entities in this case are in orders 0, 1, 3, 7 ... and if you look at the data that seems to be pretty much right.
This is the most basic examples I could come up with. I did not ran the original examples on the freebase data or on the LiveJournal data, simply because they take quite some time to train. You can find the code and references here:
GitHub repository of PyTorch BigGraph
GitHub repository with sample code
https://arxiv.org/pdf/1903.12287.pdf, A. Leerer, et. al. (2019), PyTorch-BigGraph: a Large-scale Graph Embedding System.
https://arxiv.org/abs/1609.02907, T. N. Kipf, M. Welling (2016), Semi-Supervised Classification with Graph Convolutional Networks.
I ran the code on my mac and encountered three issues:
An error stating βlib*.....Reason: image not found: β The solution is to install whatβs missing e.g. with βbrew install libompβ
I then ran into an error βAttributeError: module βtorchβ has no attribute β_sixββ, which might simply be because of incompatible python & torch versions. Anyway I move from python 3.6 & torch 1.1 => python 3.7 & torch 1.X and had my problem solved.
Inspect the train.txt and test.txt before you move on, I saw some missing new lines there while testing.
Hope this helps and is fun to play with!
|
[
{
"code": null,
"e": 332,
"s": 172,
"text": "PyTorch BigGraph is a tool to create and handle large graph embeddings for machine learning. Currently there are two approaches in graph-based neural networks:"
},
{
"code": null,
"e": 529,
"s": 332,
"text": "Directly use the graph structure and feed it to a neural network. The graph structure is then preserved at every layer. graphCNNs use that approach, see for instance my post or this paper on that."
},
{
"code": null,
"e": 696,
"s": 529,
"text": "But most graphs are too large for that. So itβs also reasonable to create a large embedding of the graph. And then use it as features in a traditional neural network."
},
{
"code": null,
"e": 1114,
"s": 696,
"text": "PyTorch BigGraph handles the second approach, and we will do so as well below. Just for reference letβs talk about the size aspect for a second. Graphs are usually encoded by their adjacency matrix. If you have a graph with 3,000 nodes and an edge between each node, you end up with around 10,000,000 entries in your matrix. Even if thatβs sparse, apparently this bursts most GPUs according to the paper linked above."
},
{
"code": null,
"e": 1566,
"s": 1114,
"text": "If you think about the usual graphs used in recommendation systems, youβll realise they are typically much larger than that. Now there are already some excellent posts about the how and why of BigGraph, so I wonβt spend more time on that. Iβm interested in applying BigGraph to my machine learning problem and for that I like to take the simplest examples and getting things to work. I constructed two examples which we will walk through step by step."
},
{
"code": null,
"e": 1684,
"s": 1566,
"text": "The whole code is refactored and available at GitHub. Itβs adapted from the example found at the BigGraph repository."
},
{
"code": null,
"e": 1765,
"s": 1684,
"text": "The first example is part of the LiveJournal graph and the data looks like this:"
},
{
"code": null,
"e": 1824,
"s": 1765,
"text": "# FromNodeId ToNodeId0 10 20 3...0 100 110 12...0 461 0..."
},
{
"code": null,
"e": 1874,
"s": 1824,
"text": "The second example are simply 8 nodes with edges:"
},
{
"code": null,
"e": 1991,
"s": 1874,
"text": "# FromNodeId ToNodeId0 10 20 30 41 01 21 31 42 12 32 43 13 23 43 74 15 16 27 3"
},
{
"code": null,
"e": 2357,
"s": 1991,
"text": "BigGraph is made to work around the memory limit of machines, so itβs completely file based. Youβll have to trigger processes to create the appropriate file structure. And if you want run an example again, youβll have to delete the checkpoints. We also have to split into train and test beforehand, again on file basis. The file format is TSV, tab separated values."
},
{
"code": null,
"e": 2513,
"s": 2357,
"text": "Letβs dive right into it. The first code snippet declares two helper functions, take from the BigGraph source, sets some constants and runs the file split."
},
{
"code": null,
"e": 2889,
"s": 2513,
"text": "This splits the edges into a test and train set by creating the two files data/example_1/test.txt and train.txt. Next we use BigGraphs converters to create the file based structure for our datasets. We will βpartitionβ into 1 partition. For that we already need parts of the config file. Hereβs the relevant part of the config file, the I/O data part and the graph structure."
},
{
"code": null,
"e": 3348,
"s": 2889,
"text": "entities_base = 'data/example_1' def get_torchbiggraph_config(): config = dict( # I/O data entity_path=entities_base, edge_paths=[], checkpoint_path='model/example_1', # Graph structure entities={ 'user_id': {'num_partitions': 1}, }, relations=[{ 'name': 'follow', 'lhs': 'user_id', 'rhs': 'user_id', 'operator': 'none', }],..."
},
{
"code": null,
"e": 3491,
"s": 3348,
"text": "This tells BigGraph where to find our data and how to interpret our tab separated values. With this config we can run the next Python snippet."
},
{
"code": null,
"e": 3559,
"s": 3491,
"text": "The results should be a bunch of new files in the data dir, namely:"
},
{
"code": null,
"e": 3607,
"s": 3559,
"text": "two folders test_partitioned, train_partitioned"
},
{
"code": null,
"e": 3678,
"s": 3607,
"text": "one file per folder for the edges in h5 format for quick partial reads"
},
{
"code": null,
"e": 3767,
"s": 3678,
"text": "the dictionary.json file containing the mapping between βuser_idsβ and new assigned ids."
},
{
"code": null,
"e": 3838,
"s": 3767,
"text": "entity_count_user_id_0.txt contains the entity count, in this case 47."
},
{
"code": null,
"e": 4071,
"s": 3838,
"text": "The dictionary.json is important to later map results of the BigGraph model to the actual embedding we want to have. Enough preparation, letβs train the embedding. Take a look at the config_1.py, it contains three relevant sections."
},
{
"code": null,
"e": 4344,
"s": 4071,
"text": " # Scoring model - the embedding size dimension=1024, global_emb=False, # Training - the epochs to train and the learning rate num_epochs=10, lr=0.001, # Misc - not important hogwild_delay=2, ) return config"
},
{
"code": null,
"e": 4387,
"s": 4344,
"text": "To train we run the following Python code."
},
{
"code": null,
"e": 4485,
"s": 4387,
"text": "We can evaluate the model based on some preinstalled metrics on our test set via this code piece."
},
{
"code": null,
"e": 4711,
"s": 4485,
"text": "Now letβs try to retrieve the actual embedding. Again as everything is file based, it should now be located as h5 in the models/ folder. We can load the embedding of user 0 by looking up his mapping in the dictionary like so:"
},
{
"code": null,
"e": 4913,
"s": 4711,
"text": "Now letβs switch to our second example, a constructed one on which we hopefully can do something partially useful. The liveJournal data is simply too huge to run through in a reasonable amount of time."
},
{
"code": null,
"e": 5168,
"s": 4913,
"text": "Alright, we will repeat the steps for the second example, except we will produce an embedding of dimension 10, so we can view it and work with it. Besides dimension 10 seems to me more than enough for 8 vertices. We set upthose things in the config_2.py."
},
{
"code": null,
"e": 5805,
"s": 5168,
"text": "entities_base = 'data/example_2' def get_torchbiggraph_config(): config = dict( # I/O data entity_path=entities_base, edge_paths=[], checkpoint_path='model/example_2', # Graph structure entities={ 'user_id': {'num_partitions': 1}, }, relations=[{ 'name': 'follow', 'lhs': 'user_id', 'rhs': 'user_id', 'operator': 'none', }], # Scoring model dimension=10, global_emb=False, # Training num_epochs=10, lr=0.001, # Misc hogwild_delay=2, ) return config"
},
{
"code": null,
"e": 5974,
"s": 5805,
"text": "Then we run the same code as before but in one go, taking care of different file paths and format. In this case we only have 3 lines of comments on top of the datafile:"
},
{
"code": null,
"e": 6467,
"s": 5974,
"text": "As final output you should get a bunch of things and in particular all embeddings. Letβs do some basic tasks with the embedding. Of course we could now use it and load it into any framework we like, keras, tensorflow, but BigGraph already brings some implementations for common tasks like link prediction and ranking. So letβs try them out. The first task is link prediction. We predict the scores for the entities 0-7 and for 0β1 as we know from our data that 0β1 should be much more likely."
},
{
"code": null,
"e": 6702,
"s": 6467,
"text": "As comparator we loaded the βDotComparatorβ which computes the dot product or scalar product of the two 10-dimensional vectors. Turns out the outputted numbers are tiny, but at least score_2 is much higher than score_1 as we expected."
},
{
"code": null,
"e": 6927,
"s": 6702,
"text": "Finally as the last piece of code we can produce a ranking of similar items, which uses the same mechanism as before. We use the scalar product to compute the distances of embeddings to all other entities and then rank them."
},
{
"code": null,
"e": 7050,
"s": 6927,
"text": "The top entities in this case are in orders 0, 1, 3, 7 ... and if you look at the data that seems to be pretty much right."
},
{
"code": null,
"e": 7283,
"s": 7050,
"text": "This is the most basic examples I could come up with. I did not ran the original examples on the freebase data or on the LiveJournal data, simply because they take quite some time to train. You can find the code and references here:"
},
{
"code": null,
"e": 7321,
"s": 7283,
"text": "GitHub repository of PyTorch BigGraph"
},
{
"code": null,
"e": 7356,
"s": 7321,
"text": "GitHub repository with sample code"
},
{
"code": null,
"e": 7477,
"s": 7356,
"text": "https://arxiv.org/pdf/1903.12287.pdf, A. Leerer, et. al. (2019), PyTorch-BigGraph: a Large-scale Graph Embedding System."
},
{
"code": null,
"e": 7608,
"s": 7477,
"text": "https://arxiv.org/abs/1609.02907, T. N. Kipf, M. Welling (2016), Semi-Supervised Classification with Graph Convolutional Networks."
},
{
"code": null,
"e": 7663,
"s": 7608,
"text": "I ran the code on my mac and encountered three issues:"
},
{
"code": null,
"e": 7791,
"s": 7663,
"text": "An error stating βlib*.....Reason: image not found: β The solution is to install whatβs missing e.g. with βbrew install libompβ"
},
{
"code": null,
"e": 8040,
"s": 7791,
"text": "I then ran into an error βAttributeError: module βtorchβ has no attribute β_sixββ, which might simply be because of incompatible python & torch versions. Anyway I move from python 3.6 & torch 1.1 => python 3.7 & torch 1.X and had my problem solved."
},
{
"code": null,
"e": 8145,
"s": 8040,
"text": "Inspect the train.txt and test.txt before you move on, I saw some missing new lines there while testing."
}
] |
Rearrange numbers in an array such that no two adjacent numbers are same - GeeksforGeeks
|
29 Oct, 2021
Given an array of integers. The task is to rearrange elements of the array such that no two adjacent elements in the array are same.
Examples:
Input: arr[] = {1, 1, 1, 2, 2, 2}
Output: {2, 1, 2, 1, 2, 1}
Input: arr[] = {1, 1, 1, 1, 2, 2, 3, 3}
Output: {1, 3, 1, 3, 2, 1, 2, 1}
The idea is to put the highest frequency element first (a greedy approach). We use a priority queue (Or Binary Max Heap) and put all elements and ordered by their frequencies (highest frequency element at the root). We then one by one take the highest frequency element from the heap and add it to result. After we add, we decrease the frequency of the element and temporarily move this element out of priority queue so that it is not picked next time.
We have to follow the step to solve this problem, they are:
Build a Priority_queue or max_heap, pq that stores elements and their frequencies. ...... Priority_queue or max_heap is built on the bases of the frequency of elements.Create a temporary Key that will be used as the previously visited element (the previous element in the resultant array. Initialize it { num = -1, freq = -1 }While pq is not empty. Pop an element and add it to the result.Decrease frequency of the popped element by β1β.Push the previous element back into the priority_queue if itβs frequency > β0β.Make the current element as the previous element for the next iteration.If the length of resultant string and original are not equal, print βnot possibleβ. Else print result.
Build a Priority_queue or max_heap, pq that stores elements and their frequencies. ...... Priority_queue or max_heap is built on the bases of the frequency of elements.
Create a temporary Key that will be used as the previously visited element (the previous element in the resultant array. Initialize it { num = -1, freq = -1 }
While pq is not empty. Pop an element and add it to the result.Decrease frequency of the popped element by β1β.Push the previous element back into the priority_queue if itβs frequency > β0β.Make the current element as the previous element for the next iteration.
Pop an element and add it to the result.
Decrease frequency of the popped element by β1β.
Push the previous element back into the priority_queue if itβs frequency > β0β.
Make the current element as the previous element for the next iteration.
If the length of resultant string and original are not equal, print βnot possibleβ. Else print result.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++14 program to rearrange numbers in// an Array such that no two numbers are// adjacent#include <bits/stdc++.h>using namespace std; // Function to rearrange numbers in array such// that no two adjacent numbers are samevoid rearrangeArray(int arr[], int N){ // Store frequencies of all elements // of the array map<int, int>mp, visited; for(int i = 0; i < N; i++) { mp[arr[i]]++; } priority_queue<pair<int, int>>pq; // Adding high freq elements // in descending order for(int i = 0; i < N ; i++) { int val = arr[i]; if (mp[val] > 0 and visited[val] != 1) { pq.push({mp[val], val}); } visited[val] = 1; } // 'result[]' that will store resultant value vector<int>result(N); // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) pair<int, int>prev = { -1, -1 }; int l = 0; // Traverse queue while (pq.size() != 0) { // Pop top element from queue and add it // to result pair<int,int>k = pq.top(); pq.pop(); result[l] = k.second; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.first > 0) { pq.push(prev); } // Make current element as the previous // decrease frequency by 'one' k.first--; prev = k; l++; } for(auto it : result) { if (it == 0) { // If found 0, No valid result // array possible cout << "Not valid Array" << endl; return; } } for(auto it : result) { cout << it << ", "; }} // Driver Codeint main(){ int A[] = { 1, 1, 1, 1, 2, 2, 3, 3 }; // Size of the array int N = sizeof(A) / sizeof(A[0]); rearrangeArray(A, N);} // This code is contributed by koulick_sadhu
// Java Program to rearrange numbers in an Array// such that no two numbers are adjacent import java.util.Comparator;import java.util.PriorityQueue; // Comparator class to sort in descending orderclass KeyComparator implements Comparator<Key>{ // Overriding compare()method of Comparator public int compare(Key k1, Key k2) { if (k1.freq < k2.freq) return 1; else if (k1.freq > k2.freq) return -1; return 0; }} // Object of num and its freqclass Key{ int freq; // store frequency of character int num; Key(int freq, int num) { this.freq = freq; this.num = num; }} public class GFG{ // Function to rearrange numbers in array such // that no two adjacent numbers are same static void rearrangeArray(int[] arr) { int n = arr.length; // Store frequencies of all elements // of the array int[] count = new int[10000]; int visited[] = new int[10000]; for (int i = 0; i < n; i++) count[arr[i]]++; // Insert all characters with their frequencies // into a priority_queue PriorityQueue<Key> pq = new PriorityQueue<>(new KeyComparator()); // Adding high freq elements in descending order for (int i = 0; i < n; i++) { int val = arr[i]; if (count[val] > 0 && visited[val] != 1) pq.add(new Key(count[val], val)); visited[val] = 1; } // 'result[]' that will store resultant value int result[] = new int[n]; // work as the previous visited element // initial previous element will be ( '-1' and // it's frequency will also be '-1' ) Key prev = new Key(-1, -1); // Traverse queue int l = 0; while (pq.size() != 0) { // pop top element from queue and add it // to result Key k = pq.peek(); pq.poll(); result[l] = k.num; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.freq > 0) pq.add(prev); // make current element as the previous // decrease frequency by 'one' (k.freq)--; prev = k; l++; } // If length of the resultant array and original // array is not same then the array is not valid if (l != result.length) { System.out.println(" Not valid Array "); } // Otherwise Print the result array else { for (int i : result) { System.out.print(i + " "); } } } // Driver Code public static void main(String args[]) { int arr[] = new int[] { 1, 1, 1, 1, 2, 2, 3, 3 }; rearrangeArray(arr); }}
# Python3 program to rearrange numbers in# an Array such that no two numbers are# adjacent # Function to rearrange numbers in array such# that no two adjacent numbers are samedef rearrangeArray(arr, N) : # Store frequencies of all elements # of the array mp = {} visited = {} for i in range(N) : if(arr[i] in mp) : mp[arr[i]] += 1 else : mp[arr[i]] = 1 pq = [] # Adding high freq elements # in descending order for i in range(N) : val = arr[i] if((val in mp) and ((val not in visited) or (visited[val] != 1))) : pq.append([mp[val], val]) visited[val] = 1 pq.sort() pq.reverse() # 'result[]' that will store resultant value result = [0]*N # Work as the previous visited element # initial previous element will be ( '-1' and # it's frequency wiint also be '-1' ) prev = [-1, -1] l = 0 # Traverse queue while (len(pq) != 0) : # Pop top element from queue and add it # to result k = pq[0] pq.pop(0) result[l] = k[1] # If frequency of previous element is less # than zero that means it is useless, we # need not to push it if (prev[0] > 0) : pq.append(prev) pq.sort() pq.reverse() # Make current element as the previous # decrease frequency by 'one' prev = [k[0] - 1, k[1]] l += 1 for it in result : if (it == 0) : # If found 0, No valid result # array possible print("Not valid Array") return for it in result : print(it , end = " ") A = [ 1, 1, 1, 1, 2, 2, 3, 3 ] # Size of the arrayN = len(A)rearrangeArray(A, N) #This code is contributed by divyesh072019.
// C# program to rearrange numbers in// an Array such that no two numbers are// adjacentusing System;using System.Collections.Generic;class GFG{ // Function to rearrange numbers in array such // that no two adjacent numbers are same static void rearrangeArray(int[] arr, int N) { // Store frequencies of all elements // of the array Dictionary<int, int> mp = new Dictionary<int, int>(); Dictionary<int, int> visited = new Dictionary<int, int>(); for(int i = 0; i < N; i++) { if(mp.ContainsKey(arr[i])) { mp[arr[i]] += 1; } else{ mp[arr[i]] = 1; } } List<Tuple<int, int>> pq = new List<Tuple<int,int>>(); // Adding high freq elements // in descending order for(int i = 0; i < N ; i++) { int val = arr[i]; if (mp.ContainsKey(val) && (!visited.ContainsKey(val) || visited[val] != 1)) { pq.Add(new Tuple<int,int>(mp[val], val)); } visited[val] = 1; } pq.Sort(); pq.Reverse(); // 'result[]' that will store resultant value int[] result = new int[N]; // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) Tuple<int, int> prev = new Tuple<int,int>( -1, -1 ); int l = 0; // Traverse queue while (pq.Count != 0) { // Pop top element from queue and add it // to result Tuple<int,int> k = pq[0]; pq.RemoveAt(0); result[l] = k.Item2; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.Item1 > 0) { pq.Add(prev); pq.Sort(); pq.Reverse(); } // Make current element as the previous // decrease frequency by 'one' prev = new Tuple<int,int>(k.Item1 - 1, k.Item2); l++; } foreach(int it in result) { if (it == 0) { // If found 0, No valid result // array possible Console.WriteLine("Not valid Array"); return; } } foreach(int it in result) { Console.Write(it + " "); } } // Driver code static void Main() { int[] A = { 1, 1, 1, 1, 2, 2, 3, 3 }; // Size of the array int N = A.Length; rearrangeArray(A, N); }} // This code is contributed by divyeshrabadiya07.
<script> // Javascript program to rearrange numbers in// an Array such that no two numbers are// adjacent // Function to rearrange numbers in array such// that no two adjacent numbers are samefunction rearrangeArray(arr, N){ // Store frequencies of all elements // of the array var mp = new Map(); var visited = new Map(); for(var i = 0; i < N; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } var pq = []; // Adding high freq elements // in descending order for(var i = 0; i < N ; i++) { var val = arr[i]; if (mp.get(val) > 0 && visited[val] != 1) { pq.push([mp.get(val), val]); } visited[val] = 1; } pq.sort(); // 'result[]' that will store resultant value var result = Array(N).fill(0); // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) var prev = [-1, -1]; var l = 0; // Traverse queue while (pq.length != 0) { // Pop top element from queue and add it // to result var k = pq[pq.length-1]; pq.pop(); result[l] = k[1]; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev[0] > 0) { pq.push(prev); } pq.sort(); // Make current element as the previous // decrease frequency by 'one' k[0]--; prev = k; l++; } for(var it of result) { if (it == 0) { // If found 0, No valid result // array possible document.write("Not valid Array" + "<br>"); return; } } for(var it of result) { document.write(it + " "); }} // Driver Codevar A = [1, 1, 1, 1, 2, 2, 3, 3]; // Size of the arrayvar N = A.length; rearrangeArray(A, N); // This code is contributed by rutvik_56.</script>
1 3 1 2 1 3 2 1
Time Complexity: O(N*logN)Auxiliary Space: O(N)
koulick_sadhu
jaideep45
divyeshrabadiya07
divyesh072019
pankajsharmagfg
rutvik_56
priority-queue
Advanced Data Structure
Algorithms
Arrays
Heap
Queue
Arrays
Queue
Heap
priority-queue
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Segment Tree | Set 1 (Sum of given range)
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
A* Search Algorithm
|
[
{
"code": null,
"e": 24599,
"s": 24571,
"text": "\n29 Oct, 2021"
},
{
"code": null,
"e": 24732,
"s": 24599,
"text": "Given an array of integers. The task is to rearrange elements of the array such that no two adjacent elements in the array are same."
},
{
"code": null,
"e": 24744,
"s": 24732,
"text": "Examples: "
},
{
"code": null,
"e": 24879,
"s": 24744,
"text": "Input: arr[] = {1, 1, 1, 2, 2, 2}\nOutput: {2, 1, 2, 1, 2, 1}\n\nInput: arr[] = {1, 1, 1, 1, 2, 2, 3, 3}\nOutput: {1, 3, 1, 3, 2, 1, 2, 1}"
},
{
"code": null,
"e": 25332,
"s": 24879,
"text": "The idea is to put the highest frequency element first (a greedy approach). We use a priority queue (Or Binary Max Heap) and put all elements and ordered by their frequencies (highest frequency element at the root). We then one by one take the highest frequency element from the heap and add it to result. After we add, we decrease the frequency of the element and temporarily move this element out of priority queue so that it is not picked next time."
},
{
"code": null,
"e": 25393,
"s": 25332,
"text": "We have to follow the step to solve this problem, they are: "
},
{
"code": null,
"e": 26084,
"s": 25393,
"text": "Build a Priority_queue or max_heap, pq that stores elements and their frequencies. ...... Priority_queue or max_heap is built on the bases of the frequency of elements.Create a temporary Key that will be used as the previously visited element (the previous element in the resultant array. Initialize it { num = -1, freq = -1 }While pq is not empty. Pop an element and add it to the result.Decrease frequency of the popped element by β1β.Push the previous element back into the priority_queue if itβs frequency > β0β.Make the current element as the previous element for the next iteration.If the length of resultant string and original are not equal, print βnot possibleβ. Else print result."
},
{
"code": null,
"e": 26253,
"s": 26084,
"text": "Build a Priority_queue or max_heap, pq that stores elements and their frequencies. ...... Priority_queue or max_heap is built on the bases of the frequency of elements."
},
{
"code": null,
"e": 26412,
"s": 26253,
"text": "Create a temporary Key that will be used as the previously visited element (the previous element in the resultant array. Initialize it { num = -1, freq = -1 }"
},
{
"code": null,
"e": 26675,
"s": 26412,
"text": "While pq is not empty. Pop an element and add it to the result.Decrease frequency of the popped element by β1β.Push the previous element back into the priority_queue if itβs frequency > β0β.Make the current element as the previous element for the next iteration."
},
{
"code": null,
"e": 26716,
"s": 26675,
"text": "Pop an element and add it to the result."
},
{
"code": null,
"e": 26765,
"s": 26716,
"text": "Decrease frequency of the popped element by β1β."
},
{
"code": null,
"e": 26845,
"s": 26765,
"text": "Push the previous element back into the priority_queue if itβs frequency > β0β."
},
{
"code": null,
"e": 26918,
"s": 26845,
"text": "Make the current element as the previous element for the next iteration."
},
{
"code": null,
"e": 27021,
"s": 26918,
"text": "If the length of resultant string and original are not equal, print βnot possibleβ. Else print result."
},
{
"code": null,
"e": 27072,
"s": 27021,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27078,
"s": 27072,
"text": "C++14"
},
{
"code": null,
"e": 27083,
"s": 27078,
"text": "Java"
},
{
"code": null,
"e": 27091,
"s": 27083,
"text": "Python3"
},
{
"code": null,
"e": 27094,
"s": 27091,
"text": "C#"
},
{
"code": null,
"e": 27105,
"s": 27094,
"text": "Javascript"
},
{
"code": "// C++14 program to rearrange numbers in// an Array such that no two numbers are// adjacent#include <bits/stdc++.h>using namespace std; // Function to rearrange numbers in array such// that no two adjacent numbers are samevoid rearrangeArray(int arr[], int N){ // Store frequencies of all elements // of the array map<int, int>mp, visited; for(int i = 0; i < N; i++) { mp[arr[i]]++; } priority_queue<pair<int, int>>pq; // Adding high freq elements // in descending order for(int i = 0; i < N ; i++) { int val = arr[i]; if (mp[val] > 0 and visited[val] != 1) { pq.push({mp[val], val}); } visited[val] = 1; } // 'result[]' that will store resultant value vector<int>result(N); // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) pair<int, int>prev = { -1, -1 }; int l = 0; // Traverse queue while (pq.size() != 0) { // Pop top element from queue and add it // to result pair<int,int>k = pq.top(); pq.pop(); result[l] = k.second; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.first > 0) { pq.push(prev); } // Make current element as the previous // decrease frequency by 'one' k.first--; prev = k; l++; } for(auto it : result) { if (it == 0) { // If found 0, No valid result // array possible cout << \"Not valid Array\" << endl; return; } } for(auto it : result) { cout << it << \", \"; }} // Driver Codeint main(){ int A[] = { 1, 1, 1, 1, 2, 2, 3, 3 }; // Size of the array int N = sizeof(A) / sizeof(A[0]); rearrangeArray(A, N);} // This code is contributed by koulick_sadhu",
"e": 29173,
"s": 27105,
"text": null
},
{
"code": "// Java Program to rearrange numbers in an Array// such that no two numbers are adjacent import java.util.Comparator;import java.util.PriorityQueue; // Comparator class to sort in descending orderclass KeyComparator implements Comparator<Key>{ // Overriding compare()method of Comparator public int compare(Key k1, Key k2) { if (k1.freq < k2.freq) return 1; else if (k1.freq > k2.freq) return -1; return 0; }} // Object of num and its freqclass Key{ int freq; // store frequency of character int num; Key(int freq, int num) { this.freq = freq; this.num = num; }} public class GFG{ // Function to rearrange numbers in array such // that no two adjacent numbers are same static void rearrangeArray(int[] arr) { int n = arr.length; // Store frequencies of all elements // of the array int[] count = new int[10000]; int visited[] = new int[10000]; for (int i = 0; i < n; i++) count[arr[i]]++; // Insert all characters with their frequencies // into a priority_queue PriorityQueue<Key> pq = new PriorityQueue<>(new KeyComparator()); // Adding high freq elements in descending order for (int i = 0; i < n; i++) { int val = arr[i]; if (count[val] > 0 && visited[val] != 1) pq.add(new Key(count[val], val)); visited[val] = 1; } // 'result[]' that will store resultant value int result[] = new int[n]; // work as the previous visited element // initial previous element will be ( '-1' and // it's frequency will also be '-1' ) Key prev = new Key(-1, -1); // Traverse queue int l = 0; while (pq.size() != 0) { // pop top element from queue and add it // to result Key k = pq.peek(); pq.poll(); result[l] = k.num; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.freq > 0) pq.add(prev); // make current element as the previous // decrease frequency by 'one' (k.freq)--; prev = k; l++; } // If length of the resultant array and original // array is not same then the array is not valid if (l != result.length) { System.out.println(\" Not valid Array \"); } // Otherwise Print the result array else { for (int i : result) { System.out.print(i + \" \"); } } } // Driver Code public static void main(String args[]) { int arr[] = new int[] { 1, 1, 1, 1, 2, 2, 3, 3 }; rearrangeArray(arr); }}",
"e": 32083,
"s": 29173,
"text": null
},
{
"code": "# Python3 program to rearrange numbers in# an Array such that no two numbers are# adjacent # Function to rearrange numbers in array such# that no two adjacent numbers are samedef rearrangeArray(arr, N) : # Store frequencies of all elements # of the array mp = {} visited = {} for i in range(N) : if(arr[i] in mp) : mp[arr[i]] += 1 else : mp[arr[i]] = 1 pq = [] # Adding high freq elements # in descending order for i in range(N) : val = arr[i] if((val in mp) and ((val not in visited) or (visited[val] != 1))) : pq.append([mp[val], val]) visited[val] = 1 pq.sort() pq.reverse() # 'result[]' that will store resultant value result = [0]*N # Work as the previous visited element # initial previous element will be ( '-1' and # it's frequency wiint also be '-1' ) prev = [-1, -1] l = 0 # Traverse queue while (len(pq) != 0) : # Pop top element from queue and add it # to result k = pq[0] pq.pop(0) result[l] = k[1] # If frequency of previous element is less # than zero that means it is useless, we # need not to push it if (prev[0] > 0) : pq.append(prev) pq.sort() pq.reverse() # Make current element as the previous # decrease frequency by 'one' prev = [k[0] - 1, k[1]] l += 1 for it in result : if (it == 0) : # If found 0, No valid result # array possible print(\"Not valid Array\") return for it in result : print(it , end = \" \") A = [ 1, 1, 1, 1, 2, 2, 3, 3 ] # Size of the arrayN = len(A)rearrangeArray(A, N) #This code is contributed by divyesh072019.",
"e": 33986,
"s": 32083,
"text": null
},
{
"code": "// C# program to rearrange numbers in// an Array such that no two numbers are// adjacentusing System;using System.Collections.Generic;class GFG{ // Function to rearrange numbers in array such // that no two adjacent numbers are same static void rearrangeArray(int[] arr, int N) { // Store frequencies of all elements // of the array Dictionary<int, int> mp = new Dictionary<int, int>(); Dictionary<int, int> visited = new Dictionary<int, int>(); for(int i = 0; i < N; i++) { if(mp.ContainsKey(arr[i])) { mp[arr[i]] += 1; } else{ mp[arr[i]] = 1; } } List<Tuple<int, int>> pq = new List<Tuple<int,int>>(); // Adding high freq elements // in descending order for(int i = 0; i < N ; i++) { int val = arr[i]; if (mp.ContainsKey(val) && (!visited.ContainsKey(val) || visited[val] != 1)) { pq.Add(new Tuple<int,int>(mp[val], val)); } visited[val] = 1; } pq.Sort(); pq.Reverse(); // 'result[]' that will store resultant value int[] result = new int[N]; // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) Tuple<int, int> prev = new Tuple<int,int>( -1, -1 ); int l = 0; // Traverse queue while (pq.Count != 0) { // Pop top element from queue and add it // to result Tuple<int,int> k = pq[0]; pq.RemoveAt(0); result[l] = k.Item2; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev.Item1 > 0) { pq.Add(prev); pq.Sort(); pq.Reverse(); } // Make current element as the previous // decrease frequency by 'one' prev = new Tuple<int,int>(k.Item1 - 1, k.Item2); l++; } foreach(int it in result) { if (it == 0) { // If found 0, No valid result // array possible Console.WriteLine(\"Not valid Array\"); return; } } foreach(int it in result) { Console.Write(it + \" \"); } } // Driver code static void Main() { int[] A = { 1, 1, 1, 1, 2, 2, 3, 3 }; // Size of the array int N = A.Length; rearrangeArray(A, N); }} // This code is contributed by divyeshrabadiya07.",
"e": 36855,
"s": 33986,
"text": null
},
{
"code": "<script> // Javascript program to rearrange numbers in// an Array such that no two numbers are// adjacent // Function to rearrange numbers in array such// that no two adjacent numbers are samefunction rearrangeArray(arr, N){ // Store frequencies of all elements // of the array var mp = new Map(); var visited = new Map(); for(var i = 0; i < N; i++) { if(mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } var pq = []; // Adding high freq elements // in descending order for(var i = 0; i < N ; i++) { var val = arr[i]; if (mp.get(val) > 0 && visited[val] != 1) { pq.push([mp.get(val), val]); } visited[val] = 1; } pq.sort(); // 'result[]' that will store resultant value var result = Array(N).fill(0); // Work as the previous visited element // initial previous element will be ( '-1' and // it's frequency wiint also be '-1' ) var prev = [-1, -1]; var l = 0; // Traverse queue while (pq.length != 0) { // Pop top element from queue and add it // to result var k = pq[pq.length-1]; pq.pop(); result[l] = k[1]; // If frequency of previous element is less // than zero that means it is useless, we // need not to push it if (prev[0] > 0) { pq.push(prev); } pq.sort(); // Make current element as the previous // decrease frequency by 'one' k[0]--; prev = k; l++; } for(var it of result) { if (it == 0) { // If found 0, No valid result // array possible document.write(\"Not valid Array\" + \"<br>\"); return; } } for(var it of result) { document.write(it + \" \"); }} // Driver Codevar A = [1, 1, 1, 1, 2, 2, 3, 3]; // Size of the arrayvar N = A.length; rearrangeArray(A, N); // This code is contributed by rutvik_56.</script>",
"e": 38949,
"s": 36855,
"text": null
},
{
"code": null,
"e": 38965,
"s": 38949,
"text": "1 3 1 2 1 3 2 1"
},
{
"code": null,
"e": 39015,
"s": 38967,
"text": "Time Complexity: O(N*logN)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 39029,
"s": 39015,
"text": "koulick_sadhu"
},
{
"code": null,
"e": 39039,
"s": 39029,
"text": "jaideep45"
},
{
"code": null,
"e": 39057,
"s": 39039,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 39071,
"s": 39057,
"text": "divyesh072019"
},
{
"code": null,
"e": 39087,
"s": 39071,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 39097,
"s": 39087,
"text": "rutvik_56"
},
{
"code": null,
"e": 39112,
"s": 39097,
"text": "priority-queue"
},
{
"code": null,
"e": 39136,
"s": 39112,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 39147,
"s": 39136,
"text": "Algorithms"
},
{
"code": null,
"e": 39154,
"s": 39147,
"text": "Arrays"
},
{
"code": null,
"e": 39159,
"s": 39154,
"text": "Heap"
},
{
"code": null,
"e": 39165,
"s": 39159,
"text": "Queue"
},
{
"code": null,
"e": 39172,
"s": 39165,
"text": "Arrays"
},
{
"code": null,
"e": 39178,
"s": 39172,
"text": "Queue"
},
{
"code": null,
"e": 39183,
"s": 39178,
"text": "Heap"
},
{
"code": null,
"e": 39198,
"s": 39183,
"text": "priority-queue"
},
{
"code": null,
"e": 39209,
"s": 39198,
"text": "Algorithms"
},
{
"code": null,
"e": 39307,
"s": 39209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39316,
"s": 39307,
"text": "Comments"
},
{
"code": null,
"e": 39329,
"s": 39316,
"text": "Old Comments"
},
{
"code": null,
"e": 39363,
"s": 39329,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 39403,
"s": 39363,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 39431,
"s": 39403,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 39463,
"s": 39431,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 39505,
"s": 39463,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 39554,
"s": 39505,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 39598,
"s": 39554,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 39623,
"s": 39598,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 39654,
"s": 39623,
"text": "Difference between BFS and DFS"
}
] |
isNAN() function in JavaScript
|
The isNaN() function accepts a value and determines whether the given value is a number or not.If so, this method returns true else it returns false. You can also call this method using Number object.
Its Syntax is as follows
isNAN(5655);
Live Demo
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var result1 = parseFloat("Ef00A.D3");
document.write(isNaN(result1));
document.write('<br>');
var result2 = Math.log("welcome");
document.write(isNaN(result2));
document.write('<br>');
var result3 = Math.log(1254);
document.write(isNaN(result3));
</script>
</body>
</html>
true
true
false
|
[
{
"code": null,
"e": 1263,
"s": 1062,
"text": "The isNaN() function accepts a value and determines whether the given value is a number or not.If so, this method returns true else it returns false. You can also call this method using Number object."
},
{
"code": null,
"e": 1288,
"s": 1263,
"text": "Its Syntax is as follows"
},
{
"code": null,
"e": 1301,
"s": 1288,
"text": "isNAN(5655);"
},
{
"code": null,
"e": 1312,
"s": 1301,
"text": " Live Demo"
},
{
"code": null,
"e": 1737,
"s": 1312,
"text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n var result1 = parseFloat(\"Ef00A.D3\");\n document.write(isNaN(result1));\n document.write('<br>');\n var result2 = Math.log(\"welcome\");\n document.write(isNaN(result2));\n document.write('<br>');\n var result3 = Math.log(1254);\n document.write(isNaN(result3));\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1753,
"s": 1737,
"text": "true\ntrue\nfalse"
}
] |
Node.js process.cpuUsage() Method - GeeksforGeeks
|
12 Oct, 2021
The process.cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds. Return values may differ from the actual time elapsed especially for multi-core CPUs.
Syntax:
process.cpuUsage( previous_value )
Parameters: This method accepts a single parameter as mentioned above and described below:
previous_value: It is an optional parameter, an object returned by the calling process.cpuUsage() previously. If it is passed then the difference is returned.
Return: This method returns an object on success, which contains properties like user and system, with some integer value that signifies time elapsed by the process, measured in microseconds.
user: It is an integer that represents the time elapsed by user
system: It is an integer represents the time elapsed by system
Below examples illustrate the use of process.cpuUsage() method in Node.js:
Example 1:
Javascript
// Allocating process moduleconst process = require('process'); // Calling process.cpuUsage() methodconst usage = process.cpuUsage(); // Printing returned valueconsole.log(usage);
Output:
{ user: 78000, system: 15000 }
Example 2:
Javascript
// Allocating process moduleconst process = require('process'); // Calling process.cpuUsage() methodvar usage = process.cpuUsage();// Printing returned valueconsole.log("cpu usage before: ", usage); // Current timeconst now = Date.now(); // Loop to delay almost 100 millisecondswhile (Date.now() - now < 100); // After using the cpu for nearly equal to // 100 milliseconds// Calling process.cpuUsage() methodusage = process.cpuUsage(usage); // Printing returned valueconsole.log("Cpu usage by this process: ", usage);
Output:
cpu usage before: { user: 62000, system: 15000 }
Cpu usage by this process: { user: 109000, system: 0 }
Reference: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue
arorakashish0911
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
How to update NPM ?
Difference between promise and async await in Node.js
Roadmap to Become a Web Developer in 2022
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?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 37176,
"s": 37148,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 37526,
"s": 37176,
"text": "The process.cpuUsage() method is an inbuilt application programming interface of the Process module which is used to get the user, system CPU time usage of the current process. It is returned as an object with property user and system, values are in microseconds. Return values may differ from the actual time elapsed especially for multi-core CPUs."
},
{
"code": null,
"e": 37535,
"s": 37526,
"text": "Syntax: "
},
{
"code": null,
"e": 37570,
"s": 37535,
"text": "process.cpuUsage( previous_value )"
},
{
"code": null,
"e": 37663,
"s": 37570,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below: "
},
{
"code": null,
"e": 37822,
"s": 37663,
"text": "previous_value: It is an optional parameter, an object returned by the calling process.cpuUsage() previously. If it is passed then the difference is returned."
},
{
"code": null,
"e": 38015,
"s": 37822,
"text": "Return: This method returns an object on success, which contains properties like user and system, with some integer value that signifies time elapsed by the process, measured in microseconds. "
},
{
"code": null,
"e": 38079,
"s": 38015,
"text": "user: It is an integer that represents the time elapsed by user"
},
{
"code": null,
"e": 38142,
"s": 38079,
"text": "system: It is an integer represents the time elapsed by system"
},
{
"code": null,
"e": 38217,
"s": 38142,
"text": "Below examples illustrate the use of process.cpuUsage() method in Node.js:"
},
{
"code": null,
"e": 38230,
"s": 38217,
"text": "Example 1: "
},
{
"code": null,
"e": 38241,
"s": 38230,
"text": "Javascript"
},
{
"code": "// Allocating process moduleconst process = require('process'); // Calling process.cpuUsage() methodconst usage = process.cpuUsage(); // Printing returned valueconsole.log(usage);",
"e": 38423,
"s": 38241,
"text": null
},
{
"code": null,
"e": 38432,
"s": 38423,
"text": "Output: "
},
{
"code": null,
"e": 38463,
"s": 38432,
"text": "{ user: 78000, system: 15000 }"
},
{
"code": null,
"e": 38475,
"s": 38463,
"text": "Example 2: "
},
{
"code": null,
"e": 38486,
"s": 38475,
"text": "Javascript"
},
{
"code": "// Allocating process moduleconst process = require('process'); // Calling process.cpuUsage() methodvar usage = process.cpuUsage();// Printing returned valueconsole.log(\"cpu usage before: \", usage); // Current timeconst now = Date.now(); // Loop to delay almost 100 millisecondswhile (Date.now() - now < 100); // After using the cpu for nearly equal to // 100 milliseconds// Calling process.cpuUsage() methodusage = process.cpuUsage(usage); // Printing returned valueconsole.log(\"Cpu usage by this process: \", usage);",
"e": 39009,
"s": 38486,
"text": null
},
{
"code": null,
"e": 39018,
"s": 39009,
"text": "Output: "
},
{
"code": null,
"e": 39124,
"s": 39018,
"text": "cpu usage before: { user: 62000, system: 15000 }\nCpu usage by this process: { user: 109000, system: 0 }"
},
{
"code": null,
"e": 39211,
"s": 39124,
"text": "Reference: https://nodejs.org/api/process.html#process_process_cpuusage_previousvalue "
},
{
"code": null,
"e": 39228,
"s": 39211,
"text": "arorakashish0911"
},
{
"code": null,
"e": 39251,
"s": 39228,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 39259,
"s": 39251,
"text": "Node.js"
},
{
"code": null,
"e": 39276,
"s": 39259,
"text": "Web Technologies"
},
{
"code": null,
"e": 39374,
"s": 39276,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39383,
"s": 39374,
"text": "Comments"
},
{
"code": null,
"e": 39396,
"s": 39383,
"text": "Old Comments"
},
{
"code": null,
"e": 39433,
"s": 39396,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 39481,
"s": 39433,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 39514,
"s": 39481,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 39534,
"s": 39514,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 39588,
"s": 39534,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 39630,
"s": 39588,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 39673,
"s": 39630,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 39735,
"s": 39673,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 39785,
"s": 39735,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Creating benchmark models the scikit-learn way | by Eryk Lewinson | Towards Data Science
|
What I really like about scikit-learn is that I often stumble upon functionalities, which I was not aware of before. My most recent βdiscoveryβ is the DummyClassifier. The dummy estimator does not learn any patterns from the features, it uses simple heuristics (inferred from the targets) to calculate the predictions.
We can use that naiΜve estimator as a simple sanity check for our more advanced models. To pass the check, the considered model should result in better performance than the simple benchmark.
In this short article, I show how to use the DummyClassifier and explain the available heuristics.
We need to import the required libraries:
For this article, I write a simple function printing a few selected evaluation metrics to assess the modelβs performance. Aside from accuracy, I included metrics that help to evaluate the performance in case of a class imbalance (the list is by no means exhaustive).
For this article, I use the famous Iris dataset. To simplify the problem even further, I transform the multi-class problem into a binary classification, at the same time introducing class imbalance. The goal of the exercise will be to predict if a given plant belongs to the Versicolour class or βotherβ (Setosa or Virginica).
After the transformation, the ratio of classes is 2:1.
The last step before training the models is to split the data into training and test sets using the train_test_split function:
As we intentionally introduced class imbalance
The DummyClassifier estimator offers a few possible rules (called strategies), which we can use for determining the benchmark class predictions. Below I briefly describe them and present the corresponding code snippets showing implementation.
Arguably the simplest variant of the dummy classifier. The idea is to replace all labels with a single value. A possible use case for this variant is when we want to evaluate a potential estimator in terms of the F1 Score, which is the harmonic mean of precision and recall.
I used the minority class (Versicolour) for creating the naiΜve prediction. It is also worth mentioning that the features do not play any role in determining the predicted value, they are only there to match the scikit-learnβs fit + predict style. In the summary presented below, we see that we achieved perfect recall and an F1-Score of 0.5.
{'accuracy': 0.3333333333333333, 'recall': 1.0, 'precision': 0.3333333333333333, 'f1_score': 0.5}
In this variant, the naiΜve prediction is generated at random (uniformly) from the available classes.
Running the code results in the following summary:
{'accuracy': 0.4, 'recall': 0.4, 'precision': 0.25, 'f1_score': 0.3076923076923077}
Additionally, we inspect the distribution of the predicted labels using Counter:
Counter({0: 14, 1: 16})
As expected from a uniform draw, the distribution of the target is random and does not reflect the true distribution of the labels.
To account for the previously mentioned drawback, we can use the stratified rule. The predictions are generated randomly, however, the distribution of classes from the training set is preserved. Just as in the stratified train_test_split.
Running the code results in the following summary:
{'accuracy': 0.6333333333333333, 'recall': 0.3, 'precision': 0.42857142857142855, 'f1_score': 0.3529411764705882}
Once again, we look at the number of observations in each class:
Counter({0: 23, 1: 7})
Using the `stratified` strategy results in a distribution similar to the one we saw in the observed values.
The name of the strategy is pretty much self-explanatory β the predicted value is the most frequent value among the labels.
Running the code results in the following summary:
{'accuracy': 0.6666666666666666, 'recall': 0.0, 'precision': 0.0, 'f1_score': 0.0}
While running the code, we receive the following warning: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. The reason for that is the strategy we chose. As the majority class was used for all of the predictions, there are no observations of the minority class and metrics such as precision and recall cannot be calculated.
A very similar strategy to the βmost_frequentβ strategy. The dummy classifier always predicts the class that maximizes the class prior. The difference lies in the predict_proba method of the fitted classifier. In the case of the βpriorβ strategy, it returns the class prior (class probabilities as determined by the ratio of the labels in the training set).
The results of the βpriorβ and βmost_frequentβ strategies are the same, so I do not show them again for brevity.
It is worth mentioning that for all strategies the predict method completely ignores the input data, the values that will be used as predictions were determined during the fitting stage (or provided by us when using the βconstantβ strategy).
Having experimented with multiple strategies for creating a benchmark model, it is time to train a simple classifier and evaluate if it outperforms the benchmarks. For that, I use the Decision Tree Classifier with default settings (aside from the random_state, specified for reproducibility).
By inspecting the summary presented below, we can clearly state that the decision tree outperformed all of the benchmarks.
{'accuracy': 0.9473684210526315, 'recall': 0.9230769230769231, 'precision': 0.9230769230769231, 'f1_score': 0.9230769230769231}
I already showed how to use the scikit-learnβs DummyClassifier to estimate benchmark models for classification tasks. Naturally, there exists an analogical estimator for regression problems β DummyRegressor. I will not go into much detail, as the usage is pretty similar to the DummyClassifier. For completeness, I only mention the available strategies:
'meanβ β the estimator uses the average of the target (from the training set) as predictions
'medianβ β the estimator uses the median of the target (training set) as predictions
'constantβ β the estimator uses a constant value as predictions
'quantileβ β the estimator uses the specified quantile of the targets (training set) as predictions
Similarly to the DummyClassifier, the predict method ignores the input data for calculating the predictions.
In this article, I showed how to use estimators available in scikit-learn for creating benchmark models using simple heuristics. We can use such models for sanity checks, to see if our estimators perform better than naiΜve baselines. If not, we should investigate what causes the problem (maybe the features are not helpful or the class imbalance is impacting the results).
You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
I recently published a book on using Python for solving practical tasks in the financial domain. If you are interested, I posted an article introducing the contents of the book. You can get the book on Amazon or Packtβs website.
|
[
{
"code": null,
"e": 490,
"s": 171,
"text": "What I really like about scikit-learn is that I often stumble upon functionalities, which I was not aware of before. My most recent βdiscoveryβ is the DummyClassifier. The dummy estimator does not learn any patterns from the features, it uses simple heuristics (inferred from the targets) to calculate the predictions."
},
{
"code": null,
"e": 681,
"s": 490,
"text": "We can use that naiΜve estimator as a simple sanity check for our more advanced models. To pass the check, the considered model should result in better performance than the simple benchmark."
},
{
"code": null,
"e": 780,
"s": 681,
"text": "In this short article, I show how to use the DummyClassifier and explain the available heuristics."
},
{
"code": null,
"e": 822,
"s": 780,
"text": "We need to import the required libraries:"
},
{
"code": null,
"e": 1089,
"s": 822,
"text": "For this article, I write a simple function printing a few selected evaluation metrics to assess the modelβs performance. Aside from accuracy, I included metrics that help to evaluate the performance in case of a class imbalance (the list is by no means exhaustive)."
},
{
"code": null,
"e": 1416,
"s": 1089,
"text": "For this article, I use the famous Iris dataset. To simplify the problem even further, I transform the multi-class problem into a binary classification, at the same time introducing class imbalance. The goal of the exercise will be to predict if a given plant belongs to the Versicolour class or βotherβ (Setosa or Virginica)."
},
{
"code": null,
"e": 1471,
"s": 1416,
"text": "After the transformation, the ratio of classes is 2:1."
},
{
"code": null,
"e": 1598,
"s": 1471,
"text": "The last step before training the models is to split the data into training and test sets using the train_test_split function:"
},
{
"code": null,
"e": 1645,
"s": 1598,
"text": "As we intentionally introduced class imbalance"
},
{
"code": null,
"e": 1888,
"s": 1645,
"text": "The DummyClassifier estimator offers a few possible rules (called strategies), which we can use for determining the benchmark class predictions. Below I briefly describe them and present the corresponding code snippets showing implementation."
},
{
"code": null,
"e": 2163,
"s": 1888,
"text": "Arguably the simplest variant of the dummy classifier. The idea is to replace all labels with a single value. A possible use case for this variant is when we want to evaluate a potential estimator in terms of the F1 Score, which is the harmonic mean of precision and recall."
},
{
"code": null,
"e": 2506,
"s": 2163,
"text": "I used the minority class (Versicolour) for creating the naiΜve prediction. It is also worth mentioning that the features do not play any role in determining the predicted value, they are only there to match the scikit-learnβs fit + predict style. In the summary presented below, we see that we achieved perfect recall and an F1-Score of 0.5."
},
{
"code": null,
"e": 2604,
"s": 2506,
"text": "{'accuracy': 0.3333333333333333, 'recall': 1.0, 'precision': 0.3333333333333333, 'f1_score': 0.5}"
},
{
"code": null,
"e": 2706,
"s": 2604,
"text": "In this variant, the naiΜve prediction is generated at random (uniformly) from the available classes."
},
{
"code": null,
"e": 2757,
"s": 2706,
"text": "Running the code results in the following summary:"
},
{
"code": null,
"e": 2841,
"s": 2757,
"text": "{'accuracy': 0.4, 'recall': 0.4, 'precision': 0.25, 'f1_score': 0.3076923076923077}"
},
{
"code": null,
"e": 2922,
"s": 2841,
"text": "Additionally, we inspect the distribution of the predicted labels using Counter:"
},
{
"code": null,
"e": 2946,
"s": 2922,
"text": "Counter({0: 14, 1: 16})"
},
{
"code": null,
"e": 3078,
"s": 2946,
"text": "As expected from a uniform draw, the distribution of the target is random and does not reflect the true distribution of the labels."
},
{
"code": null,
"e": 3317,
"s": 3078,
"text": "To account for the previously mentioned drawback, we can use the stratified rule. The predictions are generated randomly, however, the distribution of classes from the training set is preserved. Just as in the stratified train_test_split."
},
{
"code": null,
"e": 3368,
"s": 3317,
"text": "Running the code results in the following summary:"
},
{
"code": null,
"e": 3482,
"s": 3368,
"text": "{'accuracy': 0.6333333333333333, 'recall': 0.3, 'precision': 0.42857142857142855, 'f1_score': 0.3529411764705882}"
},
{
"code": null,
"e": 3547,
"s": 3482,
"text": "Once again, we look at the number of observations in each class:"
},
{
"code": null,
"e": 3570,
"s": 3547,
"text": "Counter({0: 23, 1: 7})"
},
{
"code": null,
"e": 3678,
"s": 3570,
"text": "Using the `stratified` strategy results in a distribution similar to the one we saw in the observed values."
},
{
"code": null,
"e": 3802,
"s": 3678,
"text": "The name of the strategy is pretty much self-explanatory β the predicted value is the most frequent value among the labels."
},
{
"code": null,
"e": 3853,
"s": 3802,
"text": "Running the code results in the following summary:"
},
{
"code": null,
"e": 3936,
"s": 3853,
"text": "{'accuracy': 0.6666666666666666, 'recall': 0.0, 'precision': 0.0, 'f1_score': 0.0}"
},
{
"code": null,
"e": 4309,
"s": 3936,
"text": "While running the code, we receive the following warning: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. The reason for that is the strategy we chose. As the majority class was used for all of the predictions, there are no observations of the minority class and metrics such as precision and recall cannot be calculated."
},
{
"code": null,
"e": 4667,
"s": 4309,
"text": "A very similar strategy to the βmost_frequentβ strategy. The dummy classifier always predicts the class that maximizes the class prior. The difference lies in the predict_proba method of the fitted classifier. In the case of the βpriorβ strategy, it returns the class prior (class probabilities as determined by the ratio of the labels in the training set)."
},
{
"code": null,
"e": 4780,
"s": 4667,
"text": "The results of the βpriorβ and βmost_frequentβ strategies are the same, so I do not show them again for brevity."
},
{
"code": null,
"e": 5022,
"s": 4780,
"text": "It is worth mentioning that for all strategies the predict method completely ignores the input data, the values that will be used as predictions were determined during the fitting stage (or provided by us when using the βconstantβ strategy)."
},
{
"code": null,
"e": 5315,
"s": 5022,
"text": "Having experimented with multiple strategies for creating a benchmark model, it is time to train a simple classifier and evaluate if it outperforms the benchmarks. For that, I use the Decision Tree Classifier with default settings (aside from the random_state, specified for reproducibility)."
},
{
"code": null,
"e": 5438,
"s": 5315,
"text": "By inspecting the summary presented below, we can clearly state that the decision tree outperformed all of the benchmarks."
},
{
"code": null,
"e": 5566,
"s": 5438,
"text": "{'accuracy': 0.9473684210526315, 'recall': 0.9230769230769231, 'precision': 0.9230769230769231, 'f1_score': 0.9230769230769231}"
},
{
"code": null,
"e": 5920,
"s": 5566,
"text": "I already showed how to use the scikit-learnβs DummyClassifier to estimate benchmark models for classification tasks. Naturally, there exists an analogical estimator for regression problems β DummyRegressor. I will not go into much detail, as the usage is pretty similar to the DummyClassifier. For completeness, I only mention the available strategies:"
},
{
"code": null,
"e": 6013,
"s": 5920,
"text": "'meanβ β the estimator uses the average of the target (from the training set) as predictions"
},
{
"code": null,
"e": 6098,
"s": 6013,
"text": "'medianβ β the estimator uses the median of the target (training set) as predictions"
},
{
"code": null,
"e": 6162,
"s": 6098,
"text": "'constantβ β the estimator uses a constant value as predictions"
},
{
"code": null,
"e": 6262,
"s": 6162,
"text": "'quantileβ β the estimator uses the specified quantile of the targets (training set) as predictions"
},
{
"code": null,
"e": 6371,
"s": 6262,
"text": "Similarly to the DummyClassifier, the predict method ignores the input data for calculating the predictions."
},
{
"code": null,
"e": 6745,
"s": 6371,
"text": "In this article, I showed how to use estimators available in scikit-learn for creating benchmark models using simple heuristics. We can use such models for sanity checks, to see if our estimators perform better than naiΜve baselines. If not, we should investigate what causes the problem (maybe the features are not helpful or the class imbalance is impacting the results)."
},
{
"code": null,
"e": 6907,
"s": 6745,
"text": "You can find the code used for this article on my GitHub. As always, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
}
] |
Mining Telecom Product Recommendations | by Meghana Holemadlu Murthy | Towards Data Science
|
In the current age of information overload, it is becoming increasingly hard for people to find relevant content. Recommender systems have been introduced to help people in retrieving potentially useful information from a huge set of choices. It is a system that suggests products, services, information to users based on the analysis of data and has become increasingly significant in solving the information explosion problem.
In recent years, significant steps have been taken in the direction of providing personalized recommendation services for a wide variety of web-based applications in e-commerce, e-learning, and e-governance. However, this system is surprisingly not present in the telecom sector as of today, though it is a necessity. Hence, this blog explores the need for recommender systems in telcos to assist its customers in selecting the most appropriate telecom plans/products online. The blog ends with the development and implementation of a personalized recommendation system for telecom products/services by mining association rules from data to find the right telcos packages/plans/products for a new customer.
While artificial intelligence (AI) has unquestionable power to transform the telecom industry, it is still very much a nascent field. Yet I believe telcos are uniquely well-positioned to take advantage of AI technology, largely because they are already used to dealing with huge volumes of data on which AI and machine learning (ML) rely. Since this isnβt a passing fad, itβs important for telcos to play the long game with AI and consider less-explored domains that could unlock new revenue streams.
AI and ML require vast quantities of data to function correctly, but the data must be of sufficient quality, too. If the right amount of good-quality data is not available, decisions recommended by an AI or ML model are unlikely to be accurate or successful.
On a positive note, telcos do have access to large quantities of data, perhaps more than companies in most other industries. However, the struggle lies in capturing the right dataset and storing them with the degree of granularity needed for ML.
It is one thing to have high-quality data collected in a traditional way, but it is another to get this data into a specific way which you might need to solve a use case. Most telcos operatorβs web page today, consists of a vast number of choices, which in turn becomes increasingly hard for a customer to find his/her desired choice of product.
Donβt you think it would be substantial if the same web page could automatically give you recommendations on various add-on products/bundles based on choices made by existing customers in the past?
Recommendation systems can be fine-tuned to cater to user profiles/preferences based on the choices of other users. The advantage of this system is to suggest the right items (base plans or add-on products) to particular users, based on their explicit and implicit preferences by applying an information filtering algorithm. The algorithm that I have used for implementation is called Apriori.
Apriori Algorithm β It is simply the study of customer transaction database to determine dependencies between purchases of different plans/products.
In other words, it is the study of βwhat goes with whatβ.
The availability of detailed information on customer transactions has led to the development of techniques that automatically look for associations between items that are stored in the database. Example β data collected about customer transactions regarding each plan/base package along with the add-on products are captured by the network operator in their database. Such databases consist of a large number of transaction records where each record lists either the base plan or the add-on product purchased by the customer.
By performing basic EDA on customer transaction data using Python, it is very likely to observe that there are certain base packages/plans that appear more often than the rest. Hence it would be a good idea to display a popular list of base packages as a first step. Given all the data is stored in a pandas dataframe βdfβ, we can get the list of popular base-packages/plans using the code below.
df["BASE_PACKAGE_NAME"].value_counts()
Getting this data into a form where each record lists all the items bought by the user wouldnβt be much of a challenge using Python.
At this stage, we would be interested to know if certain groups of items are consistently purchased together, which can be found with the help of the Apriori algorithm.
#Convert the dataframe to a listrecords = df.values.tolist()#Generate association rules with required #minimum support, confidence and liftfrom apyori import aprioriassociation_rules = apriori(records, min_support=0.3346, min_confidence=0.20, min_lift=3, min_length=3)association_results = list(association_rules)
There are four performance metrics within the Apriori algorithm. These parameters are used to exclude association rules in the result that have support and confidence lower than the minimum support, confidence, lift, or length, respectively.
min_support β A float value between 0 and 1; used to select the items with support value greater than the value specified in the parameter.
min_support β A float value between 0 and 1; used to select the items with support value greater than the value specified in the parameter.
2. min_confidence β A float value between 0 and 1; used to filter those rules that have confidence greater than the confidence threshold specified in the parameter.
3. min_lift β This specifies the minimum lift value for the shortlisted rules.
4. min_length β This specifies the minimum number of items that you want to see in your association rules itemsets.
The optimum values for min_support, min_confidence, and min_lift arguments can be set by trying out different values and checking whether they are producing valid association between the itemsets or not.
Obtaining association rules in a comprehensible format could be a challenge; hereβs how I overcame that. Note that βPredecessorβ is an item found within the data, whereas βSuccessorβ is an item found in combination with the Predecessor.
#Create a dataframe with all the necessary informationdf = pd.DataFrame(columns=('Items','Predecessor','Successor','Support','Confidence','Lift'))Support =[]Confidence = []Lift = []Items = []Predecessor= []Successor=[]for RelationRecord in association_results: for ordered_stat in RelationRecord.ordered_statistics: Support.append(RelationRecord.support) Items.append(RelationRecord.items) Predecessor.append(ordered_stat.items_base) Successor.append(ordered_stat.items_add) Confidence.append(ordered_stat.confidence) Lift.append(ordered_stat.lift)df['Items'] = list(map(set, Items)) df['Predecessor'] = list(map(set, Predecessor))df['Successor'] = list(map(set, Successor))df['Support'] = Supportdf['Confidence'] = Confidencedf['Lift']= Lift#Sort the dataframe based on confidence df.sort_values(by ='Confidence', ascending = False, inplace = True)
Providing the right recommendations would be by picking the items in the βSuccessorβ column given that the βPredecessorβ column value is equal to the base-package name selected by the customer from the popular package list.
#Picking the records for a particular plan/base_package that has been selected by the customer on the GUIpackage_name = "1GB/Day(24 day Validity)"index=[]for key, value in df["Predecessor"].iteritems(): if len(value) == 1 and package_name in value: print(key,value) index.append(key) recommendations = df[df.index.isin(index)]
And voila!
Note that the frequently bought percentage is the measure of confidence parameter, which is computed by the Apriori algorithm as stated earlier.
Being a part of the telecom industry for almost 5 years, I have seen that any AI initiative can have various technical and organizational questions; which is not very surprising as AI is such a pie-in-the-sky thing that you need to give the organization something tangible. Hence, making the leap from concept to live project or, making the move from piloting AI proof-of-concept projects to deploying live is a further challenge. The association-rule mining approach described in this blog proves the benefits of automated affinity analysis and is a fundamental business use-case for telcos in my opinion. It is critically important to have a clear understanding of what would constitute success from such an investment.
Taking a step further, the above implementation is limited to provide recommendations for new customers subscribing to the network via web-GUI/kiosk. The model can be improved by providing recommendations to existing/new customers by adding a clustering algorithm in the initial stage; which would segment customers based on age, salary, geographical data, etc. Additionally, some shortcomings of the Apriori algorithm are the profusion of rules that are generated and the fact that rare combinations of itemsets tend to be ignored, as they do not meet the minimum support requirements. Using a more robust algorithm would help to resolve this issue.
Thank you for reading!
[1] https://www.appliedaicourse.com/
[2] Telcos and AI: What it will take to create an AI-Driven Telecoms Industry β May 2019 by STL Partners, supported by Nokia.
[3] Research Article β Improving Top-NRecommendation Performance Using Missing Data by Beijing Research Center for Information Technology in Agriculture and School of Computer Science and Technology, Beijing.
[4] Research Article β A Recommender System Architecture for Predictive Telecom Network Management by IEEE Communications Magazine.
|
[
{
"code": null,
"e": 601,
"s": 172,
"text": "In the current age of information overload, it is becoming increasingly hard for people to find relevant content. Recommender systems have been introduced to help people in retrieving potentially useful information from a huge set of choices. It is a system that suggests products, services, information to users based on the analysis of data and has become increasingly significant in solving the information explosion problem."
},
{
"code": null,
"e": 1308,
"s": 601,
"text": "In recent years, significant steps have been taken in the direction of providing personalized recommendation services for a wide variety of web-based applications in e-commerce, e-learning, and e-governance. However, this system is surprisingly not present in the telecom sector as of today, though it is a necessity. Hence, this blog explores the need for recommender systems in telcos to assist its customers in selecting the most appropriate telecom plans/products online. The blog ends with the development and implementation of a personalized recommendation system for telecom products/services by mining association rules from data to find the right telcos packages/plans/products for a new customer."
},
{
"code": null,
"e": 1809,
"s": 1308,
"text": "While artificial intelligence (AI) has unquestionable power to transform the telecom industry, it is still very much a nascent field. Yet I believe telcos are uniquely well-positioned to take advantage of AI technology, largely because they are already used to dealing with huge volumes of data on which AI and machine learning (ML) rely. Since this isnβt a passing fad, itβs important for telcos to play the long game with AI and consider less-explored domains that could unlock new revenue streams."
},
{
"code": null,
"e": 2068,
"s": 1809,
"text": "AI and ML require vast quantities of data to function correctly, but the data must be of sufficient quality, too. If the right amount of good-quality data is not available, decisions recommended by an AI or ML model are unlikely to be accurate or successful."
},
{
"code": null,
"e": 2314,
"s": 2068,
"text": "On a positive note, telcos do have access to large quantities of data, perhaps more than companies in most other industries. However, the struggle lies in capturing the right dataset and storing them with the degree of granularity needed for ML."
},
{
"code": null,
"e": 2660,
"s": 2314,
"text": "It is one thing to have high-quality data collected in a traditional way, but it is another to get this data into a specific way which you might need to solve a use case. Most telcos operatorβs web page today, consists of a vast number of choices, which in turn becomes increasingly hard for a customer to find his/her desired choice of product."
},
{
"code": null,
"e": 2858,
"s": 2660,
"text": "Donβt you think it would be substantial if the same web page could automatically give you recommendations on various add-on products/bundles based on choices made by existing customers in the past?"
},
{
"code": null,
"e": 3252,
"s": 2858,
"text": "Recommendation systems can be fine-tuned to cater to user profiles/preferences based on the choices of other users. The advantage of this system is to suggest the right items (base plans or add-on products) to particular users, based on their explicit and implicit preferences by applying an information filtering algorithm. The algorithm that I have used for implementation is called Apriori."
},
{
"code": null,
"e": 3401,
"s": 3252,
"text": "Apriori Algorithm β It is simply the study of customer transaction database to determine dependencies between purchases of different plans/products."
},
{
"code": null,
"e": 3459,
"s": 3401,
"text": "In other words, it is the study of βwhat goes with whatβ."
},
{
"code": null,
"e": 3985,
"s": 3459,
"text": "The availability of detailed information on customer transactions has led to the development of techniques that automatically look for associations between items that are stored in the database. Example β data collected about customer transactions regarding each plan/base package along with the add-on products are captured by the network operator in their database. Such databases consist of a large number of transaction records where each record lists either the base plan or the add-on product purchased by the customer."
},
{
"code": null,
"e": 4382,
"s": 3985,
"text": "By performing basic EDA on customer transaction data using Python, it is very likely to observe that there are certain base packages/plans that appear more often than the rest. Hence it would be a good idea to display a popular list of base packages as a first step. Given all the data is stored in a pandas dataframe βdfβ, we can get the list of popular base-packages/plans using the code below."
},
{
"code": null,
"e": 4421,
"s": 4382,
"text": "df[\"BASE_PACKAGE_NAME\"].value_counts()"
},
{
"code": null,
"e": 4554,
"s": 4421,
"text": "Getting this data into a form where each record lists all the items bought by the user wouldnβt be much of a challenge using Python."
},
{
"code": null,
"e": 4723,
"s": 4554,
"text": "At this stage, we would be interested to know if certain groups of items are consistently purchased together, which can be found with the help of the Apriori algorithm."
},
{
"code": null,
"e": 5037,
"s": 4723,
"text": "#Convert the dataframe to a listrecords = df.values.tolist()#Generate association rules with required #minimum support, confidence and liftfrom apyori import aprioriassociation_rules = apriori(records, min_support=0.3346, min_confidence=0.20, min_lift=3, min_length=3)association_results = list(association_rules)"
},
{
"code": null,
"e": 5279,
"s": 5037,
"text": "There are four performance metrics within the Apriori algorithm. These parameters are used to exclude association rules in the result that have support and confidence lower than the minimum support, confidence, lift, or length, respectively."
},
{
"code": null,
"e": 5419,
"s": 5279,
"text": "min_support β A float value between 0 and 1; used to select the items with support value greater than the value specified in the parameter."
},
{
"code": null,
"e": 5559,
"s": 5419,
"text": "min_support β A float value between 0 and 1; used to select the items with support value greater than the value specified in the parameter."
},
{
"code": null,
"e": 5724,
"s": 5559,
"text": "2. min_confidence β A float value between 0 and 1; used to filter those rules that have confidence greater than the confidence threshold specified in the parameter."
},
{
"code": null,
"e": 5803,
"s": 5724,
"text": "3. min_lift β This specifies the minimum lift value for the shortlisted rules."
},
{
"code": null,
"e": 5919,
"s": 5803,
"text": "4. min_length β This specifies the minimum number of items that you want to see in your association rules itemsets."
},
{
"code": null,
"e": 6123,
"s": 5919,
"text": "The optimum values for min_support, min_confidence, and min_lift arguments can be set by trying out different values and checking whether they are producing valid association between the itemsets or not."
},
{
"code": null,
"e": 6360,
"s": 6123,
"text": "Obtaining association rules in a comprehensible format could be a challenge; hereβs how I overcame that. Note that βPredecessorβ is an item found within the data, whereas βSuccessorβ is an item found in combination with the Predecessor."
},
{
"code": null,
"e": 7289,
"s": 6360,
"text": "#Create a dataframe with all the necessary informationdf = pd.DataFrame(columns=('Items','Predecessor','Successor','Support','Confidence','Lift'))Support =[]Confidence = []Lift = []Items = []Predecessor= []Successor=[]for RelationRecord in association_results: for ordered_stat in RelationRecord.ordered_statistics: Support.append(RelationRecord.support) Items.append(RelationRecord.items) Predecessor.append(ordered_stat.items_base) Successor.append(ordered_stat.items_add) Confidence.append(ordered_stat.confidence) Lift.append(ordered_stat.lift)df['Items'] = list(map(set, Items)) df['Predecessor'] = list(map(set, Predecessor))df['Successor'] = list(map(set, Successor))df['Support'] = Supportdf['Confidence'] = Confidencedf['Lift']= Lift#Sort the dataframe based on confidence df.sort_values(by ='Confidence', ascending = False, inplace = True)"
},
{
"code": null,
"e": 7513,
"s": 7289,
"text": "Providing the right recommendations would be by picking the items in the βSuccessorβ column given that the βPredecessorβ column value is equal to the base-package name selected by the customer from the popular package list."
},
{
"code": null,
"e": 7865,
"s": 7513,
"text": "#Picking the records for a particular plan/base_package that has been selected by the customer on the GUIpackage_name = \"1GB/Day(24 day Validity)\"index=[]for key, value in df[\"Predecessor\"].iteritems(): if len(value) == 1 and package_name in value: print(key,value) index.append(key) recommendations = df[df.index.isin(index)]"
},
{
"code": null,
"e": 7876,
"s": 7865,
"text": "And voila!"
},
{
"code": null,
"e": 8021,
"s": 7876,
"text": "Note that the frequently bought percentage is the measure of confidence parameter, which is computed by the Apriori algorithm as stated earlier."
},
{
"code": null,
"e": 8743,
"s": 8021,
"text": "Being a part of the telecom industry for almost 5 years, I have seen that any AI initiative can have various technical and organizational questions; which is not very surprising as AI is such a pie-in-the-sky thing that you need to give the organization something tangible. Hence, making the leap from concept to live project or, making the move from piloting AI proof-of-concept projects to deploying live is a further challenge. The association-rule mining approach described in this blog proves the benefits of automated affinity analysis and is a fundamental business use-case for telcos in my opinion. It is critically important to have a clear understanding of what would constitute success from such an investment."
},
{
"code": null,
"e": 9394,
"s": 8743,
"text": "Taking a step further, the above implementation is limited to provide recommendations for new customers subscribing to the network via web-GUI/kiosk. The model can be improved by providing recommendations to existing/new customers by adding a clustering algorithm in the initial stage; which would segment customers based on age, salary, geographical data, etc. Additionally, some shortcomings of the Apriori algorithm are the profusion of rules that are generated and the fact that rare combinations of itemsets tend to be ignored, as they do not meet the minimum support requirements. Using a more robust algorithm would help to resolve this issue."
},
{
"code": null,
"e": 9417,
"s": 9394,
"text": "Thank you for reading!"
},
{
"code": null,
"e": 9454,
"s": 9417,
"text": "[1] https://www.appliedaicourse.com/"
},
{
"code": null,
"e": 9580,
"s": 9454,
"text": "[2] Telcos and AI: What it will take to create an AI-Driven Telecoms Industry β May 2019 by STL Partners, supported by Nokia."
},
{
"code": null,
"e": 9789,
"s": 9580,
"text": "[3] Research Article β Improving Top-NRecommendation Performance Using Missing Data by Beijing Research Center for Information Technology in Agriculture and School of Computer Science and Technology, Beijing."
}
] |
Basics of File Handling in C Programming
|
File Handling is the storing of data in a file using a program. In C programming language, the programs store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch data from a file to work with it in the program.
The operations that you can perform on a File in C are β
Creating a new file
Creating a new file
Opening an existing file
Opening an existing file
Reading data from an existing file
Reading data from an existing file
Writing data to a file
Writing data to a file
Moving data to a specific location on the file
Moving data to a specific location on the file
Closing the file
Closing the file
The fopen() function is used to create a new file or open an existing file in C. The fopen function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
file = fopen(βfile_nameβ, βmodeβ)
This is a common syntax for both opening and creating a file in C.
file_name β It is a string that specifies the name of the file that is to be opened or created using the fopen method. mode: It is a string (usually a single character ) that specifies the mode in which the file is to be opened. There are various modes available to open a file in C, we will learn about all of them later in this article.
The fopen function will create a new file when it will not find any file of the specified name in the specified location. Else, if the file is found it will be opened with the mode specified.
Letβs see can example which will make the concept clear,
Suppose we are opening a file named hello.txt using the fopen function. The following will be the statement,
file = fopen(βhello.txtβ, βwβ)
This will search for a file named hello.txt in the current directory. If the file exists, it will open the file otherwise it will create a new file named βhello.txtβ and open it with write mode (specified using βwβ).
Now, letβs see all types of modes that are available for us to read or write a file in C, and see code snippets that will show sample runs of the code.
Mode = βrβ β open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using r mode");
fclose(file);
return 0;
}
File opened successfully in read mode
We have created a file named hello.txt in our current directory but if we try to access other file then we will get βThe file is not present! cannot create a new file using r modeβ as output.
Mode = βrbβ β open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("program.txt", "rb")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using rb mode");
fclose(file);
return 0;
}
The file is not present! cannot create a new file using rb mode
Mode = βwβ β open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing.
If we open a file that contains some text in it, the contents will be overwritten.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w")){
printf("File opened successfully in write mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in write mode or a new file is created
You can see here, we have tried to open file βhelo.txtβ which is not present in the directory, still the function returned the success message because it has create a file named βhelo.txtβ.
Mode = βwbβ β open for writing in binary mode, this mode will open the file if present in the current directory for writing in binary mode i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary mode.
If we open a file that contains some text in it, the contents will be overwritten.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "wb")){
printf("File opened successfully in write in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in write in binary mode or a new file is created
Mode = βaβ β open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a")){
printf("File opened successfully in append mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in append mode or a new file is created
Mode = βabβ β open for append in binary, this mode will open the file if present in the current directory for writing in binary only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "ab")){
printf("File opened successfully in append in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in append in binary mode or a new file is created
Mode = βr+β β open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "r+")){
printf("File opened successfully in read and write both");
}
else
printf("The file is not present! cannot create a new file using r+ mode");
fclose(file);
return 0;
}
File opened successfully in read and write both
We have created a file named hello.txt in our current directory but if we try to access another file then we will get βThe file is not present! cannot create a new file using r+ modeβ as output.
Mode = βrb+β β open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it.
This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode.
If we open a file that contains some text in it and write something, the contents will be overwritten.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("program.txt", "rb+")){
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using rb+ mode");
fclose(file);
return 0;
}
The file is not present! cannot create a new file using rb+ mode
Mode = βwβ β open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will be overwritten.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("helo.txt", "w+")){
printf("File opened successfully in read-write mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in read-write mode or a new file is created
You can see here, we have tried to open file βhelo.txtβ which is not present in the directory, still the function returned the success message because it has create a file named βhelo.txtβ.
Mode = βwb+β : open for writing and reading in binary mode, this mode will open the file if present in the current directory for writing and reading in
binary mode. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary mode.
If we open a file that contains some text in it, the contents will be overwritten.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "wb+")){
printf("File opened successfully in read-write in binary mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in read-write in binary mode or a new file is created
Mode = βa+β β open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing.
If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "a+")){
printf("File opened successfully in read-append mode or a new file is created");
}
else
printf("Error!");
fclose(file);
return 0;
}
File opened successfully in read-append mode or a new file is created
Mode = βab+β β open for read and append in binary, this mode will open the file if present in the current directory for both reading and writing in binary. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "ab+")){
printf("File opened successfully in read-append in binary mode or a new file is created");
}
else
printf("Error!β);
fclose(file);
return 0;
}
File opened successfully in read-append mode or a new file is created
We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file.
Letβs see the working of each of the function β
The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it.
int fscanf(FILE *stream, const char *charPointer[])
FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
while(fscanf(file,"%s", str)!=EOF){
printf("%s", str);
}
}
else
printf("Error!β);
fclose(file);
return 0;
}
LearnprogrammingattutorialsPoint
The fget() function in C is used to read string from the stream.
char* fgets(char *string, int length, FILE *stream)
char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.
#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
printf("%s", fgets(str, 50, file));
}
fclose(file);
return 0;
}
Learn programming at tutorials Point
The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file.
char* fgetc(FILE *stream)
FILE *stream: It is the pointer to the opened file.
#include <stdio.h>
int main(){
FILE * file;
char str;
if (file = fopen("hello.txt", "r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return 0;
}
Learn programming at tutorials Point
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file.
Letβs see the working of each of the function β
The fprintf() function is used to write data to a file. It writes a set of characters in a file.
int fprintf(FILE *stream, char *string[])
FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fprintf(file, "tutorials Pointβ) >= 0)
printf("Write operation successful");
}
fclose(file);
return 0;
}
Write operation successful
The fputf() function in C can be used to write to a file. It is used to write a line (character line) to the file.
int fputs(const char *string, FILE *stream)
Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fputs("tutorials Point", file) >= 0)
printf("String written to the file successfully...");
}
fclose(file);
return 0;
}
String written to the file successfully...
The fputc() function is used to write a single character to the file.
int fputc(char character , FILE *stream)
char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
fputc('T', file);
}
fclose(file);
return 0;
}
βTβ is written to the file.
The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it.
fclose(FILE *stream)
FILE for *stream: It is the pointer to the opened file.
Live Demo
#include <stdio.h>
int main(){
FILE * file;
char string[300];
if (file = fopen("hello.txt", "a+")){
while(fscanf(file,"%s", string)!=EOF){
printf("%s", string);
}
fputs("Hello", file);
}
fclose(file);
return 0;
}
LearnprogrammingatTutorialsPoint
Learn programming at Tutorials PointHello
|
[
{
"code": null,
"e": 1323,
"s": 1062,
"text": "File Handling is the storing of data in a file using a program. In C programming language, the programs store results, and other data of the program to a file using file handling in C. Also, we can extract/fetch data from a file to work with it in the program."
},
{
"code": null,
"e": 1380,
"s": 1323,
"text": "The operations that you can perform on a File in C are β"
},
{
"code": null,
"e": 1400,
"s": 1380,
"text": "Creating a new file"
},
{
"code": null,
"e": 1420,
"s": 1400,
"text": "Creating a new file"
},
{
"code": null,
"e": 1445,
"s": 1420,
"text": "Opening an existing file"
},
{
"code": null,
"e": 1470,
"s": 1445,
"text": "Opening an existing file"
},
{
"code": null,
"e": 1505,
"s": 1470,
"text": "Reading data from an existing file"
},
{
"code": null,
"e": 1540,
"s": 1505,
"text": "Reading data from an existing file"
},
{
"code": null,
"e": 1563,
"s": 1540,
"text": "Writing data to a file"
},
{
"code": null,
"e": 1586,
"s": 1563,
"text": "Writing data to a file"
},
{
"code": null,
"e": 1633,
"s": 1586,
"text": "Moving data to a specific location on the file"
},
{
"code": null,
"e": 1680,
"s": 1633,
"text": "Moving data to a specific location on the file"
},
{
"code": null,
"e": 1697,
"s": 1680,
"text": "Closing the file"
},
{
"code": null,
"e": 1714,
"s": 1697,
"text": "Closing the file"
},
{
"code": null,
"e": 1853,
"s": 1714,
"text": "The fopen() function is used to create a new file or open an existing file in C. The fopen function is defined in the stdio.h header file."
},
{
"code": null,
"e": 1923,
"s": 1853,
"text": "Now, lets see the syntax for creation of a new file or opening a file"
},
{
"code": null,
"e": 1957,
"s": 1923,
"text": "file = fopen(βfile_nameβ, βmodeβ)"
},
{
"code": null,
"e": 2024,
"s": 1957,
"text": "This is a common syntax for both opening and creating a file in C."
},
{
"code": null,
"e": 2363,
"s": 2024,
"text": "file_name β It is a string that specifies the name of the file that is to be opened or created using the fopen method. mode: It is a string (usually a single character ) that specifies the mode in which the file is to be opened. There are various modes available to open a file in C, we will learn about all of them later in this article."
},
{
"code": null,
"e": 2555,
"s": 2363,
"text": "The fopen function will create a new file when it will not find any file of the specified name in the specified location. Else, if the file is found it will be opened with the mode specified."
},
{
"code": null,
"e": 2721,
"s": 2555,
"text": "Letβs see can example which will make the concept clear,\nSuppose we are opening a file named hello.txt using the fopen function. The following will be the statement,"
},
{
"code": null,
"e": 2752,
"s": 2721,
"text": "file = fopen(βhello.txtβ, βwβ)"
},
{
"code": null,
"e": 2969,
"s": 2752,
"text": "This will search for a file named hello.txt in the current directory. If the file exists, it will open the file otherwise it will create a new file named βhello.txtβ and open it with write mode (specified using βwβ)."
},
{
"code": null,
"e": 3121,
"s": 2969,
"text": "Now, letβs see all types of modes that are available for us to read or write a file in C, and see code snippets that will show sample runs of the code."
},
{
"code": null,
"e": 3288,
"s": 3121,
"text": "Mode = βrβ β open for reading, this mode will open the file for reading purpose only, i.e. the contents can only be viewed, nothing else like edits can be done to it."
},
{
"code": null,
"e": 3396,
"s": 3288,
"text": "This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode."
},
{
"code": null,
"e": 3660,
"s": 3396,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"r\")){\n printf(\"File opened successfully in read mode\");\n }\n else\n printf(\"The file is not present! cannot create a new file using r mode\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 3698,
"s": 3660,
"text": "File opened successfully in read mode"
},
{
"code": null,
"e": 3890,
"s": 3698,
"text": "We have created a file named hello.txt in our current directory but if we try to access other file then we will get βThe file is not present! cannot create a new file using r modeβ as output."
},
{
"code": null,
"e": 4083,
"s": 3890,
"text": "Mode = βrbβ β open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it."
},
{
"code": null,
"e": 4191,
"s": 4083,
"text": "This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode."
},
{
"code": null,
"e": 4459,
"s": 4191,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"program.txt\", \"rb\")){\n printf(\"File opened successfully in read mode\");\n }\n else\n printf(\"The file is not present! cannot create a new file using rb mode\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 4523,
"s": 4459,
"text": "The file is not present! cannot create a new file using rb mode"
},
{
"code": null,
"e": 4798,
"s": 4523,
"text": "Mode = βwβ β open for writing only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing."
},
{
"code": null,
"e": 4881,
"s": 4798,
"text": "If we open a file that contains some text in it, the contents will be overwritten."
},
{
"code": null,
"e": 4892,
"s": 4881,
"text": " Live Demo"
},
{
"code": null,
"e": 5125,
"s": 4892,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"helo.txt\", \"w\")){\n printf(\"File opened successfully in write mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 5189,
"s": 5125,
"text": "File opened successfully in write mode or a new file is created"
},
{
"code": null,
"e": 5379,
"s": 5189,
"text": "You can see here, we have tried to open file βhelo.txtβ which is not present in the directory, still the function returned the success message because it has create a file named βhelo.txtβ."
},
{
"code": null,
"e": 5690,
"s": 5379,
"text": "Mode = βwbβ β open for writing in binary mode, this mode will open the file if present in the current directory for writing in binary mode i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary mode."
},
{
"code": null,
"e": 5773,
"s": 5690,
"text": "If we open a file that contains some text in it, the contents will be overwritten."
},
{
"code": null,
"e": 5784,
"s": 5773,
"text": " Live Demo"
},
{
"code": null,
"e": 6029,
"s": 5784,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"wb\")){\n printf(\"File opened successfully in write in binary mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 6103,
"s": 6029,
"text": "File opened successfully in write in binary mode or a new file is created"
},
{
"code": null,
"e": 6536,
"s": 6103,
"text": "Mode = βaβ β open for append only, this mode will open the file if present in the current directory for writing only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file."
},
{
"code": null,
"e": 6547,
"s": 6536,
"text": " Live Demo"
},
{
"code": null,
"e": 6782,
"s": 6547,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"a\")){\n printf(\"File opened successfully in append mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 6847,
"s": 6782,
"text": "File opened successfully in append mode or a new file is created"
},
{
"code": null,
"e": 7147,
"s": 6847,
"text": "Mode = βabβ β open for append in binary, this mode will open the file if present in the current directory for writing in binary only i.e. reading operation cannot be performed. If the file is not present in the current directory, the program will create a new file and open it for writing in binary."
},
{
"code": null,
"e": 7306,
"s": 7147,
"text": "If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file."
},
{
"code": null,
"e": 7317,
"s": 7306,
"text": " Live Demo"
},
{
"code": null,
"e": 7563,
"s": 7317,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"ab\")){\n printf(\"File opened successfully in append in binary mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 7638,
"s": 7563,
"text": "File opened successfully in append in binary mode or a new file is created"
},
{
"code": null,
"e": 7820,
"s": 7638,
"text": "Mode = βr+β β open for reading and writing both, this mode will open the file for both reading and writing purposes i.e. both read and write operations can be performed to the file."
},
{
"code": null,
"e": 7928,
"s": 7820,
"text": "This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode."
},
{
"code": null,
"e": 8031,
"s": 7928,
"text": "If we open a file that contains some text in it and write something, the contents will be overwritten."
},
{
"code": null,
"e": 8307,
"s": 8031,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"r+\")){\n printf(\"File opened successfully in read and write both\");\n }\n else\n printf(\"The file is not present! cannot create a new file using r+ mode\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 8355,
"s": 8307,
"text": "File opened successfully in read and write both"
},
{
"code": null,
"e": 8550,
"s": 8355,
"text": "We have created a file named hello.txt in our current directory but if we try to access another file then we will get βThe file is not present! cannot create a new file using r+ modeβ as output."
},
{
"code": null,
"e": 8744,
"s": 8550,
"text": "Mode = βrb+β β open for reading in binary mode, this mode will open the file for reading in binary mode only, i.e. the contents can only be viewed and nothing else like edits can be done to it."
},
{
"code": null,
"e": 8852,
"s": 8744,
"text": "This mode cannot create a new file and open() returns NULL, if we try to create a new file using this mode."
},
{
"code": null,
"e": 8955,
"s": 8852,
"text": "If we open a file that contains some text in it and write something, the contents will be overwritten."
},
{
"code": null,
"e": 9225,
"s": 8955,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"program.txt\", \"rb+\")){\n printf(\"File opened successfully in read mode\");\n }\n else\n printf(\"The file is not present! cannot create a new file using rb+ mode\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 9290,
"s": 9225,
"text": "The file is not present! cannot create a new file using rb+ mode"
},
{
"code": null,
"e": 9563,
"s": 9290,
"text": "Mode = βwβ β open for writing and reading, this mode will open the file if present in the current directory for writing and reading operation both. If the file is not present in the current directory, the program will create a new file and open it for reading and writing."
},
{
"code": null,
"e": 9646,
"s": 9563,
"text": "If we open a file that contains some text in it, the contents will be overwritten."
},
{
"code": null,
"e": 9657,
"s": 9646,
"text": " Live Demo"
},
{
"code": null,
"e": 9896,
"s": 9657,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"helo.txt\", \"w+\")){\n printf(\"File opened successfully in read-write mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 9965,
"s": 9896,
"text": "File opened successfully in read-write mode or a new file is created"
},
{
"code": null,
"e": 10155,
"s": 9965,
"text": "You can see here, we have tried to open file βhelo.txtβ which is not present in the directory, still the function returned the success message because it has create a file named βhelo.txtβ."
},
{
"code": null,
"e": 10307,
"s": 10155,
"text": "Mode = βwb+β : open for writing and reading in binary mode, this mode will open the file if present in the current directory for writing and reading in"
},
{
"code": null,
"e": 10543,
"s": 10307,
"text": "binary mode. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary mode.\nIf we open a file that contains some text in it, the contents will be overwritten."
},
{
"code": null,
"e": 10554,
"s": 10543,
"text": " Live Demo"
},
{
"code": null,
"e": 10805,
"s": 10554,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"wb+\")){\n printf(\"File opened successfully in read-write in binary mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 10884,
"s": 10805,
"text": "File opened successfully in read-write in binary mode or a new file is created"
},
{
"code": null,
"e": 11144,
"s": 10884,
"text": "Mode = βa+β β open for read and append, this mode will open the file if present in the current directory for both reading and writing. If the file is not present in the current directory, the program will create a new file and open it for reading and writing."
},
{
"code": null,
"e": 11303,
"s": 11144,
"text": "If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file."
},
{
"code": null,
"e": 11314,
"s": 11303,
"text": " Live Demo"
},
{
"code": null,
"e": 11555,
"s": 11314,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"a+\")){\n printf(\"File opened successfully in read-append mode or a new file is created\");\n }\n else\n printf(\"Error!\");\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 11625,
"s": 11555,
"text": "File opened successfully in read-append mode or a new file is created"
},
{
"code": null,
"e": 12075,
"s": 11625,
"text": "Mode = βab+β β open for read and append in binary, this mode will open the file if present in the current directory for both reading and writing in binary. If the file is not present in the current directory, the program will create a new file and open it for reading and writing in binary. If we open a file that contains some text in it, the contents will not be overwritten; instead the new text will be added after the existing text in the file."
},
{
"code": null,
"e": 12327,
"s": 12075,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"ab+\")){\n printf(\"File opened successfully in read-append in binary mode or a new file is created\");\n }\n else\n printf(\"Error!β);\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 12397,
"s": 12327,
"text": "File opened successfully in read-append mode or a new file is created"
},
{
"code": null,
"e": 12575,
"s": 12397,
"text": "We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used to read contents of a file.\nLetβs see the working of each of the function β"
},
{
"code": null,
"e": 12723,
"s": 12575,
"text": "The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when all the content of the file are read by it."
},
{
"code": null,
"e": 12775,
"s": 12723,
"text": "int fscanf(FILE *stream, const char *charPointer[])"
},
{
"code": null,
"e": 12869,
"s": 12775,
"text": "FILE *stream: the pointer to the opened file.\nconst char *charPointer[]: string of character."
},
{
"code": null,
"e": 13121,
"s": 12869,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n char str[500];\n if (file = fopen(\"hello.txt\", \"r\")){\n while(fscanf(file,\"%s\", str)!=EOF){\n printf(\"%s\", str);\n }\n }\n else\n printf(\"Error!β);\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 13154,
"s": 13121,
"text": "LearnprogrammingattutorialsPoint"
},
{
"code": null,
"e": 13219,
"s": 13154,
"text": "The fget() function in C is used to read string from the stream."
},
{
"code": null,
"e": 13271,
"s": 13219,
"text": "char* fgets(char *string, int length, FILE *stream)"
},
{
"code": null,
"e": 13471,
"s": 13271,
"text": "char *string: It is a string which will store the data from the string.\nint length: It is an int which gives the length of string to be considered.\nFILE *stream: It is the pointer to the opened file."
},
{
"code": null,
"e": 13655,
"s": 13471,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n char str[500];\n if (file = fopen(\"hello.txt\", \"r\")){\n printf(\"%s\", fgets(str, 50, file));\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 13692,
"s": 13655,
"text": "Learn programming at tutorials Point"
},
{
"code": null,
"e": 13840,
"s": 13692,
"text": "The fgetc() function in C is used to return a single character from the file. It gets a character from the file and returns EOF at the end of file."
},
{
"code": null,
"e": 13866,
"s": 13840,
"text": "char* fgetc(FILE *stream)"
},
{
"code": null,
"e": 13918,
"s": 13866,
"text": "FILE *stream: It is the pointer to the opened file."
},
{
"code": null,
"e": 14115,
"s": 13918,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n char str;\n if (file = fopen(\"hello.txt\", \"r\")){\n while((str=fgetc(file))!=EOF)\n printf(\"%c\",str);\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 14152,
"s": 14115,
"text": "Learn programming at tutorials Point"
},
{
"code": null,
"e": 14276,
"s": 14152,
"text": "We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write contents to a file."
},
{
"code": null,
"e": 14324,
"s": 14276,
"text": "Letβs see the working of each of the function β"
},
{
"code": null,
"e": 14421,
"s": 14324,
"text": "The fprintf() function is used to write data to a file. It writes a set of characters in a file."
},
{
"code": null,
"e": 14463,
"s": 14421,
"text": "int fprintf(FILE *stream, char *string[])"
},
{
"code": null,
"e": 14596,
"s": 14463,
"text": "FILE for *stream: It is the pointer to the opened file.\nchar *string[]: It is the character array that we want to write in the file."
},
{
"code": null,
"e": 14812,
"s": 14596,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"w\")){\n if(fprintf(file, \"tutorials Pointβ) >= 0)\n printf(\"Write operation successful\");\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 14839,
"s": 14812,
"text": "Write operation successful"
},
{
"code": null,
"e": 14954,
"s": 14839,
"text": "The fputf() function in C can be used to write to a file. It is used to write a line (character line) to the file."
},
{
"code": null,
"e": 14998,
"s": 14954,
"text": "int fputs(const char *string, FILE *stream)"
},
{
"code": null,
"e": 15140,
"s": 14998,
"text": "Constant char *string[]: It is the character array that we want to write in the file.\nFILE for *stream: It is the pointer to the opened file."
},
{
"code": null,
"e": 15151,
"s": 15140,
"text": " Live Demo"
},
{
"code": null,
"e": 15381,
"s": 15151,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"w\")){\n if(fputs(\"tutorials Point\", file) >= 0)\n printf(\"String written to the file successfully...\");\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 15424,
"s": 15381,
"text": "String written to the file successfully..."
},
{
"code": null,
"e": 15494,
"s": 15424,
"text": "The fputc() function is used to write a single character to the file."
},
{
"code": null,
"e": 15535,
"s": 15494,
"text": "int fputc(char character , FILE *stream)"
},
{
"code": null,
"e": 15663,
"s": 15535,
"text": "char character : It is the character that we want to write in the file.\nFILE for *stream: It is the pointer to the opened file."
},
{
"code": null,
"e": 15674,
"s": 15663,
"text": " Live Demo"
},
{
"code": null,
"e": 15822,
"s": 15674,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n if (file = fopen(\"hello.txt\", \"w\")){\n fputc('T', file);\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 15850,
"s": 15822,
"text": "βTβ is written to the file."
},
{
"code": null,
"e": 16014,
"s": 15850,
"text": "The fclose() function is used to close the open file. We should close the file after performing operations on it to save the operations that we have applied to it."
},
{
"code": null,
"e": 16035,
"s": 16014,
"text": "fclose(FILE *stream)"
},
{
"code": null,
"e": 16091,
"s": 16035,
"text": "FILE for *stream: It is the pointer to the opened file."
},
{
"code": null,
"e": 16102,
"s": 16091,
"text": " Live Demo"
},
{
"code": null,
"e": 16360,
"s": 16102,
"text": "#include <stdio.h>\nint main(){\n FILE * file;\n char string[300];\n if (file = fopen(\"hello.txt\", \"a+\")){\n while(fscanf(file,\"%s\", string)!=EOF){\n printf(\"%s\", string);\n }\n fputs(\"Hello\", file);\n }\n fclose(file);\n return 0;\n}"
},
{
"code": null,
"e": 16393,
"s": 16360,
"text": "LearnprogrammingatTutorialsPoint"
},
{
"code": null,
"e": 16435,
"s": 16393,
"text": "Learn programming at Tutorials PointHello"
}
] |
FormatException in C#
|
FomatException is thrown when the format of an argument is invalid.
Let us see an example.
When we set a value other than int to int.Parse() method, then FormatException is thrown as shown below β
Live Demo
using System;
class Demo {
static void Main() {
string str = "3.5";
int res = int.Parse(str);
}
}
The following error is thrown when the above program is compiled since we have passed a value other than integer.
Unhandled Exception:
System.FormatException: Input string was not in a correct format.
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "FomatException is thrown when the format of an argument is invalid."
},
{
"code": null,
"e": 1153,
"s": 1130,
"text": "Let us see an example."
},
{
"code": null,
"e": 1259,
"s": 1153,
"text": "When we set a value other than int to int.Parse() method, then FormatException is thrown as shown below β"
},
{
"code": null,
"e": 1270,
"s": 1259,
"text": " Live Demo"
},
{
"code": null,
"e": 1386,
"s": 1270,
"text": "using System;\nclass Demo {\n static void Main() {\n string str = \"3.5\";\n int res = int.Parse(str);\n }\n}"
},
{
"code": null,
"e": 1500,
"s": 1386,
"text": "The following error is thrown when the above program is compiled since we have passed a value other than integer."
},
{
"code": null,
"e": 1587,
"s": 1500,
"text": "Unhandled Exception:\nSystem.FormatException: Input string was not in a correct format."
}
] |
Statistics in Python β Using Chi-Square for Feature Selection | by Wei-Meng Lee | Towards Data Science
|
In my previous two articles, I talked about how to measure correlations between the various columns in your dataset and how to detect multicollinearity between them:
towardsdatascience.com
towardsdatascience.com
However, these techniques are useful when the variables you are trying to compare with are continuous. How do you compare them if your variables are categorical? In this article, I will explain to you how you can test two categorical columns in your dataset to determine if they are dependent on each other (i.e. correlated). We will use a statistics test known as chi-square (commonly written as Ο2).
Before we start our discussion on chi-square, here is a quick summary of the test methods that can be used for testing the various types of variables:
The chi-square (Ο2) statistics is a way to check the relationship between two categorical nominal variables.
Nominal variables contains values that have no intrinsic ordering. Examples of nominal variables are sex, race, eye color, skin color, etc. Ordinal variables, on the other hand, contains values that have ordering. Examples of ordinal variables are grade, education level, economic status, etc.
The key idea behind the chi-square test is to compare the observed values in your data to the expected values and see if they are related or not. In particular, it is a useful way to check if two categorical nominal variables are correlated. This is particularly important in machine learning where you only want features that are correlated to the target to be used for training.
There are two types of chi-square tests:
Chi-Square Goodness of Fit Test β test if one variable is likely to come from a given distribution.
Chi-Square Test of Independence β test if two variables might be correlated or not.
Check out https://www.jmp.com/en_us/statistics-knowledge-portal/chi-square-test.html for a more detailed discusson of the above two chi-square tests.
When comparing to see if two categorical variables are correlated, you will use the Chi-Square Test of Independence.
To use the chi-square test, you need to perform the following steps:
Define your null hypothesis and alternate hypothesis. They are:
Define your null hypothesis and alternate hypothesis. They are:
H0 (Null Hypothesis) β that the 2 categorical variables being compared are independent of each other.
H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other.
2. Decide on the Ξ± value. This is the risk that you are willing to take in drawing the wrong conclusion. As an example, say you set Ξ±=0.05 when testing for independence. This means you are undertaking a 5% risk of concluding that two variables are independent when in reality they are not.
3. Calculate the chi-square score using the two categorical variables and use it to calculate the p-value. A low p-value means there is a high correlation between your two categorical variables (they are dependent on each other). The p-value is calculated from the chi-square score. The p-value will tell you if your tests results are significant or not.
In a chi-square analysis, the p-value is the probability of obtaining a chi-square as large or larger than that in the current experiment and yet the data will still support the hypothesis. It is the probability of deviations from what was expected being due to mere chance. In general a p-value of 0.05 or greater is considered critical, anything less means the deviations are significant and the hypothesis being tested must be rejected.
Source: https://passel2.unl.edu/view/lesson/9beaa382bf7e/8
To calculate the p-value, you need two pieces of information:
Degrees of freedom β the number of categories minus 1
Chi-square score.
If the p-value obtained is:
< 0.05 (the Ξ± value you have chosen) you reject the H0 (Null Hypothesis) and accept the H1 (Alternate Hypothesis). This means the two categorical variables are dependent.
> 0.05 you accept the H0 (Null Hypothesis) and reject the H1 (Alternate Hypothesis). This means the two categorical variables are independent.
In the case of feature selection for machine learning, you would want the feature that is being compared to the target to have a low p-value (less than 0.05), as this means that the feature is dependent on (correlated to) the target.
With the chi-square score that is calculated, you can also use it to refer to a chi-square table to see if your score falls within the rejection region or the acceptance region.
All the steps above sound a little vague, and the best way to really understand how chi-square works is to look at an example. In the next section, I will use the Titanic dataset and apply the chi-square test on a few of the features and see how if they are correlated to the target.
A good way to understand a new topic is to go through the concepts using an example. For this, I am going to use the classic Titanic dataset (https://www.kaggle.com/tedllh/titanic-train).
The Titanic dataset is often used in machine learning to demonstrate how to build a machine learning model and use it to make predictions. In particular, the dataset contains several features (Pclass, Sex, Age, Embarked, etc) and one target (Survived). Several features in the dataset are categorical variables:
Pclass-the class of cabin that the passenger was in
Sex-the sex of the passenger
Embarked-the port of embarkation
Survived-if the passenger survived the disaster
Because this article explores the relationships between categorical features and targets, we are only interested in those columns that contains categorical values.
Now that you have obtained the dataset, letβs load it up in a Pandas DataFrame:
import pandas as pdimport numpy as npdf = pd.read_csv('titanic_train.csv')df.sample(5)
There are some columns that are not really useful and hence we will proceed to drop them. Also, there are some missing values so letβs drop all those rows with empty values:
df.drop(columns=['PassengerId','Name', 'Ticket','Fare','Cabin'], inplace=True)df.dropna(inplace=True)df
We will also add one more column named Alone, based on the Parch (Parent or children) and Sibsp (Siblings or spouse) columns. The idea we want to explore is if being alone affects the surviability of the passenger. So Alone is 1 if both Parch and Sibsp are 0, else it is 0:
df['Alone'] = (df['Parch'] + df['SibSp']).apply( lambda x: 1 if x == 0 else 0)df
Now that the data is cleaned, letβs try to visualize how the sex of passengers is related to their survival of the accident:
import seaborn as snssns.barplot(x='Sex', y='Survived', data=df, ci=None)
The Sex column contains nominal data(i.e. ranking is not important).
From the above figure, you can see that of all the female passengers, more than 70% survived; of all the men, about 20% survived. Seems like there exists a very strong relationship between the Sex and Survived features. To confirm this, we will use the chi-square test to confirm this later on.
How about Pclass and Survived? Are they related?
sns.barplot(x='Pclass', y='Survived', data=df, ci=None)
Perhaps unsurprisingly, it shows that the higher the Pclass that the passenger was in, the higher the survival rate of the passenger.
The next feature of interest is if the place of embarkation determines who survives and who doesnβt:
sns.barplot(x='Embarked', y='Survived', data=df, ci=None)
From the chart it seems like more people who embarked from C (Cherbourg) survived.
C = Cherbourg; Q = Queenstown; S = Southampton
You also want to know if being alone on the trip makes one more survivable:
ax = sns.barplot(x='Alone', y='Survived', data=df, ci=None) ax.set_xticklabels(['Not Alone','Alone'])
You can see that if one is with their family, he/she will have a higher chances of survival.
Now that we have visualized the relationships between the categorical features against the target (Survived), we want to now visualize the relationships between each feature. Before you can do that, you need to convert the label values in the Sex and Embarked columns to numeric. To do that, you can make use of the LabelEncoder class in sklearn:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import preprocessingle = preprocessing.LabelEncoder()le.fit(df['Sex'])df['Sex'] = le.transform(df['Sex'])sex_labels = dict(zip(le.classes_, le.transform(le.classes_)))print(sex_labels)le.fit(df['Embarked'])df['Embarked'] = le.transform(df['Embarked'])embarked_labels = dict(zip(le.classes_, le.transform(le.classes_)))print(embarked_labels)
The above code snippet label-encodes the Sex and Embarked columns. The output shows the mappings of the values for each column, which is very useful later when performing predictions:
{'female': 0, 'male': 1}{'C': 0, 'Q': 1, 'S': 2}
The following statements show the relationship between Embarked and Sex:
ax = sns.barplot(x='Embarked', y='Sex', data=df, ci=None)ax.set_xticklabels(embarked_labels.keys())
Seems like more males boarded from Southampton (S) than in Queenstown (Q) and Cherbourg (C).
How about Embarked and Alone?
ax = sns.barplot(x='Embarked', y='Alone', data=df, ci=None)ax.set_xticklabels(embarked_labels.keys())
Seems like a large proportion of those who embarked from Queenstown are alone.
And finally, letβs see the relationship between Sex and Alone:
ax = sns.barplot(x='Sex', y='Alone', data=df, ci=None)ax.set_xticklabels(sex_labels.keys())
As you can see, there are more males than females who are alone for the trip.
You now define your null hypothesis and alternate hypothesis. As explained earlier, they are:
H0 (Null Hypothesis) β that the 2 categorical variables to be compared are independent of each other.
H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other.
And you draw your conclusions based on the following p-value conditions:
p < 0.05 β this means the two categorical variables are correlated.
p > 0.05 β this means the two categorical variables are not correlated.
Letβs manually go through the steps in calculating the Ο2 values. The first step is to create a contingency table. Using the Sex and Survived columns as example, you first create a contingency table:
The contingency table above displays the frequency distribution of the two categorical columns β Sex and Survived.
The Degrees of Freedom is next calculated as (number of rows -1) * (number of columns -1). In this example, the degree of freedom is (2β1)*(2β1) = 1.
Once the contingency table is created, sum up all the rows and columns, like this:
The above is your Observed values.
Next, you are going to calculate the Expected values. Here is how they are calculated:
Replace each value in the observed value with the product of the sum of its column and the sum of its row, divided by the total sum.
The following figure shows how the first value is calculated:
The next figure shows how the second value is calculated:
Here is the result for the Expected values:
Then, calculate the chi-square value for each cell using the formula for Ο2:
Applying this formula to the Observed and Expected values, you get the chi-square values:
The chi-square score is the grand total of the chi-square values:
You can use the following websites to verify if the numbers are correct:
Chi-Square Calculator β https://www.mathsisfun.com/data/chi-square-calculator.html
The Python implementation for the above steps is contained within the following chi2_by_hand() function:
def chi2_by_hand(df, col1, col2): #---create the contingency table--- df_cont = pd.crosstab(index = df[col1], columns = df[col2]) display(df_cont) #---calculate degree of freedom--- degree_f = (df_cont.shape[0]-1) * (df_cont.shape[1]-1) #---sum up the totals for row and columns--- df_cont.loc[:,'Total']= df_cont.sum(axis=1) df_cont.loc['Total']= df_cont.sum() print('---Observed (O)---') display(df_cont) #---create the expected value dataframe--- df_exp = df_cont.copy() df_exp.iloc[:,:] = np.multiply.outer( df_cont.sum(1).values,df_cont.sum().values) / df_cont.sum().sum() print('---Expected (E)---') display(df_exp) # calculate chi-square values df_chi2 = ((df_cont - df_exp)**2) / df_exp df_chi2.loc[:,'Total']= df_chi2.sum(axis=1) df_chi2.loc['Total']= df_chi2.sum() print('---Chi-Square---') display(df_chi2) #---get chi-square score--- chi_square_score = df_chi2.iloc[:-1,:-1].sum().sum() return chi_square_score, degree_f
The chi2_by_hand() function takes in three argument β the dataframe containing all your columns, followed by two strings containing the names of the two columns you are comparing against. It returns a tuple β the chi-square score, plus the degrees of freedom.
Letβs now test the above function using the Titanic dataset. First, letβs compare the Sex and the Survived columns:
chi_score, degree_f = chi2_by_hand(df,'Sex','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}')
You will see the following result:
Chi2_score: 205.1364846934008, Degrees of freedom: 1
Using the chi-square score, you can now decide if you will accept or reject the null hypothesis using the chi-square distribution curve:
The x-axis represents the Ο2 score. The area that is to the right of the critical chi-square region is known as the rejection region. Area to the left of it is known as the acceptance region. If the chi-square score that you have obtained falls in the acceptance region, the null hypothesis is accepted; else the alternate hypothesis is accepted.
So how do you obtain the critical chi-square region? For this, you have to check the chi-square table:
You can check out the Chi-Square Table at https://www.mathsisfun.com/data/chi-square-table.html
This is how you use the chi-square table. With your Ξ± set to be 0.05, and 1 degrees of freedom, the critical chi-square region is 3.84 (refer to the chart above). Putting this value into the chi-square distribution curve, you can conclude that:
As the calculated chi-square value (205) is greater than 3.84, it therefore falls in the rejection region, and hence the null hypothesis is rejected and the alternate hypothesis is accepted.
Recalling our alternate hypothesis as: H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other.
This means that the Sex and Survived columns are dependent on each other.
As a practise, you can use the chi2_by_hand() function on the other features.
The previous section shows how you can accept or reject the null hypothesis by examining the chi-square score and comparing it with the chi-square distribution curve.
An alternative way to accept or reject the null hypothesis is by using the p-value. Remember, the p-value can be calculated using the chi-square score and the degrees of freedom.
For simplicity, we shall not go into the details of how to calculate the p-value by hand.
In Python, you can calculate the p-value using the stats moduleβs sf() function:
def chi2_by_hand(df, col1, col2): #---create the contingency table--- df_cont = pd.crosstab(index = df[col1], columns = df[col2]) display(df_cont) ... chi_square_score = df_chi2.iloc[:-1,:-1].sum().sum() #---calculate the p-value--- from scipy import stats p = stats.distributions.chi2.sf(chi_square_score, degree_f) return chi_square_score, degree_f, p
You can now call the chi2_by_hand() function and get both the chi_square score, degrees of freedom, and p-value:
chi_score, degree_f, p = chi2_by_hand(df,'Sex','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')
The above code results in the following p-value:
Chi2_score: 205.1364846934008, Degrees of freedom: 1, p-value: 1.581266384342472e-46
As a quick recap, you accept or reject the hypotheses and form your conclusion based on the following p-value conditions:
p < 0.05 β this means the two categorical variables are correlated.
p > 0.05 β this means the two categorical variables are not correlated.
And since p < 0.05 β this means the two categorical variables are correlated.
Letβs try out the categorical columns that contains nominal values:
chi_score, degree_f, p = chi2_by_hand(df,'Embarked','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')# Chi2_score: 27.918691003688615, Degrees of freedom: 2, # p-value: 8.660306799267924e-07chi_score, degree_f, p = chi2_by_hand(df,'Alone','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')# Chi2_score: 28.406341862069905, Degrees of freedom: 1, # p-value: 9.834262807301776e-08
Since the p-values for both Embarked and Alone are < 0.05, you can conclude that both the Embarked and Alone features are correlated to the Survived target, and should be included for training in your model.
In this article, I have gone through a brief explanation of how the chi-square statistics test works, and how you can apply it to the Titanic dataset. A few notes of caution would be useful here:
While the Pearsonβs coefficient and Spearmanβs rank coefficient measure the strength of an association between two variables, the chi-square test measures the significance of the association between two variables. What it tells you is whether the relationship you found in the sample is likely to exist in the population, or how likely it is by chance due to sampling error.The chi-square test is sensitive to small frequencies in your contingency table. Generally, if a cell in your contingency table has a frequency of 5 or less, the chi-square test will lead to errors in conclusion. Also, chi-square test should not be used if the sample size is less than 50.
While the Pearsonβs coefficient and Spearmanβs rank coefficient measure the strength of an association between two variables, the chi-square test measures the significance of the association between two variables. What it tells you is whether the relationship you found in the sample is likely to exist in the population, or how likely it is by chance due to sampling error.
The chi-square test is sensitive to small frequencies in your contingency table. Generally, if a cell in your contingency table has a frequency of 5 or less, the chi-square test will lead to errors in conclusion. Also, chi-square test should not be used if the sample size is less than 50.
I hope you now have a better understanding of how chi-square works and how it can be used for feature selection in machine learning. See you in my next article!
|
[
{
"code": null,
"e": 338,
"s": 172,
"text": "In my previous two articles, I talked about how to measure correlations between the various columns in your dataset and how to detect multicollinearity between them:"
},
{
"code": null,
"e": 361,
"s": 338,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 384,
"s": 361,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 786,
"s": 384,
"text": "However, these techniques are useful when the variables you are trying to compare with are continuous. How do you compare them if your variables are categorical? In this article, I will explain to you how you can test two categorical columns in your dataset to determine if they are dependent on each other (i.e. correlated). We will use a statistics test known as chi-square (commonly written as Ο2)."
},
{
"code": null,
"e": 937,
"s": 786,
"text": "Before we start our discussion on chi-square, here is a quick summary of the test methods that can be used for testing the various types of variables:"
},
{
"code": null,
"e": 1046,
"s": 937,
"text": "The chi-square (Ο2) statistics is a way to check the relationship between two categorical nominal variables."
},
{
"code": null,
"e": 1340,
"s": 1046,
"text": "Nominal variables contains values that have no intrinsic ordering. Examples of nominal variables are sex, race, eye color, skin color, etc. Ordinal variables, on the other hand, contains values that have ordering. Examples of ordinal variables are grade, education level, economic status, etc."
},
{
"code": null,
"e": 1721,
"s": 1340,
"text": "The key idea behind the chi-square test is to compare the observed values in your data to the expected values and see if they are related or not. In particular, it is a useful way to check if two categorical nominal variables are correlated. This is particularly important in machine learning where you only want features that are correlated to the target to be used for training."
},
{
"code": null,
"e": 1762,
"s": 1721,
"text": "There are two types of chi-square tests:"
},
{
"code": null,
"e": 1862,
"s": 1762,
"text": "Chi-Square Goodness of Fit Test β test if one variable is likely to come from a given distribution."
},
{
"code": null,
"e": 1946,
"s": 1862,
"text": "Chi-Square Test of Independence β test if two variables might be correlated or not."
},
{
"code": null,
"e": 2096,
"s": 1946,
"text": "Check out https://www.jmp.com/en_us/statistics-knowledge-portal/chi-square-test.html for a more detailed discusson of the above two chi-square tests."
},
{
"code": null,
"e": 2213,
"s": 2096,
"text": "When comparing to see if two categorical variables are correlated, you will use the Chi-Square Test of Independence."
},
{
"code": null,
"e": 2282,
"s": 2213,
"text": "To use the chi-square test, you need to perform the following steps:"
},
{
"code": null,
"e": 2346,
"s": 2282,
"text": "Define your null hypothesis and alternate hypothesis. They are:"
},
{
"code": null,
"e": 2410,
"s": 2346,
"text": "Define your null hypothesis and alternate hypothesis. They are:"
},
{
"code": null,
"e": 2512,
"s": 2410,
"text": "H0 (Null Hypothesis) β that the 2 categorical variables being compared are independent of each other."
},
{
"code": null,
"e": 2617,
"s": 2512,
"text": "H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other."
},
{
"code": null,
"e": 2907,
"s": 2617,
"text": "2. Decide on the Ξ± value. This is the risk that you are willing to take in drawing the wrong conclusion. As an example, say you set Ξ±=0.05 when testing for independence. This means you are undertaking a 5% risk of concluding that two variables are independent when in reality they are not."
},
{
"code": null,
"e": 3262,
"s": 2907,
"text": "3. Calculate the chi-square score using the two categorical variables and use it to calculate the p-value. A low p-value means there is a high correlation between your two categorical variables (they are dependent on each other). The p-value is calculated from the chi-square score. The p-value will tell you if your tests results are significant or not."
},
{
"code": null,
"e": 3702,
"s": 3262,
"text": "In a chi-square analysis, the p-value is the probability of obtaining a chi-square as large or larger than that in the current experiment and yet the data will still support the hypothesis. It is the probability of deviations from what was expected being due to mere chance. In general a p-value of 0.05 or greater is considered critical, anything less means the deviations are significant and the hypothesis being tested must be rejected."
},
{
"code": null,
"e": 3761,
"s": 3702,
"text": "Source: https://passel2.unl.edu/view/lesson/9beaa382bf7e/8"
},
{
"code": null,
"e": 3823,
"s": 3761,
"text": "To calculate the p-value, you need two pieces of information:"
},
{
"code": null,
"e": 3877,
"s": 3823,
"text": "Degrees of freedom β the number of categories minus 1"
},
{
"code": null,
"e": 3895,
"s": 3877,
"text": "Chi-square score."
},
{
"code": null,
"e": 3923,
"s": 3895,
"text": "If the p-value obtained is:"
},
{
"code": null,
"e": 4094,
"s": 3923,
"text": "< 0.05 (the Ξ± value you have chosen) you reject the H0 (Null Hypothesis) and accept the H1 (Alternate Hypothesis). This means the two categorical variables are dependent."
},
{
"code": null,
"e": 4237,
"s": 4094,
"text": "> 0.05 you accept the H0 (Null Hypothesis) and reject the H1 (Alternate Hypothesis). This means the two categorical variables are independent."
},
{
"code": null,
"e": 4471,
"s": 4237,
"text": "In the case of feature selection for machine learning, you would want the feature that is being compared to the target to have a low p-value (less than 0.05), as this means that the feature is dependent on (correlated to) the target."
},
{
"code": null,
"e": 4649,
"s": 4471,
"text": "With the chi-square score that is calculated, you can also use it to refer to a chi-square table to see if your score falls within the rejection region or the acceptance region."
},
{
"code": null,
"e": 4933,
"s": 4649,
"text": "All the steps above sound a little vague, and the best way to really understand how chi-square works is to look at an example. In the next section, I will use the Titanic dataset and apply the chi-square test on a few of the features and see how if they are correlated to the target."
},
{
"code": null,
"e": 5121,
"s": 4933,
"text": "A good way to understand a new topic is to go through the concepts using an example. For this, I am going to use the classic Titanic dataset (https://www.kaggle.com/tedllh/titanic-train)."
},
{
"code": null,
"e": 5433,
"s": 5121,
"text": "The Titanic dataset is often used in machine learning to demonstrate how to build a machine learning model and use it to make predictions. In particular, the dataset contains several features (Pclass, Sex, Age, Embarked, etc) and one target (Survived). Several features in the dataset are categorical variables:"
},
{
"code": null,
"e": 5485,
"s": 5433,
"text": "Pclass-the class of cabin that the passenger was in"
},
{
"code": null,
"e": 5514,
"s": 5485,
"text": "Sex-the sex of the passenger"
},
{
"code": null,
"e": 5547,
"s": 5514,
"text": "Embarked-the port of embarkation"
},
{
"code": null,
"e": 5595,
"s": 5547,
"text": "Survived-if the passenger survived the disaster"
},
{
"code": null,
"e": 5759,
"s": 5595,
"text": "Because this article explores the relationships between categorical features and targets, we are only interested in those columns that contains categorical values."
},
{
"code": null,
"e": 5839,
"s": 5759,
"text": "Now that you have obtained the dataset, letβs load it up in a Pandas DataFrame:"
},
{
"code": null,
"e": 5926,
"s": 5839,
"text": "import pandas as pdimport numpy as npdf = pd.read_csv('titanic_train.csv')df.sample(5)"
},
{
"code": null,
"e": 6100,
"s": 5926,
"text": "There are some columns that are not really useful and hence we will proceed to drop them. Also, there are some missing values so letβs drop all those rows with empty values:"
},
{
"code": null,
"e": 6212,
"s": 6100,
"text": "df.drop(columns=['PassengerId','Name', 'Ticket','Fare','Cabin'], inplace=True)df.dropna(inplace=True)df"
},
{
"code": null,
"e": 6486,
"s": 6212,
"text": "We will also add one more column named Alone, based on the Parch (Parent or children) and Sibsp (Siblings or spouse) columns. The idea we want to explore is if being alone affects the surviability of the passenger. So Alone is 1 if both Parch and Sibsp are 0, else it is 0:"
},
{
"code": null,
"e": 6584,
"s": 6486,
"text": "df['Alone'] = (df['Parch'] + df['SibSp']).apply( lambda x: 1 if x == 0 else 0)df"
},
{
"code": null,
"e": 6709,
"s": 6584,
"text": "Now that the data is cleaned, letβs try to visualize how the sex of passengers is related to their survival of the accident:"
},
{
"code": null,
"e": 6788,
"s": 6709,
"text": "import seaborn as snssns.barplot(x='Sex', y='Survived', data=df, ci=None) "
},
{
"code": null,
"e": 6857,
"s": 6788,
"text": "The Sex column contains nominal data(i.e. ranking is not important)."
},
{
"code": null,
"e": 7152,
"s": 6857,
"text": "From the above figure, you can see that of all the female passengers, more than 70% survived; of all the men, about 20% survived. Seems like there exists a very strong relationship between the Sex and Survived features. To confirm this, we will use the chi-square test to confirm this later on."
},
{
"code": null,
"e": 7201,
"s": 7152,
"text": "How about Pclass and Survived? Are they related?"
},
{
"code": null,
"e": 7257,
"s": 7201,
"text": "sns.barplot(x='Pclass', y='Survived', data=df, ci=None)"
},
{
"code": null,
"e": 7391,
"s": 7257,
"text": "Perhaps unsurprisingly, it shows that the higher the Pclass that the passenger was in, the higher the survival rate of the passenger."
},
{
"code": null,
"e": 7492,
"s": 7391,
"text": "The next feature of interest is if the place of embarkation determines who survives and who doesnβt:"
},
{
"code": null,
"e": 7550,
"s": 7492,
"text": "sns.barplot(x='Embarked', y='Survived', data=df, ci=None)"
},
{
"code": null,
"e": 7633,
"s": 7550,
"text": "From the chart it seems like more people who embarked from C (Cherbourg) survived."
},
{
"code": null,
"e": 7680,
"s": 7633,
"text": "C = Cherbourg; Q = Queenstown; S = Southampton"
},
{
"code": null,
"e": 7756,
"s": 7680,
"text": "You also want to know if being alone on the trip makes one more survivable:"
},
{
"code": null,
"e": 7861,
"s": 7756,
"text": "ax = sns.barplot(x='Alone', y='Survived', data=df, ci=None) ax.set_xticklabels(['Not Alone','Alone'])"
},
{
"code": null,
"e": 7954,
"s": 7861,
"text": "You can see that if one is with their family, he/she will have a higher chances of survival."
},
{
"code": null,
"e": 8301,
"s": 7954,
"text": "Now that we have visualized the relationships between the categorical features against the target (Survived), we want to now visualize the relationships between each feature. Before you can do that, you need to convert the label values in the Sex and Embarked columns to numeric. To do that, you can make use of the LabelEncoder class in sklearn:"
},
{
"code": null,
"e": 8766,
"s": 8301,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom sklearn import preprocessingle = preprocessing.LabelEncoder()le.fit(df['Sex'])df['Sex'] = le.transform(df['Sex'])sex_labels = dict(zip(le.classes_, le.transform(le.classes_)))print(sex_labels)le.fit(df['Embarked'])df['Embarked'] = le.transform(df['Embarked'])embarked_labels = dict(zip(le.classes_, le.transform(le.classes_)))print(embarked_labels)"
},
{
"code": null,
"e": 8950,
"s": 8766,
"text": "The above code snippet label-encodes the Sex and Embarked columns. The output shows the mappings of the values for each column, which is very useful later when performing predictions:"
},
{
"code": null,
"e": 8999,
"s": 8950,
"text": "{'female': 0, 'male': 1}{'C': 0, 'Q': 1, 'S': 2}"
},
{
"code": null,
"e": 9072,
"s": 8999,
"text": "The following statements show the relationship between Embarked and Sex:"
},
{
"code": null,
"e": 9172,
"s": 9072,
"text": "ax = sns.barplot(x='Embarked', y='Sex', data=df, ci=None)ax.set_xticklabels(embarked_labels.keys())"
},
{
"code": null,
"e": 9265,
"s": 9172,
"text": "Seems like more males boarded from Southampton (S) than in Queenstown (Q) and Cherbourg (C)."
},
{
"code": null,
"e": 9295,
"s": 9265,
"text": "How about Embarked and Alone?"
},
{
"code": null,
"e": 9397,
"s": 9295,
"text": "ax = sns.barplot(x='Embarked', y='Alone', data=df, ci=None)ax.set_xticklabels(embarked_labels.keys())"
},
{
"code": null,
"e": 9476,
"s": 9397,
"text": "Seems like a large proportion of those who embarked from Queenstown are alone."
},
{
"code": null,
"e": 9539,
"s": 9476,
"text": "And finally, letβs see the relationship between Sex and Alone:"
},
{
"code": null,
"e": 9631,
"s": 9539,
"text": "ax = sns.barplot(x='Sex', y='Alone', data=df, ci=None)ax.set_xticklabels(sex_labels.keys())"
},
{
"code": null,
"e": 9709,
"s": 9631,
"text": "As you can see, there are more males than females who are alone for the trip."
},
{
"code": null,
"e": 9803,
"s": 9709,
"text": "You now define your null hypothesis and alternate hypothesis. As explained earlier, they are:"
},
{
"code": null,
"e": 9905,
"s": 9803,
"text": "H0 (Null Hypothesis) β that the 2 categorical variables to be compared are independent of each other."
},
{
"code": null,
"e": 10010,
"s": 9905,
"text": "H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other."
},
{
"code": null,
"e": 10083,
"s": 10010,
"text": "And you draw your conclusions based on the following p-value conditions:"
},
{
"code": null,
"e": 10151,
"s": 10083,
"text": "p < 0.05 β this means the two categorical variables are correlated."
},
{
"code": null,
"e": 10223,
"s": 10151,
"text": "p > 0.05 β this means the two categorical variables are not correlated."
},
{
"code": null,
"e": 10423,
"s": 10223,
"text": "Letβs manually go through the steps in calculating the Ο2 values. The first step is to create a contingency table. Using the Sex and Survived columns as example, you first create a contingency table:"
},
{
"code": null,
"e": 10538,
"s": 10423,
"text": "The contingency table above displays the frequency distribution of the two categorical columns β Sex and Survived."
},
{
"code": null,
"e": 10688,
"s": 10538,
"text": "The Degrees of Freedom is next calculated as (number of rows -1) * (number of columns -1). In this example, the degree of freedom is (2β1)*(2β1) = 1."
},
{
"code": null,
"e": 10771,
"s": 10688,
"text": "Once the contingency table is created, sum up all the rows and columns, like this:"
},
{
"code": null,
"e": 10806,
"s": 10771,
"text": "The above is your Observed values."
},
{
"code": null,
"e": 10893,
"s": 10806,
"text": "Next, you are going to calculate the Expected values. Here is how they are calculated:"
},
{
"code": null,
"e": 11026,
"s": 10893,
"text": "Replace each value in the observed value with the product of the sum of its column and the sum of its row, divided by the total sum."
},
{
"code": null,
"e": 11088,
"s": 11026,
"text": "The following figure shows how the first value is calculated:"
},
{
"code": null,
"e": 11146,
"s": 11088,
"text": "The next figure shows how the second value is calculated:"
},
{
"code": null,
"e": 11190,
"s": 11146,
"text": "Here is the result for the Expected values:"
},
{
"code": null,
"e": 11267,
"s": 11190,
"text": "Then, calculate the chi-square value for each cell using the formula for Ο2:"
},
{
"code": null,
"e": 11357,
"s": 11267,
"text": "Applying this formula to the Observed and Expected values, you get the chi-square values:"
},
{
"code": null,
"e": 11423,
"s": 11357,
"text": "The chi-square score is the grand total of the chi-square values:"
},
{
"code": null,
"e": 11496,
"s": 11423,
"text": "You can use the following websites to verify if the numbers are correct:"
},
{
"code": null,
"e": 11579,
"s": 11496,
"text": "Chi-Square Calculator β https://www.mathsisfun.com/data/chi-square-calculator.html"
},
{
"code": null,
"e": 11684,
"s": 11579,
"text": "The Python implementation for the above steps is contained within the following chi2_by_hand() function:"
},
{
"code": null,
"e": 12747,
"s": 11684,
"text": "def chi2_by_hand(df, col1, col2): #---create the contingency table--- df_cont = pd.crosstab(index = df[col1], columns = df[col2]) display(df_cont) #---calculate degree of freedom--- degree_f = (df_cont.shape[0]-1) * (df_cont.shape[1]-1) #---sum up the totals for row and columns--- df_cont.loc[:,'Total']= df_cont.sum(axis=1) df_cont.loc['Total']= df_cont.sum() print('---Observed (O)---') display(df_cont) #---create the expected value dataframe--- df_exp = df_cont.copy() df_exp.iloc[:,:] = np.multiply.outer( df_cont.sum(1).values,df_cont.sum().values) / df_cont.sum().sum() print('---Expected (E)---') display(df_exp) # calculate chi-square values df_chi2 = ((df_cont - df_exp)**2) / df_exp df_chi2.loc[:,'Total']= df_chi2.sum(axis=1) df_chi2.loc['Total']= df_chi2.sum() print('---Chi-Square---') display(df_chi2) #---get chi-square score--- chi_square_score = df_chi2.iloc[:-1,:-1].sum().sum() return chi_square_score, degree_f"
},
{
"code": null,
"e": 13007,
"s": 12747,
"text": "The chi2_by_hand() function takes in three argument β the dataframe containing all your columns, followed by two strings containing the names of the two columns you are comparing against. It returns a tuple β the chi-square score, plus the degrees of freedom."
},
{
"code": null,
"e": 13123,
"s": 13007,
"text": "Letβs now test the above function using the Titanic dataset. First, letβs compare the Sex and the Survived columns:"
},
{
"code": null,
"e": 13244,
"s": 13123,
"text": "chi_score, degree_f = chi2_by_hand(df,'Sex','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}')"
},
{
"code": null,
"e": 13279,
"s": 13244,
"text": "You will see the following result:"
},
{
"code": null,
"e": 13332,
"s": 13279,
"text": "Chi2_score: 205.1364846934008, Degrees of freedom: 1"
},
{
"code": null,
"e": 13469,
"s": 13332,
"text": "Using the chi-square score, you can now decide if you will accept or reject the null hypothesis using the chi-square distribution curve:"
},
{
"code": null,
"e": 13816,
"s": 13469,
"text": "The x-axis represents the Ο2 score. The area that is to the right of the critical chi-square region is known as the rejection region. Area to the left of it is known as the acceptance region. If the chi-square score that you have obtained falls in the acceptance region, the null hypothesis is accepted; else the alternate hypothesis is accepted."
},
{
"code": null,
"e": 13919,
"s": 13816,
"text": "So how do you obtain the critical chi-square region? For this, you have to check the chi-square table:"
},
{
"code": null,
"e": 14015,
"s": 13919,
"text": "You can check out the Chi-Square Table at https://www.mathsisfun.com/data/chi-square-table.html"
},
{
"code": null,
"e": 14260,
"s": 14015,
"text": "This is how you use the chi-square table. With your Ξ± set to be 0.05, and 1 degrees of freedom, the critical chi-square region is 3.84 (refer to the chart above). Putting this value into the chi-square distribution curve, you can conclude that:"
},
{
"code": null,
"e": 14451,
"s": 14260,
"text": "As the calculated chi-square value (205) is greater than 3.84, it therefore falls in the rejection region, and hence the null hypothesis is rejected and the alternate hypothesis is accepted."
},
{
"code": null,
"e": 14595,
"s": 14451,
"text": "Recalling our alternate hypothesis as: H1 (Alternate Hypothesis) β that the 2 categorical variables being compared are dependent on each other."
},
{
"code": null,
"e": 14669,
"s": 14595,
"text": "This means that the Sex and Survived columns are dependent on each other."
},
{
"code": null,
"e": 14747,
"s": 14669,
"text": "As a practise, you can use the chi2_by_hand() function on the other features."
},
{
"code": null,
"e": 14914,
"s": 14747,
"text": "The previous section shows how you can accept or reject the null hypothesis by examining the chi-square score and comparing it with the chi-square distribution curve."
},
{
"code": null,
"e": 15093,
"s": 14914,
"text": "An alternative way to accept or reject the null hypothesis is by using the p-value. Remember, the p-value can be calculated using the chi-square score and the degrees of freedom."
},
{
"code": null,
"e": 15183,
"s": 15093,
"text": "For simplicity, we shall not go into the details of how to calculate the p-value by hand."
},
{
"code": null,
"e": 15264,
"s": 15183,
"text": "In Python, you can calculate the p-value using the stats moduleβs sf() function:"
},
{
"code": null,
"e": 15653,
"s": 15264,
"text": "def chi2_by_hand(df, col1, col2): #---create the contingency table--- df_cont = pd.crosstab(index = df[col1], columns = df[col2]) display(df_cont) ... chi_square_score = df_chi2.iloc[:-1,:-1].sum().sum() #---calculate the p-value--- from scipy import stats p = stats.distributions.chi2.sf(chi_square_score, degree_f) return chi_square_score, degree_f, p"
},
{
"code": null,
"e": 15766,
"s": 15653,
"text": "You can now call the chi2_by_hand() function and get both the chi_square score, degrees of freedom, and p-value:"
},
{
"code": null,
"e": 15904,
"s": 15766,
"text": "chi_score, degree_f, p = chi2_by_hand(df,'Sex','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')"
},
{
"code": null,
"e": 15953,
"s": 15904,
"text": "The above code results in the following p-value:"
},
{
"code": null,
"e": 16038,
"s": 15953,
"text": "Chi2_score: 205.1364846934008, Degrees of freedom: 1, p-value: 1.581266384342472e-46"
},
{
"code": null,
"e": 16160,
"s": 16038,
"text": "As a quick recap, you accept or reject the hypotheses and form your conclusion based on the following p-value conditions:"
},
{
"code": null,
"e": 16228,
"s": 16160,
"text": "p < 0.05 β this means the two categorical variables are correlated."
},
{
"code": null,
"e": 16300,
"s": 16228,
"text": "p > 0.05 β this means the two categorical variables are not correlated."
},
{
"code": null,
"e": 16378,
"s": 16300,
"text": "And since p < 0.05 β this means the two categorical variables are correlated."
},
{
"code": null,
"e": 16446,
"s": 16378,
"text": "Letβs try out the categorical columns that contains nominal values:"
},
{
"code": null,
"e": 16906,
"s": 16446,
"text": "chi_score, degree_f, p = chi2_by_hand(df,'Embarked','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')# Chi2_score: 27.918691003688615, Degrees of freedom: 2, # p-value: 8.660306799267924e-07chi_score, degree_f, p = chi2_by_hand(df,'Alone','Survived')print(f'Chi2_score: {chi_score}, Degrees of freedom: {degree_f}, p-value: {p}')# Chi2_score: 28.406341862069905, Degrees of freedom: 1, # p-value: 9.834262807301776e-08"
},
{
"code": null,
"e": 17114,
"s": 16906,
"text": "Since the p-values for both Embarked and Alone are < 0.05, you can conclude that both the Embarked and Alone features are correlated to the Survived target, and should be included for training in your model."
},
{
"code": null,
"e": 17310,
"s": 17114,
"text": "In this article, I have gone through a brief explanation of how the chi-square statistics test works, and how you can apply it to the Titanic dataset. A few notes of caution would be useful here:"
},
{
"code": null,
"e": 17974,
"s": 17310,
"text": "While the Pearsonβs coefficient and Spearmanβs rank coefficient measure the strength of an association between two variables, the chi-square test measures the significance of the association between two variables. What it tells you is whether the relationship you found in the sample is likely to exist in the population, or how likely it is by chance due to sampling error.The chi-square test is sensitive to small frequencies in your contingency table. Generally, if a cell in your contingency table has a frequency of 5 or less, the chi-square test will lead to errors in conclusion. Also, chi-square test should not be used if the sample size is less than 50."
},
{
"code": null,
"e": 18349,
"s": 17974,
"text": "While the Pearsonβs coefficient and Spearmanβs rank coefficient measure the strength of an association between two variables, the chi-square test measures the significance of the association between two variables. What it tells you is whether the relationship you found in the sample is likely to exist in the population, or how likely it is by chance due to sampling error."
},
{
"code": null,
"e": 18639,
"s": 18349,
"text": "The chi-square test is sensitive to small frequencies in your contingency table. Generally, if a cell in your contingency table has a frequency of 5 or less, the chi-square test will lead to errors in conclusion. Also, chi-square test should not be used if the sample size is less than 50."
}
] |
Query Salesforce Data in Python using intake-salesforce | by Sophia Yang | Towards Data Science
|
A Salesforce database can be a hot mess. The figure below illustrates the relationship among some of the data tables in Salesforce. As you can see, the relationship among data tables (i.e., objects) can be complicated and hard to work with. I wrote a blog post previously on how to understand and query Salesforce data using the Salesforce Object Query Language (SOQL) through a Python API simple-salesforce. Salesforce Object Query Language (SOQL) is a SQL-like language that is designed specifically for the relational data in Salesforce and it is not the easiest to understand and write for people who are not familiar with the Salesforce database. Thus, I wrote an intake driver to load Salesforce data to help people query Salesforce data easily.
Intake was developed by Anaconda in 2018. It is a lightweight data catalog and data access library. It helps users to access data and share data more productively. Specifically, Intake has the following key features that make it desirable to data scientists:
Intake loads data from various data sources and provides descriptions of your data in Intake catalogs.
Caching helps to load data faster.
Intake allows users to create a data package easily.
Graphic Interface helps with easy data exploration.
Intake loads data from various data formats and allows users to create plugins/drivers for new file formats.
The intake ecosystem currently includes more than 30 intake drivers that help users to load data from different sources with a uniform API.
More information on how to use intake can be found in the intake documentation.
Before we get started on intake-salesforce, we need to get some Salesforce credential information:
Username
Password
Security token: can be found under Settings β Personal β Reset My Security Token
Instance: YOUR_COMPANY_NAME.lightning.force.com
To install intake-salesforce, run the following
conda install intake-salesforce -c conda-forge
or pip install intake-salesforce
To get a catalog of tables in Salesforce, we use the intake.open_salesforce_catalog method:
Now we have a list of 1003 tables, which we can read using catalog.TABLE_NAME.read() and return Pandas dataframes in memory. For example, let's read in the "Account" table (not real data):
There are 48 columns in the Account table. Note that the column names ending with __c are all custom objects in Salesforce, which means in this case, our Salesforce admin creates a variable object called βARR__cβ in the Account table object.
Similarly, we can read in other tables (e.g., Opportunity) and merge the Account table with the Opportunity table (again, not real data shown below). To be clear which variables belong to which table, I added βacc_β in front of the Account variables and βopp_β in front of the Opportunity variables. Here we see the merged table has 90 columns.
How do we load data from various sources in a consistent manner? We are going to show an example to load a local .csv file, a group of parquet files that are stored on AWS, and Salesforce data.
The key feature and concept of Intake are the catalog files, which is βa YAML specification file which contains a list of named entries describing how to load data sourcesβ (https://intake.readthedocs.io/en/latest/catalog.html). In the βload_data.yamlβ example below, we defined three data sources: example_csv_data, example_s3_data, and salesforce_catalog. Under each data source, we listed its intake driver, arguments, and other information. Note that we are loading all data as Pandas dataframes, other data types and partitioned/parallel access are also possible with Intake.
To load data from these three data sources, we can simply open this yaml file as the catalog catand read in data as follows:
Read .csv file: cat.example_csv_data.read()
Read .parquet file: cat.example_s3_data(year=xxx, month=xxx).read() . Note that we need to conda install intake-parquet s3fs python-snappyfirst, and also note we are able to pass in arguments as parameters.
Read Salesforce data: cat.salesforce_catalog shows a list of Salesforce tables and cat.salesforce_catalog.TABLE_NAME.read() reads in the specified table.
In summary, intake-salesforce provides an easy way for users to see a catalog of tables in Salesforce and read in specific data tables as Pandas dataframes. Intake catalog allows users to load data from various sources consistently. Hope you enjoy using Intake and Intake-Salesforce. Thanks!
Credit: Special thanks to Martin Durant, Albert DeFusco, and Stan Seibert for the guidance and feedback in developing intake-Salesforce and writing this article.
https://intake.readthedocs.io/ https://www.anaconda.com/intake-taking-the-pain-out-of-data-access/ https://martindurant.github.io/blog/flurry-of-drivers/ https://medium.com/swlh/query-salesforce-data-in-python-e290a00e3cba https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.htm
By Sophia Yang on July 1, 2021
|
[
{
"code": null,
"e": 923,
"s": 171,
"text": "A Salesforce database can be a hot mess. The figure below illustrates the relationship among some of the data tables in Salesforce. As you can see, the relationship among data tables (i.e., objects) can be complicated and hard to work with. I wrote a blog post previously on how to understand and query Salesforce data using the Salesforce Object Query Language (SOQL) through a Python API simple-salesforce. Salesforce Object Query Language (SOQL) is a SQL-like language that is designed specifically for the relational data in Salesforce and it is not the easiest to understand and write for people who are not familiar with the Salesforce database. Thus, I wrote an intake driver to load Salesforce data to help people query Salesforce data easily."
},
{
"code": null,
"e": 1182,
"s": 923,
"text": "Intake was developed by Anaconda in 2018. It is a lightweight data catalog and data access library. It helps users to access data and share data more productively. Specifically, Intake has the following key features that make it desirable to data scientists:"
},
{
"code": null,
"e": 1285,
"s": 1182,
"text": "Intake loads data from various data sources and provides descriptions of your data in Intake catalogs."
},
{
"code": null,
"e": 1320,
"s": 1285,
"text": "Caching helps to load data faster."
},
{
"code": null,
"e": 1373,
"s": 1320,
"text": "Intake allows users to create a data package easily."
},
{
"code": null,
"e": 1425,
"s": 1373,
"text": "Graphic Interface helps with easy data exploration."
},
{
"code": null,
"e": 1534,
"s": 1425,
"text": "Intake loads data from various data formats and allows users to create plugins/drivers for new file formats."
},
{
"code": null,
"e": 1674,
"s": 1534,
"text": "The intake ecosystem currently includes more than 30 intake drivers that help users to load data from different sources with a uniform API."
},
{
"code": null,
"e": 1754,
"s": 1674,
"text": "More information on how to use intake can be found in the intake documentation."
},
{
"code": null,
"e": 1853,
"s": 1754,
"text": "Before we get started on intake-salesforce, we need to get some Salesforce credential information:"
},
{
"code": null,
"e": 1862,
"s": 1853,
"text": "Username"
},
{
"code": null,
"e": 1871,
"s": 1862,
"text": "Password"
},
{
"code": null,
"e": 1952,
"s": 1871,
"text": "Security token: can be found under Settings β Personal β Reset My Security Token"
},
{
"code": null,
"e": 2000,
"s": 1952,
"text": "Instance: YOUR_COMPANY_NAME.lightning.force.com"
},
{
"code": null,
"e": 2048,
"s": 2000,
"text": "To install intake-salesforce, run the following"
},
{
"code": null,
"e": 2095,
"s": 2048,
"text": "conda install intake-salesforce -c conda-forge"
},
{
"code": null,
"e": 2128,
"s": 2095,
"text": "or pip install intake-salesforce"
},
{
"code": null,
"e": 2220,
"s": 2128,
"text": "To get a catalog of tables in Salesforce, we use the intake.open_salesforce_catalog method:"
},
{
"code": null,
"e": 2409,
"s": 2220,
"text": "Now we have a list of 1003 tables, which we can read using catalog.TABLE_NAME.read() and return Pandas dataframes in memory. For example, let's read in the \"Account\" table (not real data):"
},
{
"code": null,
"e": 2651,
"s": 2409,
"text": "There are 48 columns in the Account table. Note that the column names ending with __c are all custom objects in Salesforce, which means in this case, our Salesforce admin creates a variable object called βARR__cβ in the Account table object."
},
{
"code": null,
"e": 2996,
"s": 2651,
"text": "Similarly, we can read in other tables (e.g., Opportunity) and merge the Account table with the Opportunity table (again, not real data shown below). To be clear which variables belong to which table, I added βacc_β in front of the Account variables and βopp_β in front of the Opportunity variables. Here we see the merged table has 90 columns."
},
{
"code": null,
"e": 3190,
"s": 2996,
"text": "How do we load data from various sources in a consistent manner? We are going to show an example to load a local .csv file, a group of parquet files that are stored on AWS, and Salesforce data."
},
{
"code": null,
"e": 3771,
"s": 3190,
"text": "The key feature and concept of Intake are the catalog files, which is βa YAML specification file which contains a list of named entries describing how to load data sourcesβ (https://intake.readthedocs.io/en/latest/catalog.html). In the βload_data.yamlβ example below, we defined three data sources: example_csv_data, example_s3_data, and salesforce_catalog. Under each data source, we listed its intake driver, arguments, and other information. Note that we are loading all data as Pandas dataframes, other data types and partitioned/parallel access are also possible with Intake."
},
{
"code": null,
"e": 3896,
"s": 3771,
"text": "To load data from these three data sources, we can simply open this yaml file as the catalog catand read in data as follows:"
},
{
"code": null,
"e": 3940,
"s": 3896,
"text": "Read .csv file: cat.example_csv_data.read()"
},
{
"code": null,
"e": 4147,
"s": 3940,
"text": "Read .parquet file: cat.example_s3_data(year=xxx, month=xxx).read() . Note that we need to conda install intake-parquet s3fs python-snappyfirst, and also note we are able to pass in arguments as parameters."
},
{
"code": null,
"e": 4301,
"s": 4147,
"text": "Read Salesforce data: cat.salesforce_catalog shows a list of Salesforce tables and cat.salesforce_catalog.TABLE_NAME.read() reads in the specified table."
},
{
"code": null,
"e": 4593,
"s": 4301,
"text": "In summary, intake-salesforce provides an easy way for users to see a catalog of tables in Salesforce and read in specific data tables as Pandas dataframes. Intake catalog allows users to load data from various sources consistently. Hope you enjoy using Intake and Intake-Salesforce. Thanks!"
},
{
"code": null,
"e": 4755,
"s": 4593,
"text": "Credit: Special thanks to Martin Durant, Albert DeFusco, and Stan Seibert for the guidance and feedback in developing intake-Salesforce and writing this article."
},
{
"code": null,
"e": 5079,
"s": 4755,
"text": "https://intake.readthedocs.io/ https://www.anaconda.com/intake-taking-the-pain-out-of-data-access/ https://martindurant.github.io/blog/flurry-of-drivers/ https://medium.com/swlh/query-salesforce-data-in-python-e290a00e3cba https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql.htm"
}
] |
Google Summer Trainee Engineering Program(STEP) Interview Experience - GeeksforGeeks
|
04 Jun, 2019
Telephonic Interview 1. (Telephonic + Google Docs Shared)
Q1. Given an array of integers, you need to find the local maxima.
Example : [1 3 5 4 7 10 6]
Output: 5 or 10
Explanation: Any of the local maxima can be the output.
Here 5 is greater than 3 and 4, 10 is greater than 7 and 6.
Hint : Refer this article.
Q2. Given a sequence of brackets, how will you identify if its valid or not.
Example : ({[][]})
Output: Valid
Explanation: Every opening bracket has a closing bracket.
Example: ({[]]})
Output: Invalid
Explanation : Every opening bracket does not have a closing bracket.
Hint : Refer this article.Telephonic Interview 2. (Telephonic + Google Docs Shared)
Q1. There are 2 arrays. Smaller is of size m and has m elements in sorted order. The bigger array isof size m+n, where there are only n elements in initial n positions in sorted order. So, last mpositions are empty in the bigger array. Insert smaller arrayβs m elements in m + n array has all numbers in sorted order.
Example :
Input Array N[]={5, 9, 15, 20,,,,,, } n=4
M[]={1, 3, 6, 8, 19, 35} m=6
Output array N[]={1, 3, 5, 6, 8, 9, 15, 19, 20, 35}
Hint : Refer this article.
Q2. Given a binary tree with integer values, find the sub-path with the maximum value in it
Example :
1
/ \
2 3
/ \ / \
4 5 6 7
Output : Max path is 5, 2, 1, 3, 7
Explanation : 5+2+1+3+7=18 is the maximum value that can spanned.
-100
/ \
2 3
/ \ / \
4 5 6 7
Output : Max path is 6, 3, 7
Explanation : 6+3+7=16 is the maximum value that can spanned.
Hint : Refer this article.
Google
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
OLX Interview Experience (On-Campus)
Zoho Interview Experience (Off-Campus ) 2022
Zoho Corporation (Internship cum Offer Experience )
Difference Between ON Page and OFF Page SEO
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1
|
[
{
"code": null,
"e": 25234,
"s": 25206,
"text": "\n04 Jun, 2019"
},
{
"code": null,
"e": 25292,
"s": 25234,
"text": "Telephonic Interview 1. (Telephonic + Google Docs Shared)"
},
{
"code": null,
"e": 25359,
"s": 25292,
"text": "Q1. Given an array of integers, you need to find the local maxima."
},
{
"code": null,
"e": 25523,
"s": 25359,
"text": "Example : [1 3 5 4 7 10 6]\n\nOutput: 5 or 10\n\nExplanation: Any of the local maxima can be the output. \nHere 5 is greater than 3 and 4, 10 is greater than 7 and 6. \n"
},
{
"code": null,
"e": 25550,
"s": 25523,
"text": "Hint : Refer this article."
},
{
"code": null,
"e": 25627,
"s": 25550,
"text": "Q2. Given a sequence of brackets, how will you identify if its valid or not."
},
{
"code": null,
"e": 25828,
"s": 25627,
"text": "Example : ({[][]})\n\nOutput: Valid\n\nExplanation: Every opening bracket has a closing bracket.\n\nExample: ({[]]}) \n\nOutput: Invalid \n\nExplanation : Every opening bracket does not have a closing bracket.\n"
},
{
"code": null,
"e": 25912,
"s": 25828,
"text": "Hint : Refer this article.Telephonic Interview 2. (Telephonic + Google Docs Shared)"
},
{
"code": null,
"e": 26230,
"s": 25912,
"text": "Q1. There are 2 arrays. Smaller is of size m and has m elements in sorted order. The bigger array isof size m+n, where there are only n elements in initial n positions in sorted order. So, last mpositions are empty in the bigger array. Insert smaller arrayβs m elements in m + n array has all numbers in sorted order."
},
{
"code": null,
"e": 26387,
"s": 26230,
"text": "Example : \nInput Array N[]={5, 9, 15, 20,,,,,, } n=4\n M[]={1, 3, 6, 8, 19, 35} m=6\nOutput array N[]={1, 3, 5, 6, 8, 9, 15, 19, 20, 35}\n"
},
{
"code": null,
"e": 26414,
"s": 26387,
"text": "Hint : Refer this article."
},
{
"code": null,
"e": 26506,
"s": 26414,
"text": "Q2. Given a binary tree with integer values, find the sub-path with the maximum value in it"
},
{
"code": null,
"e": 26856,
"s": 26506,
"text": " \nExample : \n 1\n / \\ \n 2 3\n / \\ / \\\n 4 5 6 7\n\nOutput : Max path is 5, 2, 1, 3, 7\nExplanation : 5+2+1+3+7=18 is the maximum value that can spanned.\n\n -100\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n\nOutput : Max path is 6, 3, 7\nExplanation : 6+3+7=16 is the maximum value that can spanned.\n"
},
{
"code": null,
"e": 26883,
"s": 26856,
"text": "Hint : Refer this article."
},
{
"code": null,
"e": 26890,
"s": 26883,
"text": "Google"
},
{
"code": null,
"e": 26901,
"s": 26890,
"text": "Internship"
},
{
"code": null,
"e": 26923,
"s": 26901,
"text": "Interview Experiences"
},
{
"code": null,
"e": 26930,
"s": 26923,
"text": "Google"
},
{
"code": null,
"e": 27028,
"s": 26930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27037,
"s": 27028,
"text": "Comments"
},
{
"code": null,
"e": 27050,
"s": 27037,
"text": "Old Comments"
},
{
"code": null,
"e": 27109,
"s": 27050,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 27146,
"s": 27109,
"text": "OLX Interview Experience (On-Campus)"
},
{
"code": null,
"e": 27191,
"s": 27146,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 27243,
"s": 27191,
"text": "Zoho Corporation (Internship cum Offer Experience )"
},
{
"code": null,
"e": 27287,
"s": 27243,
"text": "Difference Between ON Page and OFF Page SEO"
},
{
"code": null,
"e": 27314,
"s": 27287,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 27374,
"s": 27314,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 27424,
"s": 27374,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 27460,
"s": 27424,
"text": "Difference between ANN, CNN and RNN"
}
] |
Calculating Customer Lifetime Values using a Shifted-Beta-Geometric model | by Farshad Lavassani Miraftab | Towards Data Science
|
Customer lifetime values (CLV) are a critical metric considered to be a companyβs north star metric and all in-compassing KPI, used to inform:
marketing campaigns β how much should we spend to acquire customers?
customer segmentation β who are our most valuable customers and what are their demographic and behavioral traits?
overall health of the business β how is our CLV changing over time?
total company value β how can we estimate the value of our existing and future customers?
But what is CLV?
The present value of all future cash flows of a current customer
At a high-level, in order to estimate your CLV youβll need to understand two simple customer attributes; a customers lifetime and the revenue they generate on a recurring basis. The more a customer pays and the longer they stay as a customer, the greater their CLV.
This post will focus on the more challenging component β measuring a customers lifetime, which requires you to understand your businesses current retention rates.
This post aims to provide an end-to-end robust methodology to estimate customer lifetime values.
The formula below is traditionally used to calculate CLV for most recurring revenue businesses.
However, there are 3 major issues with this methodology:
This formula computes a single number expressing the expected customer lifetime value (or the average). It disregards any uncertainty in our estimates. For instance, in SaaS businesses, the revenue contributions by the customers can vary greatly, especially if you have different service plans (basic vs premium).
Arguably the most significant issue is using an aggregate retention rate among your customers. The essence of the proposed methodology is to account for the different retention rates for different customers. More to come in later.
2 inherent business dimensions should influence your CLV methodology.
Contractual vs Non-Contractual: In contractual businesses (e.g., Netflix, SaaS, Credit Cards), churn is explicitly observed. For instance, most SaaS customers are subscription-based and thus a customer will have to cancel in order to churn. Non-contractual businesses (e.g., online retail, grocery stores) donβt know if the customer's last purchase was truly their last or if theyβll eventually return to make another purchase.
Continuous vs Discrete: Transaction frequency is the second dimension. In discrete payment settings such as Netflix and fitness clubs, customers pay on a fixed cycle (i.e., monthly, yearly). In continuous payment settings such as Amazon, credit cards, payments are less predictable. For instance, although credit card companies know when youβve churn (contractual) they donβt know how frequently youβll generate transactions in a given month.
The issues outlined above all influence how we evaluate a customers lifetime. The remainder of this post will demonstrate a more robust method to evaluate your customer's retention rate specifically for Contractual β Discrete business.
Assume a cohorted customers table tracking year-over-year retention. Green values reflect current active customers.
Retention rates reflect the percent of customers that survive between subsequent periods. Churn rates are complementary to retention rates (i.e, 1 minus retention). Survival rates reflect the percent of customer that have survived since the beginning period. Survival at time t can be defined as:
Letβs compute the retention and churn rates for our oldest cohort, Cohort 0:
Annual Retention and Churn Rates for Cohort 0r1 = 84% (840 / 1000) --> c1 = 1 - .84 = 16%r2 = 73% (618 / 840) --> c2 = 1 - .73 = 27%r3 = 92% (570 / 618) --> c3 = 1 - .92 = 8%r4 = 91% (519 / 570) --> c4 = 1 - .91 = 9%Average Retention = 85%
The resulting survival rate for the same cohort:
Annual Survival Rates for Cohort 0S1 = r1 = 84%S2 = r1 * r2 = 84% * 73% = 61%S3 = r1 * r2 * r3 = 84% * 73% * 92% = 57%S4 = r1 * r2 * r3 * r4 = 84% * 73% * 92% * 91% = 52%
The challenge becomes forecasting the retention and survival rates, beyond our oldest cohort; we donβt know what percent of the 519 current customers from cohort 0 will be alive next year (year 5).
How we can take our 4yr data and forecast out to 5+ yrs?
One approach is to take the average retention rate across all years and forecast.
The chart above reflects our survival rates for each cohort. The average retention rate across these cohorts is ~84.4% which can be used to forecast survival rates for all times t using the survival formula.
Only ~20% of customers in a cohort will remain by the 9th year (.8449), as seen by the chart using an average retention. The next section proposes an alternative approach to forecasting retention.
The sGB model is great method to forecast retention for contractual businesses with discrete payment cycles. Although this post will not get into the mathematical details, it will help develop some fundamental intuition around the approach.
The formula above is the retention rate at time t for the sGB. Parameters Ξ±, Ξ² need to be estimated in a fashion that best fit our cohorted data. Letβs build some intuition around the formula:
Assume Ξ± = 2 and Ξ² = 10:r1 = (10+1-1) / (2+10+1-1) = 83.3%r2 = (10+2-1) / (2+10+2-1) = 84.6% ...r5 = (10+5-1) / (2+10+5-1) = 87.5%
Notice how retention not only is no longer constant but increasing over time. This subtly provides flexibility to more accurately model retention behavior and is a key enhancement in using a sGB model.
Because churn and retention are complementary, knowing one enables us to measure the other. The beta distribution is a flexible distribution that is used to model churn rates using the parameters, Ξ± and Ξ² mentioned earlier.
The chart below categorizes the types of survival curves based on sampled churn probabilities using the beta distribution. Each quadrant has a pair of charts β the left chart is the churn rates for a a given Ξ± and Ξ² and the right chart is its corresponding survival curve.
Below is the interpretation, demonstrating how different churn rates impact the survival rates.
The question that remains is βhow can I identify what the Ξ± and Ξ² parameters are for my business?β. The Maximum Likelihood Estimate (MLE) of the model parameters allow us to estimate the parameters that best fit our businesses observed cohorted data.
TL;DR Find values for Ξ± and Ξ² that maximize the output of the function above
There are many methods to optimize log-likelihood function above such as scipy, pymc3, or even excels solver add-ons. However, if you want to optimize probabilistically to account for uncertainties in the parameter estimates, pymc3 is a great choice. With pymc3, you can sample the posterior distribution to see the likely values to our parameters, as shown next.
We can sample the posterior distribution and visualize the uncertainty associated with our solved parameters:
We can see that the average Ξ± β 1.1 and average Ξ² β 5.3 placing our parameters in the top right quadrant on average. However, given are relatively small cohort sizes, there is uncertainty in our estimates, reflecting a strong possibility that Ξ± < 1 which would result our churn distribution falling into the bottom right quadrant.
Before measuring lifetime values, the next section will explain the value of growing retention rates.
Letβs take the two customers above as an example. Knowing only the number of times the customer as renewed their subscription with a business, which customer is more likely to renew once more (i.e., survive into the next period)? Customer B has demonstrated themself to be a loyal customer, one that clearly loves your product, hence the 9 renewals. You would anticipate that customer B is more likely to renew once more. We can measure this concept by measuring retention rates at t=2 and t=10 yrs using our estimated parameters.
Notice how retention improves at t=10 rewarding out intuition. There is a 92.7% change customer B renews into year 10 but an 84.5% chance customer A renews into year =3.
Using an average retention ignores growing loyalty in customers over time
We can also plot our churn probabilities using beta distribution from our posterior parameter samples.
Each line above reflects a churn distribution for a given Ξ± and Ξ² . The magenta-coloured lines reflect samples where both Ξ± and Ξ² were greater than 1 (generally higher churn rate on average). The black line reflects the churn rate distribution assuming our average parameters (Ξ± β 1.1 and Ξ² β 5.3). On the contrary, the green lines occur when Ξ± <1 but Ξ² >1.
Being able to compute retention rate at any time t means we compute our survival rate at any time t using our survival formula from earlier. The chart above reflects our forecasted survival curve using the sGB versus the constant retention rate.
Assuming constant retention rate underestimates our customers lifetimes, which in turn will underestimate CLV.
Not only can we now compute the expected lifetimes of future customers but also existing customers; customers that are currently active. The CLV of an existing customer can be expressed as their Residual Lifetime Value (RLV) or remaining lifetime value. Discounting their future value to present-value results in what's referred to as Discounted Expected Residual Lifetime (DERL).
The 2F1function refers to the hypergeometric function which can be imported in python from the scipy library:
from scipy.special import hyp2f1
Much like the increasing retention rates demonstrated earlier, the intuition behind the RLV is that an existing customer having renewed their subscription n times is likely to have a longer lifetime and thus a higher residual value assuming all else constant. Thus, we expect DERL to increase as the number of renewals increases.
Assuming the cash flow per customer to be $1,000 annually, the DERL after each renewal for the first 20 years is seen in the chart below:
The box-plots reflects the uncertainty in our estimate. For instance, for an active customer that has made 2 renewals, we estimate the DERL to be anywhere between $5000 to $5700 with a median of around $5300. Had we a solved for a single Ξ± and Ξ² we would have a single line. That said, notice the growing trend in residual value over time β in essence, we are quantifying customer loyalty. A newly acquired customer (number of renewals = 0) has a median DERL of around $4,500 verse an active customer thatβs made 19 renewals has a median DERL of around $8000 (78% higher).
Referring back to our cohort table, we can see our oldest cohort (Cohort 0) has made 4 renewals resulting in a median DERL of ~$5,900 per customer. Additionally, our newest cohort (Cohort 3) has only made 1 renewal with us and thus have as DERL of $4,900.
Because the DERL value shown above is per customer, the entire cohort Residual Values are obtained by multiplying the DERL by the current number of active customers for that cohort (green values). Summing across all cohorts reflects the total residual value of your existing customers.
Note that we are summing median values; in reality itβs advised to either sum the averages or continue to project the uncertainties to the end at which point you can compute any statistic you like (average, median, percentiles).
The total (median) remaining value for all our active customers is ~$14.2M
Furthermore, assume your business team forecasts a breakthrough year with an additional 1,000 new customers next year. New customers have made 0 renewals and thus have a DERL of ~$4500 per customer. As a result, we estimate those future customers will collectively have a lifetime value of $4.5M (1000 * $4500).
This post intended to demonstrate 3 considerations when evaluating CLV:
Account for uncertainty; if your customer dataset is only a handful of customers, you should less certain when modeling lifetime values.The sGB model is an excellent method to evaluate contractual β discrete businesses; modeling retention and lifetime more intuitivelyResidual Lifetime Values credits loyal customers (older) than new ones assuming all things equal.
Account for uncertainty; if your customer dataset is only a handful of customers, you should less certain when modeling lifetime values.
The sGB model is an excellent method to evaluate contractual β discrete businesses; modeling retention and lifetime more intuitively
Residual Lifetime Values credits loyal customers (older) than new ones assuming all things equal.
These considerations enable you to more accurately compute the total value of your current customers probabilistically and ultimately provide a much more robust and dynamic metric to:
evaluate A/B testing experiments
inform marketing acquisition efforts
raise the next series of funding for your startup!
[1] Whatβs Wrong With This CLV Formula?
[2] How to Project Customer Retention
[3] Probability Models for Customer-Base Analysis
|
[
{
"code": null,
"e": 315,
"s": 172,
"text": "Customer lifetime values (CLV) are a critical metric considered to be a companyβs north star metric and all in-compassing KPI, used to inform:"
},
{
"code": null,
"e": 384,
"s": 315,
"text": "marketing campaigns β how much should we spend to acquire customers?"
},
{
"code": null,
"e": 498,
"s": 384,
"text": "customer segmentation β who are our most valuable customers and what are their demographic and behavioral traits?"
},
{
"code": null,
"e": 566,
"s": 498,
"text": "overall health of the business β how is our CLV changing over time?"
},
{
"code": null,
"e": 656,
"s": 566,
"text": "total company value β how can we estimate the value of our existing and future customers?"
},
{
"code": null,
"e": 673,
"s": 656,
"text": "But what is CLV?"
},
{
"code": null,
"e": 738,
"s": 673,
"text": "The present value of all future cash flows of a current customer"
},
{
"code": null,
"e": 1004,
"s": 738,
"text": "At a high-level, in order to estimate your CLV youβll need to understand two simple customer attributes; a customers lifetime and the revenue they generate on a recurring basis. The more a customer pays and the longer they stay as a customer, the greater their CLV."
},
{
"code": null,
"e": 1167,
"s": 1004,
"text": "This post will focus on the more challenging component β measuring a customers lifetime, which requires you to understand your businesses current retention rates."
},
{
"code": null,
"e": 1264,
"s": 1167,
"text": "This post aims to provide an end-to-end robust methodology to estimate customer lifetime values."
},
{
"code": null,
"e": 1360,
"s": 1264,
"text": "The formula below is traditionally used to calculate CLV for most recurring revenue businesses."
},
{
"code": null,
"e": 1417,
"s": 1360,
"text": "However, there are 3 major issues with this methodology:"
},
{
"code": null,
"e": 1731,
"s": 1417,
"text": "This formula computes a single number expressing the expected customer lifetime value (or the average). It disregards any uncertainty in our estimates. For instance, in SaaS businesses, the revenue contributions by the customers can vary greatly, especially if you have different service plans (basic vs premium)."
},
{
"code": null,
"e": 1962,
"s": 1731,
"text": "Arguably the most significant issue is using an aggregate retention rate among your customers. The essence of the proposed methodology is to account for the different retention rates for different customers. More to come in later."
},
{
"code": null,
"e": 2032,
"s": 1962,
"text": "2 inherent business dimensions should influence your CLV methodology."
},
{
"code": null,
"e": 2460,
"s": 2032,
"text": "Contractual vs Non-Contractual: In contractual businesses (e.g., Netflix, SaaS, Credit Cards), churn is explicitly observed. For instance, most SaaS customers are subscription-based and thus a customer will have to cancel in order to churn. Non-contractual businesses (e.g., online retail, grocery stores) donβt know if the customer's last purchase was truly their last or if theyβll eventually return to make another purchase."
},
{
"code": null,
"e": 2903,
"s": 2460,
"text": "Continuous vs Discrete: Transaction frequency is the second dimension. In discrete payment settings such as Netflix and fitness clubs, customers pay on a fixed cycle (i.e., monthly, yearly). In continuous payment settings such as Amazon, credit cards, payments are less predictable. For instance, although credit card companies know when youβve churn (contractual) they donβt know how frequently youβll generate transactions in a given month."
},
{
"code": null,
"e": 3139,
"s": 2903,
"text": "The issues outlined above all influence how we evaluate a customers lifetime. The remainder of this post will demonstrate a more robust method to evaluate your customer's retention rate specifically for Contractual β Discrete business."
},
{
"code": null,
"e": 3255,
"s": 3139,
"text": "Assume a cohorted customers table tracking year-over-year retention. Green values reflect current active customers."
},
{
"code": null,
"e": 3552,
"s": 3255,
"text": "Retention rates reflect the percent of customers that survive between subsequent periods. Churn rates are complementary to retention rates (i.e, 1 minus retention). Survival rates reflect the percent of customer that have survived since the beginning period. Survival at time t can be defined as:"
},
{
"code": null,
"e": 3629,
"s": 3552,
"text": "Letβs compute the retention and churn rates for our oldest cohort, Cohort 0:"
},
{
"code": null,
"e": 3872,
"s": 3629,
"text": "Annual Retention and Churn Rates for Cohort 0r1 = 84% (840 / 1000) --> c1 = 1 - .84 = 16%r2 = 73% (618 / 840) --> c2 = 1 - .73 = 27%r3 = 92% (570 / 618) --> c3 = 1 - .92 = 8%r4 = 91% (519 / 570) --> c4 = 1 - .91 = 9%Average Retention = 85%"
},
{
"code": null,
"e": 3921,
"s": 3872,
"text": "The resulting survival rate for the same cohort:"
},
{
"code": null,
"e": 4092,
"s": 3921,
"text": "Annual Survival Rates for Cohort 0S1 = r1 = 84%S2 = r1 * r2 = 84% * 73% = 61%S3 = r1 * r2 * r3 = 84% * 73% * 92% = 57%S4 = r1 * r2 * r3 * r4 = 84% * 73% * 92% * 91% = 52%"
},
{
"code": null,
"e": 4290,
"s": 4092,
"text": "The challenge becomes forecasting the retention and survival rates, beyond our oldest cohort; we donβt know what percent of the 519 current customers from cohort 0 will be alive next year (year 5)."
},
{
"code": null,
"e": 4347,
"s": 4290,
"text": "How we can take our 4yr data and forecast out to 5+ yrs?"
},
{
"code": null,
"e": 4429,
"s": 4347,
"text": "One approach is to take the average retention rate across all years and forecast."
},
{
"code": null,
"e": 4637,
"s": 4429,
"text": "The chart above reflects our survival rates for each cohort. The average retention rate across these cohorts is ~84.4% which can be used to forecast survival rates for all times t using the survival formula."
},
{
"code": null,
"e": 4834,
"s": 4637,
"text": "Only ~20% of customers in a cohort will remain by the 9th year (.8449), as seen by the chart using an average retention. The next section proposes an alternative approach to forecasting retention."
},
{
"code": null,
"e": 5075,
"s": 4834,
"text": "The sGB model is great method to forecast retention for contractual businesses with discrete payment cycles. Although this post will not get into the mathematical details, it will help develop some fundamental intuition around the approach."
},
{
"code": null,
"e": 5268,
"s": 5075,
"text": "The formula above is the retention rate at time t for the sGB. Parameters Ξ±, Ξ² need to be estimated in a fashion that best fit our cohorted data. Letβs build some intuition around the formula:"
},
{
"code": null,
"e": 5414,
"s": 5268,
"text": "Assume Ξ± = 2 and Ξ² = 10:r1 = (10+1-1) / (2+10+1-1) = 83.3%r2 = (10+2-1) / (2+10+2-1) = 84.6% ...r5 = (10+5-1) / (2+10+5-1) = 87.5%"
},
{
"code": null,
"e": 5616,
"s": 5414,
"text": "Notice how retention not only is no longer constant but increasing over time. This subtly provides flexibility to more accurately model retention behavior and is a key enhancement in using a sGB model."
},
{
"code": null,
"e": 5840,
"s": 5616,
"text": "Because churn and retention are complementary, knowing one enables us to measure the other. The beta distribution is a flexible distribution that is used to model churn rates using the parameters, Ξ± and Ξ² mentioned earlier."
},
{
"code": null,
"e": 6113,
"s": 5840,
"text": "The chart below categorizes the types of survival curves based on sampled churn probabilities using the beta distribution. Each quadrant has a pair of charts β the left chart is the churn rates for a a given Ξ± and Ξ² and the right chart is its corresponding survival curve."
},
{
"code": null,
"e": 6209,
"s": 6113,
"text": "Below is the interpretation, demonstrating how different churn rates impact the survival rates."
},
{
"code": null,
"e": 6460,
"s": 6209,
"text": "The question that remains is βhow can I identify what the Ξ± and Ξ² parameters are for my business?β. The Maximum Likelihood Estimate (MLE) of the model parameters allow us to estimate the parameters that best fit our businesses observed cohorted data."
},
{
"code": null,
"e": 6537,
"s": 6460,
"text": "TL;DR Find values for Ξ± and Ξ² that maximize the output of the function above"
},
{
"code": null,
"e": 6901,
"s": 6537,
"text": "There are many methods to optimize log-likelihood function above such as scipy, pymc3, or even excels solver add-ons. However, if you want to optimize probabilistically to account for uncertainties in the parameter estimates, pymc3 is a great choice. With pymc3, you can sample the posterior distribution to see the likely values to our parameters, as shown next."
},
{
"code": null,
"e": 7011,
"s": 6901,
"text": "We can sample the posterior distribution and visualize the uncertainty associated with our solved parameters:"
},
{
"code": null,
"e": 7342,
"s": 7011,
"text": "We can see that the average Ξ± β 1.1 and average Ξ² β 5.3 placing our parameters in the top right quadrant on average. However, given are relatively small cohort sizes, there is uncertainty in our estimates, reflecting a strong possibility that Ξ± < 1 which would result our churn distribution falling into the bottom right quadrant."
},
{
"code": null,
"e": 7444,
"s": 7342,
"text": "Before measuring lifetime values, the next section will explain the value of growing retention rates."
},
{
"code": null,
"e": 7975,
"s": 7444,
"text": "Letβs take the two customers above as an example. Knowing only the number of times the customer as renewed their subscription with a business, which customer is more likely to renew once more (i.e., survive into the next period)? Customer B has demonstrated themself to be a loyal customer, one that clearly loves your product, hence the 9 renewals. You would anticipate that customer B is more likely to renew once more. We can measure this concept by measuring retention rates at t=2 and t=10 yrs using our estimated parameters."
},
{
"code": null,
"e": 8145,
"s": 7975,
"text": "Notice how retention improves at t=10 rewarding out intuition. There is a 92.7% change customer B renews into year 10 but an 84.5% chance customer A renews into year =3."
},
{
"code": null,
"e": 8219,
"s": 8145,
"text": "Using an average retention ignores growing loyalty in customers over time"
},
{
"code": null,
"e": 8322,
"s": 8219,
"text": "We can also plot our churn probabilities using beta distribution from our posterior parameter samples."
},
{
"code": null,
"e": 8680,
"s": 8322,
"text": "Each line above reflects a churn distribution for a given Ξ± and Ξ² . The magenta-coloured lines reflect samples where both Ξ± and Ξ² were greater than 1 (generally higher churn rate on average). The black line reflects the churn rate distribution assuming our average parameters (Ξ± β 1.1 and Ξ² β 5.3). On the contrary, the green lines occur when Ξ± <1 but Ξ² >1."
},
{
"code": null,
"e": 8926,
"s": 8680,
"text": "Being able to compute retention rate at any time t means we compute our survival rate at any time t using our survival formula from earlier. The chart above reflects our forecasted survival curve using the sGB versus the constant retention rate."
},
{
"code": null,
"e": 9037,
"s": 8926,
"text": "Assuming constant retention rate underestimates our customers lifetimes, which in turn will underestimate CLV."
},
{
"code": null,
"e": 9418,
"s": 9037,
"text": "Not only can we now compute the expected lifetimes of future customers but also existing customers; customers that are currently active. The CLV of an existing customer can be expressed as their Residual Lifetime Value (RLV) or remaining lifetime value. Discounting their future value to present-value results in what's referred to as Discounted Expected Residual Lifetime (DERL)."
},
{
"code": null,
"e": 9528,
"s": 9418,
"text": "The 2F1function refers to the hypergeometric function which can be imported in python from the scipy library:"
},
{
"code": null,
"e": 9561,
"s": 9528,
"text": "from scipy.special import hyp2f1"
},
{
"code": null,
"e": 9891,
"s": 9561,
"text": "Much like the increasing retention rates demonstrated earlier, the intuition behind the RLV is that an existing customer having renewed their subscription n times is likely to have a longer lifetime and thus a higher residual value assuming all else constant. Thus, we expect DERL to increase as the number of renewals increases."
},
{
"code": null,
"e": 10029,
"s": 9891,
"text": "Assuming the cash flow per customer to be $1,000 annually, the DERL after each renewal for the first 20 years is seen in the chart below:"
},
{
"code": null,
"e": 10602,
"s": 10029,
"text": "The box-plots reflects the uncertainty in our estimate. For instance, for an active customer that has made 2 renewals, we estimate the DERL to be anywhere between $5000 to $5700 with a median of around $5300. Had we a solved for a single Ξ± and Ξ² we would have a single line. That said, notice the growing trend in residual value over time β in essence, we are quantifying customer loyalty. A newly acquired customer (number of renewals = 0) has a median DERL of around $4,500 verse an active customer thatβs made 19 renewals has a median DERL of around $8000 (78% higher)."
},
{
"code": null,
"e": 10858,
"s": 10602,
"text": "Referring back to our cohort table, we can see our oldest cohort (Cohort 0) has made 4 renewals resulting in a median DERL of ~$5,900 per customer. Additionally, our newest cohort (Cohort 3) has only made 1 renewal with us and thus have as DERL of $4,900."
},
{
"code": null,
"e": 11144,
"s": 10858,
"text": "Because the DERL value shown above is per customer, the entire cohort Residual Values are obtained by multiplying the DERL by the current number of active customers for that cohort (green values). Summing across all cohorts reflects the total residual value of your existing customers."
},
{
"code": null,
"e": 11373,
"s": 11144,
"text": "Note that we are summing median values; in reality itβs advised to either sum the averages or continue to project the uncertainties to the end at which point you can compute any statistic you like (average, median, percentiles)."
},
{
"code": null,
"e": 11448,
"s": 11373,
"text": "The total (median) remaining value for all our active customers is ~$14.2M"
},
{
"code": null,
"e": 11760,
"s": 11448,
"text": "Furthermore, assume your business team forecasts a breakthrough year with an additional 1,000 new customers next year. New customers have made 0 renewals and thus have a DERL of ~$4500 per customer. As a result, we estimate those future customers will collectively have a lifetime value of $4.5M (1000 * $4500)."
},
{
"code": null,
"e": 11832,
"s": 11760,
"text": "This post intended to demonstrate 3 considerations when evaluating CLV:"
},
{
"code": null,
"e": 12198,
"s": 11832,
"text": "Account for uncertainty; if your customer dataset is only a handful of customers, you should less certain when modeling lifetime values.The sGB model is an excellent method to evaluate contractual β discrete businesses; modeling retention and lifetime more intuitivelyResidual Lifetime Values credits loyal customers (older) than new ones assuming all things equal."
},
{
"code": null,
"e": 12335,
"s": 12198,
"text": "Account for uncertainty; if your customer dataset is only a handful of customers, you should less certain when modeling lifetime values."
},
{
"code": null,
"e": 12468,
"s": 12335,
"text": "The sGB model is an excellent method to evaluate contractual β discrete businesses; modeling retention and lifetime more intuitively"
},
{
"code": null,
"e": 12566,
"s": 12468,
"text": "Residual Lifetime Values credits loyal customers (older) than new ones assuming all things equal."
},
{
"code": null,
"e": 12750,
"s": 12566,
"text": "These considerations enable you to more accurately compute the total value of your current customers probabilistically and ultimately provide a much more robust and dynamic metric to:"
},
{
"code": null,
"e": 12783,
"s": 12750,
"text": "evaluate A/B testing experiments"
},
{
"code": null,
"e": 12820,
"s": 12783,
"text": "inform marketing acquisition efforts"
},
{
"code": null,
"e": 12871,
"s": 12820,
"text": "raise the next series of funding for your startup!"
},
{
"code": null,
"e": 12911,
"s": 12871,
"text": "[1] Whatβs Wrong With This CLV Formula?"
},
{
"code": null,
"e": 12949,
"s": 12911,
"text": "[2] How to Project Customer Retention"
}
] |
How to Create a Spinner in JavaFX?
|
A spinner is a UI element that displays a number with an up and down arrow with it. You can increase or, decrease the value of the spinner using those arrows. You can create a spinner by instantiating the javafx.scene.control.Spinner class.
The following Example demonstrates the creation of a Spinner.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class SpinnerExample extends Application {
public void start(Stage stage) {
//Setting the label
Label label = new Label("Select Date:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//Creating a spinner
Spinner month = new Spinner(1, 12, 4);
//Setting the spinner editable
month.setEditable(true);
//Setting the size
month.setPrefSize(75, 25);
Label label1 = new Label("Month: ");
//Creating a spinner
Spinner day = new Spinner(1, 31, 4);
//Setting the spinner editable
day.setEditable(true);
//Setting the size
day.setPrefSize(75, 25);
Label label2 = new Label("Day: ");
//Creating a spinner
Spinner year = new Spinner(1947, 2999, 2009);
//Setting the spinner editable
year.setEditable(true);
//Setting the size
year.setPrefSize(75, 25);
Label label3 = new Label("Year: ");
HBox hbox = new HBox(5);
hbox.setPadding(new Insets(10, 10, 10, 25));
hbox.getChildren().addAll(label1, month, label2, day, label3, year);
//Creating a vbox to hold the pagination
VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 10, 10, 25));
vbox.getChildren().addAll(label, hbox);
//Setting the stage
Group root = new Group(vbox);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Spinner");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1303,
"s": 1062,
"text": "A spinner is a UI element that displays a number with an up and down arrow with it. You can increase or, decrease the value of the spinner using those arrows. You can create a spinner by instantiating the javafx.scene.control.Spinner class."
},
{
"code": null,
"e": 1365,
"s": 1303,
"text": "The following Example demonstrates the creation of a Spinner."
},
{
"code": null,
"e": 3416,
"s": 1365,
"text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.Spinner;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class SpinnerExample extends Application {\n public void start(Stage stage) {\n //Setting the label\n Label label = new Label(\"Select Date:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a spinner\n Spinner month = new Spinner(1, 12, 4);\n //Setting the spinner editable\n month.setEditable(true);\n //Setting the size\n month.setPrefSize(75, 25);\n Label label1 = new Label(\"Month: \");\n //Creating a spinner\n Spinner day = new Spinner(1, 31, 4);\n //Setting the spinner editable\n day.setEditable(true);\n //Setting the size\n day.setPrefSize(75, 25);\n Label label2 = new Label(\"Day: \");\n //Creating a spinner\n Spinner year = new Spinner(1947, 2999, 2009);\n //Setting the spinner editable\n year.setEditable(true);\n //Setting the size\n year.setPrefSize(75, 25);\n Label label3 = new Label(\"Year: \");\n HBox hbox = new HBox(5);\n hbox.setPadding(new Insets(10, 10, 10, 25));\n hbox.getChildren().addAll(label1, month, label2, day, label3, year);\n //Creating a vbox to hold the pagination\n VBox vbox = new VBox();\n vbox.setSpacing(5);\n vbox.setPadding(new Insets(10, 10, 10, 25));\n vbox.getChildren().addAll(label, hbox);\n //Setting the stage\n Group root = new Group(vbox);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Spinner\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Java program to implement insertion sort
|
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
1.If it is the first element, it is already sorted. return 1;
2.Pick next element
3.Compare with all elements in the sorted sub-list
4.Shift all the elements in the sorted sub-list that is greater than the value to be sorted
5.Insert the value
6.Repeat until the list is sorted
Live Demo
public class InsertionSort {
public static void main(String args[]){
int array[] = {10, 20, 25, 63, 96, 57};
int size = array.length;
for (int i=1 ;i< size; i++){
int val = array[i];
int pos = i;
while(array[pos-1]>val && pos>0){
array[pos] = array[pos-1];
pos = pos-1;
}
array[pos] = val;
}
for (int i=0 ;i< size; i++){
System.out.print(" "+array[i]);
}
}
}
10 20 25 57 63 96
|
[
{
"code": null,
"e": 1404,
"s": 1062,
"text": "This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list has to find its appropriate place and then it has to be inserted there. Hence the name, insertion sort."
},
{
"code": null,
"e": 1527,
"s": 1404,
"text": "The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array)."
},
{
"code": null,
"e": 1805,
"s": 1527,
"text": "1.If it is the first element, it is already sorted. return 1;\n2.Pick next element\n3.Compare with all elements in the sorted sub-list\n4.Shift all the elements in the sorted sub-list that is greater than the value to be sorted\n5.Insert the value\n6.Repeat until the list is sorted"
},
{
"code": null,
"e": 1815,
"s": 1805,
"text": "Live Demo"
},
{
"code": null,
"e": 2305,
"s": 1815,
"text": "public class InsertionSort {\n public static void main(String args[]){\n int array[] = {10, 20, 25, 63, 96, 57};\n int size = array.length;\n\n for (int i=1 ;i< size; i++){\n int val = array[i];\n int pos = i;\n\n while(array[pos-1]>val && pos>0){\n array[pos] = array[pos-1];\n pos = pos-1;\n }\n array[pos] = val;\n }\n\n for (int i=0 ;i< size; i++){\n System.out.print(\" \"+array[i]);\n }\n }\n}"
},
{
"code": null,
"e": 2323,
"s": 2305,
"text": "10 20 25 57 63 96"
}
] |
Identifying trolls and bots on Reddit with machine learning (Part 2) | by Jason Skowronski | Towards Data Science
|
Trolls and bots are widespread across social media, and they influence us in ways we are not always aware of. Trolls can be relatively harmless, just trying to entertain themselves at othersβ expense, but they can also be political actors sowing mistrust or discord. While some bots offer helpful information, others can be used to manipulate vote counts and promote content that supports their agenda. Weβll show you how machine learning can help protect our communities from abuse.
In the first part of this series, we covered the problem of trolls and bots on the popular site Reddit. We described how we built a dashboard to moderate suspected trolls and bots. In this part, weβll show you how we used machine learning to detect bots and trolls in political discussions and then mark suspicious comments on our moderator dashboard.
Troll and bot detection is a relatively new field. Historically, companies have employed human moderators to detect and remove content thatβs inconsistent their terms of service. However, this manual process is expensive, plus it can be emotionally tiring for humans to review the worst content. We will quickly hit the limits of human moderator efficaciousness as new technologies like OpenAI GPT-2 natural language generation are unleashed. As bots improve, it is important to employ counter technologies to protect the integrity of online communities.
Thereβve been several studies done on the topic of bot detection. For example, one researcher found competing pro-Trump and anti-Trump bots on Twitter. Researchers at Indiana University have provided a tool to check Twitter users called botornot.
Thereβs also been interesting research on online trolls. Research from Stanford has shown that just 1% of accounts create 74% of conflict. Researchers at Georgia Tech used a natural language processing model to identify users who violate norms with behavior like making personal attacks, misogynistic slurs, or even mansplaining.
Our goal is to create a machine learning model to screen comments on the politics subreddit for moderators to review. It doesnβt need to have perfect accuracy since the comments will be reviewed by a human moderator. Instead, our measure of success is how much more efficient we can make human moderators. Rather than needing to review every comment, they will be able to review a prescreened subset. We are not trying to replace the existing moderation system that Reddit provides, which allows moderators to review comments that have been reported by users. Instead, this is an additional source of information that can complement the existing system.
As described in our part one article, we have created a dashboard allowing moderators to review the comments. The machine learning model will score each comment as being a normal user, a bot, or a troll.
Try it out for yourself at reddit-dashboard.herokuapp.com.
To set your expectations, our system is designed as a proof of concept. Itβs not meant to be a production system and is not 100% accurate. Weβll use it to illustrate the steps involved in building a system, with the hopes that platform providers will be able to offer official tools like these in the future.
Our initial training dataset was collected from a list of known bots and trolls. Weβll use two lists of these 393 known bots plus 167 more from the botwatch subreddit. Weβll also use a list of 944 troll accounts from Redditβs 2017 Transparency Report that were suspected of working for the Russian Internet Research Agency.
We are using an event-driven architecture that consists of a process that downloads data from Reddit and pushes it in a Kafka queue. We then have a Kafka consumer that writes the data into a Redshift data warehouse in batches. We wrote a Kafka producer application to download the comments from the list of bots and trolls. As a result, our data warehouse contains not only the data from the known bots and trolls, but also real-time comments from the politics subreddit.
While Reddit comments arenβt exactly private, you may have data that is private. For example, you may have data thatβs regulated by HIPAA or PCI, or is sensitive to your business or customers. We followed a Heroku reference architecture that was designed to protect private data. It provides a Terraform script to automatically configure a Redshift data warehouse and connect it to a Heroku Private Space. As a result, only apps running in the Private Space can access the data.
We can either train our model on a dyno directly or run a one-off dyno to download the data to CSV and train the model locally. Weβll choose the latter for simplicity, but youβd want to keep sensitive data in the Private Space.
heroku run bash -a kafka-stream-viz-jorgeexport PGPASSWORD=<password>echo βselect * from reddit_commentsβ | psql -h tf-jorge-tf-redshift-cluster.coguuscncu3p.us-east-1.redshift.amazonaws.com -U jorge -d redshift_jorge -p 5439 -A -o reddit.csvgzip reddit.csvcurl -F βfile=@reddit.csv.gzβ https://file.io
If you prefer to use our training data to try it out yourself, you can download our CSV.
Now we have comments from both sets of users and count a total of 93,668. The ratios between the classes are fixed at 5% trolls, 10% bots, and 85% normal. This is useful for training but likely underestimates the true percentage of normal users.
Next, we need to select features to build our model. Reddit provides dozens of JSON fields for each user and comment. Some donβt have meaningful values. For example, banned_by was null in every case, probably because we lack moderator permissions. We picked the fields below because we thought theyβd be valuable as predictors or to understand how well our model performs. We added the column recent_comments with an array of the last 20 comments made by that user.
no_followlink_idgildedauthorauthor_verifiedauthor_comment_karmaauthor_link_karmanum_commentscreated_utcscoreover_18bodyis_submittercontroversialityupsis_botis_trollrecent_comments
Some fields like βscoreβ are useful for historical comments, but not for a real-time dashboard because users wonβt have had time to vote on that comment yet.
We added additional calculated fields that we thought would correlate well with bots and trolls. For example, we suspected that a userβs recent comment history would provide valuable insight into whether they are a bot or troll. For example, if a user repeatedly posts controversial comments with a negative sentiment, perhaps they are a troll. Likewise, if a user repeatedly posts comments with the same text, perhaps they are a bot. We used the TextBlob package to calculate numerical values for each of these. Weβll see whether these features are useful in practice soon.
recent_num_commentsrecent_num_last_30_daysrecent_avg_no_followrecent_avg_gildedrecent_avg_responsesrecent_percent_neg_scorerecent_avg_scorerecent_min_scorerecent_avg_controversialityrecent_avg_upsrecent_avg_diff_ratiorecent_max_diff_ratiorecent_avg_sentiment_polarityrecent_min_sentiment_polarity
For more information on what these fields are and how they are calculated, see the code in our Jupyter Notebooks in https://github.com/devspotlight/botidentification.
Our next step is to create a new machine learning model based on this list. Weβll use Pythonβs excellent scikit learn framework to build our model. Weβll store our training data into two data frames: one for the set of features to train in and the second with the desired class labels. Weβll then split our dataset into 70% training data and 30% test data.
X_train, X_test, y_train, y_test = train_test_split( input_x, input_y, test_size=0.3, random_state=16)
Next, weβll create a decision tree classifier to predict whether each comment is a bot, a troll, or a normal user. Weβll use a decision tree because the created rule is very easy to understand. The accuracy would probably be improved using a more robust algorithm like a random forest, but weβll stick to a decision tree for the purposes of keeping our example simple.
clf = DecisionTreeClassifier(max_depth=3, class_weight={βnormalβ:1, βbotβ:2.5, βtrollβ:5}, min_samples_leaf=100)
Youβll notice a few parameters in the above code sample. We are setting the maximum depth of the tree to 3 not only to avoid overfitting, but also so that itβs easier to visualize the resulting tree. We are also setting the class weights so that bots and trolls are less likely to be missed, even at the expense of falsely labeling a normal user. Lastly, we are requiring that the leaf nodes have at least 100 samples to keep our tree simpler.
Now weβll test the model against the 30% of data we held out as a test set. This will tell us how well our model performs at guessing whether each comment is from a bot, troll, or normal user.
matrix = pd.crosstab(y_true, y_pred, rownames=[βTrueβ], colnames=[βPredictedβ], margins=True)
This will create a confusion matrix showing, for each true target label, how many of the comments were predicted correctly or incorrectly. For example, we can see below that out of 1,956 total troll comments, we correctly predicted 1,451 of them.
Predicted bot normal troll AllTrue bot 3677 585 33 4295normal 197 20593 993 21783troll 5 500 1451 1956All 3879 21678 2477 28034
In other words, the recall for trolls is 74%. The precision is lower; of all comments predicted as being a troll, only 58% really are.
Recall : [0.85611176 0.94537024 0.74182004]Precision: [0.94792472 0.94994926 0.58578926]Accuracy: 0.917493044160662
We can calculate the overall accuracy at 91.7%. The model performed the best for normal users, with about 95% precision and recall. It performed fairly well for bots, but had a harder time distinguishing trolls from normal users. Overall, the results look fairly strong even with a fairly simple model.
Now that we have this great machine learning model that can predict bots and trolls, how does it work and what can we learn from it? A great start is to look at which features were most important.
feature_imp = pd.Series( clf.feature_importances_, index=my_data.columns.drop(βtargetβ)).sort_values(ascending=False)recent_avg_diff_ratio 0.465169author_comment_karma 0.329354author_link_karma 0.099974recent_avg_responses 0.098622author_verified 0.006882recent_min_sentiment_polarity 0.000000recent_avg_no_follow 0.000000over_18 0.000000is_submitter 0.000000recent_num_comments 0.000000recent_num_last_30_days 0.000000recent_avg_gilded 0.000000recent_avg_sentiment_polarity 0.000000recent_percent_neg_score 0.000000recent_avg_score 0.000000recent_min_score 0.000000recent_avg_controversiality 0.000000recent_avg_ups 0.000000recent_max_diff_ratio 0.000000no_follow 0.000000
Interesting! The most important feature was the average difference ratio in the text of the recent comments. This means if the text of the last 20 comments is very similar, itβs probably a bot. The next most important features were the comment karma, link karma, the number of responses to recent comments, and whether the account is verified.
Why are the rest zero? We limited the depth of our binary tree to 3 levels, so we are intentionally not including all the features. Of note is that we didnβt consider the scores or sentiment of previous comments to classify the trolls. Either these trolls were fairly polite and earned a decent number of votes, or the other features had better discriminatory power.
Letβs take a look at the actual decision tree to get more information.
export_graphviz(estimator, out_file=βtree.dotβ, feature_names = data.drop([βtargetβ], axis=1).columns.values, class_names = np.array([βnormalβ,βbotβ,βtrollβ]), rounded = False, proportion = False, precision = 5, filled = True)
Now we can get an idea of how this model works! You might need to zoom in to see the details.
Letβs start at the top of the tree. When the recent comments are fairly similar to each other (the average difference ratio is high), then itβs more likely to be a bot. When they have dissimilar comments, low comment karma, and high link karma, they are more likely to be a troll. This could make sense if the trolls use posts of kittens to pump up their link karma, and then make nasty comments in the forums that either get ignored or downvoted.
To make our machine learning model available to the world, we need to make it available to our moderator dashboard. We can do that by hosting an API for the dashboard to call.
To serve our API, we used Flask, which is a lightweight web framework for Python. When we load our machine learning model, the server starts. When it receives a POST request containing a JSON object with the comment data, it responds back with the prediction.
Example for a bot user:
{ βbanned_byβ:null, βno_followβ:true, βlink_idβ:βt3_aqtwe1", βgildedβ:false, βauthorβ:βAutoModeratorβ, βauthor_verifiedβ:false, βauthor_comment_karmaβ:445850.0, βauthor_link_karmaβ:1778.0, βnum_commentsβ:1.0, βcreated_utcβ:1550213389.0, βscoreβ:1.0, βover_18β:false, βbodyβ:βHey, thanks for posting at \\/r\\/SwitchHaxing! Unfortunately your comment has been removed due to rule 6; please post questions in the stickied Q&A thread.If you believe this is an error, please contact us via modmail and well sort it out.*I am a botβ, βdownsβ:0.0, βis_submitterβ:false, βnum_reportsβ:null, βcontroversialityβ:0.0, βquarantineβ:βfalseβ, βupsβ:1.0, βis_botβ:true, βis_trollβ:false, βrecent_commentsβ:β[...array of 20 recent comments...]β}
The response returned is:
{ βpredictionβ: βIs a bot userβ}
We deployed our API on Heroku because it makes it very easy to run. We just create a Procfile with a single line telling Heroku which file to use for the web server.
web: python app.py ${port}
We can then git push our code to heroku:
git push heroku master
Heroku takes care of the hassle of downloading requirements, building the API, setting up a web server, routing, etc. We can now access our API at this URL and use Postman to send a test request:
https://botidentification.herokuapp.com/
Thanks to the great moderator dashboard we wrote in the first part of this series, we can now see the performance of our model operating on real comments. If you havenβt already, check it out here: reddit-dashboard.herokuapp.com.
Itβs streaming real live comments from the r/politics subreddit. You can see each comment and whether the model scored it as a bot, troll or normal user.
You may see some comments labeled as bots or trolls, but itβs not obvious why after inspecting their comment history. Keep in mind that we used a simple model in order to keep our tutorial easier to follow. The precision for labeling trolls is only 58%. Thatβs why we designed it as a filter for human moderators to review.
If youβre interested in playing with this model yourself, check out the code on GitHub at https://github.com/devspotlight/botidentification. You can try improving the accuracy of the model by using a more sophisticated algorithm such as a random forest. Spoiler alert: itβs possible to get 95%+ accuracy on the test data with more sophisticated models, but weβll leave it as an exercise for you.
|
[
{
"code": null,
"e": 656,
"s": 172,
"text": "Trolls and bots are widespread across social media, and they influence us in ways we are not always aware of. Trolls can be relatively harmless, just trying to entertain themselves at othersβ expense, but they can also be political actors sowing mistrust or discord. While some bots offer helpful information, others can be used to manipulate vote counts and promote content that supports their agenda. Weβll show you how machine learning can help protect our communities from abuse."
},
{
"code": null,
"e": 1008,
"s": 656,
"text": "In the first part of this series, we covered the problem of trolls and bots on the popular site Reddit. We described how we built a dashboard to moderate suspected trolls and bots. In this part, weβll show you how we used machine learning to detect bots and trolls in political discussions and then mark suspicious comments on our moderator dashboard."
},
{
"code": null,
"e": 1563,
"s": 1008,
"text": "Troll and bot detection is a relatively new field. Historically, companies have employed human moderators to detect and remove content thatβs inconsistent their terms of service. However, this manual process is expensive, plus it can be emotionally tiring for humans to review the worst content. We will quickly hit the limits of human moderator efficaciousness as new technologies like OpenAI GPT-2 natural language generation are unleashed. As bots improve, it is important to employ counter technologies to protect the integrity of online communities."
},
{
"code": null,
"e": 1810,
"s": 1563,
"text": "Thereβve been several studies done on the topic of bot detection. For example, one researcher found competing pro-Trump and anti-Trump bots on Twitter. Researchers at Indiana University have provided a tool to check Twitter users called botornot."
},
{
"code": null,
"e": 2140,
"s": 1810,
"text": "Thereβs also been interesting research on online trolls. Research from Stanford has shown that just 1% of accounts create 74% of conflict. Researchers at Georgia Tech used a natural language processing model to identify users who violate norms with behavior like making personal attacks, misogynistic slurs, or even mansplaining."
},
{
"code": null,
"e": 2794,
"s": 2140,
"text": "Our goal is to create a machine learning model to screen comments on the politics subreddit for moderators to review. It doesnβt need to have perfect accuracy since the comments will be reviewed by a human moderator. Instead, our measure of success is how much more efficient we can make human moderators. Rather than needing to review every comment, they will be able to review a prescreened subset. We are not trying to replace the existing moderation system that Reddit provides, which allows moderators to review comments that have been reported by users. Instead, this is an additional source of information that can complement the existing system."
},
{
"code": null,
"e": 2998,
"s": 2794,
"text": "As described in our part one article, we have created a dashboard allowing moderators to review the comments. The machine learning model will score each comment as being a normal user, a bot, or a troll."
},
{
"code": null,
"e": 3057,
"s": 2998,
"text": "Try it out for yourself at reddit-dashboard.herokuapp.com."
},
{
"code": null,
"e": 3366,
"s": 3057,
"text": "To set your expectations, our system is designed as a proof of concept. Itβs not meant to be a production system and is not 100% accurate. Weβll use it to illustrate the steps involved in building a system, with the hopes that platform providers will be able to offer official tools like these in the future."
},
{
"code": null,
"e": 3690,
"s": 3366,
"text": "Our initial training dataset was collected from a list of known bots and trolls. Weβll use two lists of these 393 known bots plus 167 more from the botwatch subreddit. Weβll also use a list of 944 troll accounts from Redditβs 2017 Transparency Report that were suspected of working for the Russian Internet Research Agency."
},
{
"code": null,
"e": 4162,
"s": 3690,
"text": "We are using an event-driven architecture that consists of a process that downloads data from Reddit and pushes it in a Kafka queue. We then have a Kafka consumer that writes the data into a Redshift data warehouse in batches. We wrote a Kafka producer application to download the comments from the list of bots and trolls. As a result, our data warehouse contains not only the data from the known bots and trolls, but also real-time comments from the politics subreddit."
},
{
"code": null,
"e": 4641,
"s": 4162,
"text": "While Reddit comments arenβt exactly private, you may have data that is private. For example, you may have data thatβs regulated by HIPAA or PCI, or is sensitive to your business or customers. We followed a Heroku reference architecture that was designed to protect private data. It provides a Terraform script to automatically configure a Redshift data warehouse and connect it to a Heroku Private Space. As a result, only apps running in the Private Space can access the data."
},
{
"code": null,
"e": 4869,
"s": 4641,
"text": "We can either train our model on a dyno directly or run a one-off dyno to download the data to CSV and train the model locally. Weβll choose the latter for simplicity, but youβd want to keep sensitive data in the Private Space."
},
{
"code": null,
"e": 5172,
"s": 4869,
"text": "heroku run bash -a kafka-stream-viz-jorgeexport PGPASSWORD=<password>echo βselect * from reddit_commentsβ | psql -h tf-jorge-tf-redshift-cluster.coguuscncu3p.us-east-1.redshift.amazonaws.com -U jorge -d redshift_jorge -p 5439 -A -o reddit.csvgzip reddit.csvcurl -F βfile=@reddit.csv.gzβ https://file.io"
},
{
"code": null,
"e": 5261,
"s": 5172,
"text": "If you prefer to use our training data to try it out yourself, you can download our CSV."
},
{
"code": null,
"e": 5507,
"s": 5261,
"text": "Now we have comments from both sets of users and count a total of 93,668. The ratios between the classes are fixed at 5% trolls, 10% bots, and 85% normal. This is useful for training but likely underestimates the true percentage of normal users."
},
{
"code": null,
"e": 5973,
"s": 5507,
"text": "Next, we need to select features to build our model. Reddit provides dozens of JSON fields for each user and comment. Some donβt have meaningful values. For example, banned_by was null in every case, probably because we lack moderator permissions. We picked the fields below because we thought theyβd be valuable as predictors or to understand how well our model performs. We added the column recent_comments with an array of the last 20 comments made by that user."
},
{
"code": null,
"e": 6153,
"s": 5973,
"text": "no_followlink_idgildedauthorauthor_verifiedauthor_comment_karmaauthor_link_karmanum_commentscreated_utcscoreover_18bodyis_submittercontroversialityupsis_botis_trollrecent_comments"
},
{
"code": null,
"e": 6311,
"s": 6153,
"text": "Some fields like βscoreβ are useful for historical comments, but not for a real-time dashboard because users wonβt have had time to vote on that comment yet."
},
{
"code": null,
"e": 6886,
"s": 6311,
"text": "We added additional calculated fields that we thought would correlate well with bots and trolls. For example, we suspected that a userβs recent comment history would provide valuable insight into whether they are a bot or troll. For example, if a user repeatedly posts controversial comments with a negative sentiment, perhaps they are a troll. Likewise, if a user repeatedly posts comments with the same text, perhaps they are a bot. We used the TextBlob package to calculate numerical values for each of these. Weβll see whether these features are useful in practice soon."
},
{
"code": null,
"e": 7183,
"s": 6886,
"text": "recent_num_commentsrecent_num_last_30_daysrecent_avg_no_followrecent_avg_gildedrecent_avg_responsesrecent_percent_neg_scorerecent_avg_scorerecent_min_scorerecent_avg_controversialityrecent_avg_upsrecent_avg_diff_ratiorecent_max_diff_ratiorecent_avg_sentiment_polarityrecent_min_sentiment_polarity"
},
{
"code": null,
"e": 7350,
"s": 7183,
"text": "For more information on what these fields are and how they are calculated, see the code in our Jupyter Notebooks in https://github.com/devspotlight/botidentification."
},
{
"code": null,
"e": 7707,
"s": 7350,
"text": "Our next step is to create a new machine learning model based on this list. Weβll use Pythonβs excellent scikit learn framework to build our model. Weβll store our training data into two data frames: one for the set of features to train in and the second with the desired class labels. Weβll then split our dataset into 70% training data and 30% test data."
},
{
"code": null,
"e": 7810,
"s": 7707,
"text": "X_train, X_test, y_train, y_test = train_test_split( input_x, input_y, test_size=0.3, random_state=16)"
},
{
"code": null,
"e": 8179,
"s": 7810,
"text": "Next, weβll create a decision tree classifier to predict whether each comment is a bot, a troll, or a normal user. Weβll use a decision tree because the created rule is very easy to understand. The accuracy would probably be improved using a more robust algorithm like a random forest, but weβll stick to a decision tree for the purposes of keeping our example simple."
},
{
"code": null,
"e": 8294,
"s": 8179,
"text": "clf = DecisionTreeClassifier(max_depth=3, class_weight={βnormalβ:1, βbotβ:2.5, βtrollβ:5}, min_samples_leaf=100)"
},
{
"code": null,
"e": 8738,
"s": 8294,
"text": "Youβll notice a few parameters in the above code sample. We are setting the maximum depth of the tree to 3 not only to avoid overfitting, but also so that itβs easier to visualize the resulting tree. We are also setting the class weights so that bots and trolls are less likely to be missed, even at the expense of falsely labeling a normal user. Lastly, we are requiring that the leaf nodes have at least 100 samples to keep our tree simpler."
},
{
"code": null,
"e": 8931,
"s": 8738,
"text": "Now weβll test the model against the 30% of data we held out as a test set. This will tell us how well our model performs at guessing whether each comment is from a bot, troll, or normal user."
},
{
"code": null,
"e": 9025,
"s": 8931,
"text": "matrix = pd.crosstab(y_true, y_pred, rownames=[βTrueβ], colnames=[βPredictedβ], margins=True)"
},
{
"code": null,
"e": 9272,
"s": 9025,
"text": "This will create a confusion matrix showing, for each true target label, how many of the comments were predicted correctly or incorrectly. For example, we can see below that out of 1,956 total troll comments, we correctly predicted 1,451 of them."
},
{
"code": null,
"e": 9564,
"s": 9272,
"text": "Predicted bot normal troll AllTrue bot 3677 585 33 4295normal 197 20593 993 21783troll 5 500 1451 1956All 3879 21678 2477 28034"
},
{
"code": null,
"e": 9699,
"s": 9564,
"text": "In other words, the recall for trolls is 74%. The precision is lower; of all comments predicted as being a troll, only 58% really are."
},
{
"code": null,
"e": 9815,
"s": 9699,
"text": "Recall : [0.85611176 0.94537024 0.74182004]Precision: [0.94792472 0.94994926 0.58578926]Accuracy: 0.917493044160662"
},
{
"code": null,
"e": 10118,
"s": 9815,
"text": "We can calculate the overall accuracy at 91.7%. The model performed the best for normal users, with about 95% precision and recall. It performed fairly well for bots, but had a harder time distinguishing trolls from normal users. Overall, the results look fairly strong even with a fairly simple model."
},
{
"code": null,
"e": 10315,
"s": 10118,
"text": "Now that we have this great machine learning model that can predict bots and trolls, how does it work and what can we learn from it? A great start is to look at which features were most important."
},
{
"code": null,
"e": 10989,
"s": 10315,
"text": "feature_imp = pd.Series( clf.feature_importances_, index=my_data.columns.drop(βtargetβ)).sort_values(ascending=False)recent_avg_diff_ratio 0.465169author_comment_karma 0.329354author_link_karma 0.099974recent_avg_responses 0.098622author_verified 0.006882recent_min_sentiment_polarity 0.000000recent_avg_no_follow 0.000000over_18 0.000000is_submitter 0.000000recent_num_comments 0.000000recent_num_last_30_days 0.000000recent_avg_gilded 0.000000recent_avg_sentiment_polarity 0.000000recent_percent_neg_score 0.000000recent_avg_score 0.000000recent_min_score 0.000000recent_avg_controversiality 0.000000recent_avg_ups 0.000000recent_max_diff_ratio 0.000000no_follow 0.000000"
},
{
"code": null,
"e": 11333,
"s": 10989,
"text": "Interesting! The most important feature was the average difference ratio in the text of the recent comments. This means if the text of the last 20 comments is very similar, itβs probably a bot. The next most important features were the comment karma, link karma, the number of responses to recent comments, and whether the account is verified."
},
{
"code": null,
"e": 11700,
"s": 11333,
"text": "Why are the rest zero? We limited the depth of our binary tree to 3 levels, so we are intentionally not including all the features. Of note is that we didnβt consider the scores or sentiment of previous comments to classify the trolls. Either these trolls were fairly polite and earned a decent number of votes, or the other features had better discriminatory power."
},
{
"code": null,
"e": 11771,
"s": 11700,
"text": "Letβs take a look at the actual decision tree to get more information."
},
{
"code": null,
"e": 11999,
"s": 11771,
"text": "export_graphviz(estimator, out_file=βtree.dotβ, feature_names = data.drop([βtargetβ], axis=1).columns.values, class_names = np.array([βnormalβ,βbotβ,βtrollβ]), rounded = False, proportion = False, precision = 5, filled = True)"
},
{
"code": null,
"e": 12093,
"s": 11999,
"text": "Now we can get an idea of how this model works! You might need to zoom in to see the details."
},
{
"code": null,
"e": 12541,
"s": 12093,
"text": "Letβs start at the top of the tree. When the recent comments are fairly similar to each other (the average difference ratio is high), then itβs more likely to be a bot. When they have dissimilar comments, low comment karma, and high link karma, they are more likely to be a troll. This could make sense if the trolls use posts of kittens to pump up their link karma, and then make nasty comments in the forums that either get ignored or downvoted."
},
{
"code": null,
"e": 12717,
"s": 12541,
"text": "To make our machine learning model available to the world, we need to make it available to our moderator dashboard. We can do that by hosting an API for the dashboard to call."
},
{
"code": null,
"e": 12977,
"s": 12717,
"text": "To serve our API, we used Flask, which is a lightweight web framework for Python. When we load our machine learning model, the server starts. When it receives a POST request containing a JSON object with the comment data, it responds back with the prediction."
},
{
"code": null,
"e": 13001,
"s": 12977,
"text": "Example for a bot user:"
},
{
"code": null,
"e": 13736,
"s": 13001,
"text": "{ βbanned_byβ:null, βno_followβ:true, βlink_idβ:βt3_aqtwe1\", βgildedβ:false, βauthorβ:βAutoModeratorβ, βauthor_verifiedβ:false, βauthor_comment_karmaβ:445850.0, βauthor_link_karmaβ:1778.0, βnum_commentsβ:1.0, βcreated_utcβ:1550213389.0, βscoreβ:1.0, βover_18β:false, βbodyβ:βHey, thanks for posting at \\\\/r\\\\/SwitchHaxing! Unfortunately your comment has been removed due to rule 6; please post questions in the stickied Q&A thread.If you believe this is an error, please contact us via modmail and well sort it out.*I am a botβ, βdownsβ:0.0, βis_submitterβ:false, βnum_reportsβ:null, βcontroversialityβ:0.0, βquarantineβ:βfalseβ, βupsβ:1.0, βis_botβ:true, βis_trollβ:false, βrecent_commentsβ:β[...array of 20 recent comments...]β}"
},
{
"code": null,
"e": 13762,
"s": 13736,
"text": "The response returned is:"
},
{
"code": null,
"e": 13795,
"s": 13762,
"text": "{ βpredictionβ: βIs a bot userβ}"
},
{
"code": null,
"e": 13961,
"s": 13795,
"text": "We deployed our API on Heroku because it makes it very easy to run. We just create a Procfile with a single line telling Heroku which file to use for the web server."
},
{
"code": null,
"e": 13988,
"s": 13961,
"text": "web: python app.py ${port}"
},
{
"code": null,
"e": 14029,
"s": 13988,
"text": "We can then git push our code to heroku:"
},
{
"code": null,
"e": 14052,
"s": 14029,
"text": "git push heroku master"
},
{
"code": null,
"e": 14248,
"s": 14052,
"text": "Heroku takes care of the hassle of downloading requirements, building the API, setting up a web server, routing, etc. We can now access our API at this URL and use Postman to send a test request:"
},
{
"code": null,
"e": 14289,
"s": 14248,
"text": "https://botidentification.herokuapp.com/"
},
{
"code": null,
"e": 14519,
"s": 14289,
"text": "Thanks to the great moderator dashboard we wrote in the first part of this series, we can now see the performance of our model operating on real comments. If you havenβt already, check it out here: reddit-dashboard.herokuapp.com."
},
{
"code": null,
"e": 14673,
"s": 14519,
"text": "Itβs streaming real live comments from the r/politics subreddit. You can see each comment and whether the model scored it as a bot, troll or normal user."
},
{
"code": null,
"e": 14997,
"s": 14673,
"text": "You may see some comments labeled as bots or trolls, but itβs not obvious why after inspecting their comment history. Keep in mind that we used a simple model in order to keep our tutorial easier to follow. The precision for labeling trolls is only 58%. Thatβs why we designed it as a filter for human moderators to review."
}
] |
Divide two integers without using multiplication, division and mod operator | Set2 - GeeksforGeeks
|
19 Apr, 2021
Given two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator.Examples:
Input: a = 10, b = 3
Output: 3
Input: a = 43, b = -8
Output: -5
This problem has been already discussed here. In this post, a different approach is discussed.Approach :
Let a/b = c.Take log on both sideslog(a) β log(b) = log(c)Now Log of RHS can be written as exp in LHSFinal formula is : exp(log(a) β log(b)) = c
Let a/b = c.
Take log on both sides
log(a) β log(b) = log(c)
Now Log of RHS can be written as exp in LHS
Final formula is : exp(log(a) β log(b)) = c
C++
Java
Python3
C#
PHP
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Returns the quotient of dividend/divisor.void Divide(int a, int b){ long long dividend = (long long)a; long long divisor = (long long)b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive long long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of dividend and divisor dividend = abs(dividend); divisor = abs(divisor); // Zero division Exception. if (divisor == 0) { cout << "Cannot Divide by 0" << endl; return; } if (dividend == 0) { cout << a << " / " << b << " is equal to : " << 0 << endl; return; } if (divisor == 1) { cout << a << " / " << b << " is equal to : " << sign * dividend << endl; return; } // Using Formula derived above. cout << a << " / " << b << " is equal to : " << sign * exp(log(dividend) - log(divisor)) << endl;} // Drivers codeint main(){ int a = 10, b = 5; Divide(a, b); a = 49, b = -7; Divide(a, b); return 0;}
// Java program for// above approachimport java.io.*; class GFG{static void Divide(int a, int b){ long dividend = (long)a; long divisor = (long)b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.abs(dividend); divisor = Math.abs(divisor); // Zero division Exception. if (divisor == 0) { System.out.println("Cannot Divide by 0"); return; } if (dividend == 0) { System.out.println(a + " / " + b + " is equal to : " + 0); return; } if (divisor == 1) { System.out.println(a + " / " + b + " is equal to : " + sign * dividend); return; } // Using Formula // derived above. System.out.println(a + " / " + b + " is equal to : " + Math.floor(sign * (Math.exp(Math.log(dividend) - Math.log(divisor)))));} // Driver codepublic static void main (String[] args){int a = 10, b = 5; Divide(a, b); a = 49; b = -7;Divide(a, b);}} // This code is contributed// by shiv_bhakt.
# Python3 program# for above approachimport mathdef Divide(a, b): dividend = a; divisor = b; # Calculate sign of divisor # i.e., sign will be negative # only if either one of them # is negative otherwise it # will be positive sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1; # Remove signs of # dividend and divisor dividend = abs(dividend); divisor = abs(divisor); # Zero division Exception. if (divisor == 0): print("Cannot Divide by 0"); if (dividend == 0): print(a, "/", b, "is equal to :", 0); if (divisor == 1): print(a, "/", b, "is equal to :", (sign * dividend)); # Using Formula # derived above. print(a, "/", b, "is equal to :", math.floor(sign * math.exp(math.log(dividend) - math.log(divisor)))); # Driver codea = 10;b = 5; Divide(a, b); a = 49;b = -7;Divide(a, b); # This code is contributed# by mits
// C# program for// above approachusing System; class GFG{static void Divide(int a, int b){ long dividend = (long)a; long divisor = (long)b; // Calculate sign of divisor // i.e., sign will be negative // only if either one of them // is negative otherwise it // will be positive long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.Abs(dividend); divisor = Math.Abs(divisor); // Zero division Exception. if (divisor == 0) { Console.WriteLine("Cannot Divide by 0"); return; } if (dividend == 0) { Console.WriteLine(a + " / " + b + " is equal to : " + 0); return; } if (divisor == 1) { Console.WriteLine(a + " / " + b + " is equal to : " + sign * dividend); return; } // Using Formula // derived above. Console.WriteLine(a + " / " + b + " is equal to : " + Math.Floor(sign * (Math.Exp(Math.Log(dividend) - Math.Log(divisor)))));} // Driver codepublic static void Main (){ int a = 10, b = 5; Divide(a, b); a = 49; b = -7; Divide(a, b);}} // This code is contributed// by shiv_bhakt.
<?php// PHP program for above approach function Divide($a, $b){ $dividend = $a; $divisor = $b; // Calculate sign of divisor // i.e., sign will be negative // only if either one of them // is negative otherwise it // will be positive $sign = ($dividend < 0) ^ ($divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor $dividend = abs($dividend); $divisor = abs($divisor); // Zero division Exception. if ($divisor == 0) { echo "Cannot Divide by 0"; echo""; } if ($dividend == 0) { echo $a , " / " , $b , " is equal to : " , 0 ; echo ""; } if ($divisor == 1) { echo $a , " / " , $b , " is equal to : ", $sign * $dividend. "\n"; echo ""; } // Using Formula // derived above. echo $a , " / " , $b , " is equal to : " , $sign * exp(log($dividend) - log($divisor)). "\n"; echo "";} // Driver code$a = 10;$b = 5; Divide($a, $b); $a = 49;$b = -7;Divide($a, $b); // This code is contributed// by shiv_bhakt.?>
<script> // Javascript program for// above approach function Divide(a, b){ var dividend = a; var divisor = b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive var sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.abs(dividend); divisor = Math.abs(divisor); // Zero division Exception. if (divisor == 0) { document.write("Cannot Divide by 0"); return; } if (dividend == 0) { document.write(a + " / " + b + " is equal to : " + 0 + "<br>"); return; } if (divisor == 1) { System.out.println(a + " / " + b + " is equal to : " + sign * dividend + "<br>"); return; } // Using Formula // derived above. document.write(a + " / " + b + " is equal to : " + Math.floor(sign * (Math.exp(Math.log(dividend) - Math.log(divisor)))) + "<br>");} // Driver Codevar a = 10, b = 5; Divide(a, b); a = 49; b = -7;Divide(a, b); // This code is contributed by Kirti </script>
10 / 5 is equal to : 2
49 / -7 is equal to : -7
Vishal_Khoda
Mithun Kumar
Kirti_Mangal
maths-log
C++ Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
cin in C++
Count substrings that contain all vowels | SET 2
Generics in C++
Shallow Copy and Deep Copy in C++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24455,
"s": 24427,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 24595,
"s": 24455,
"text": "Given two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator.Examples: "
},
{
"code": null,
"e": 24660,
"s": 24595,
"text": "Input: a = 10, b = 3\nOutput: 3\n\nInput: a = 43, b = -8\nOutput: -5"
},
{
"code": null,
"e": 24769,
"s": 24662,
"text": "This problem has been already discussed here. In this post, a different approach is discussed.Approach : "
},
{
"code": null,
"e": 24914,
"s": 24769,
"text": "Let a/b = c.Take log on both sideslog(a) β log(b) = log(c)Now Log of RHS can be written as exp in LHSFinal formula is : exp(log(a) β log(b)) = c"
},
{
"code": null,
"e": 24927,
"s": 24914,
"text": "Let a/b = c."
},
{
"code": null,
"e": 24950,
"s": 24927,
"text": "Take log on both sides"
},
{
"code": null,
"e": 24975,
"s": 24950,
"text": "log(a) β log(b) = log(c)"
},
{
"code": null,
"e": 25019,
"s": 24975,
"text": "Now Log of RHS can be written as exp in LHS"
},
{
"code": null,
"e": 25063,
"s": 25019,
"text": "Final formula is : exp(log(a) β log(b)) = c"
},
{
"code": null,
"e": 25069,
"s": 25065,
"text": "C++"
},
{
"code": null,
"e": 25074,
"s": 25069,
"text": "Java"
},
{
"code": null,
"e": 25082,
"s": 25074,
"text": "Python3"
},
{
"code": null,
"e": 25085,
"s": 25082,
"text": "C#"
},
{
"code": null,
"e": 25089,
"s": 25085,
"text": "PHP"
},
{
"code": null,
"e": 25100,
"s": 25089,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Returns the quotient of dividend/divisor.void Divide(int a, int b){ long long dividend = (long long)a; long long divisor = (long long)b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive long long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of dividend and divisor dividend = abs(dividend); divisor = abs(divisor); // Zero division Exception. if (divisor == 0) { cout << \"Cannot Divide by 0\" << endl; return; } if (dividend == 0) { cout << a << \" / \" << b << \" is equal to : \" << 0 << endl; return; } if (divisor == 1) { cout << a << \" / \" << b << \" is equal to : \" << sign * dividend << endl; return; } // Using Formula derived above. cout << a << \" / \" << b << \" is equal to : \" << sign * exp(log(dividend) - log(divisor)) << endl;} // Drivers codeint main(){ int a = 10, b = 5; Divide(a, b); a = 49, b = -7; Divide(a, b); return 0;}",
"e": 26286,
"s": 25100,
"text": null
},
{
"code": "// Java program for// above approachimport java.io.*; class GFG{static void Divide(int a, int b){ long dividend = (long)a; long divisor = (long)b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.abs(dividend); divisor = Math.abs(divisor); // Zero division Exception. if (divisor == 0) { System.out.println(\"Cannot Divide by 0\"); return; } if (dividend == 0) { System.out.println(a + \" / \" + b + \" is equal to : \" + 0); return; } if (divisor == 1) { System.out.println(a + \" / \" + b + \" is equal to : \" + sign * dividend); return; } // Using Formula // derived above. System.out.println(a + \" / \" + b + \" is equal to : \" + Math.floor(sign * (Math.exp(Math.log(dividend) - Math.log(divisor)))));} // Driver codepublic static void main (String[] args){int a = 10, b = 5; Divide(a, b); a = 49; b = -7;Divide(a, b);}} // This code is contributed// by shiv_bhakt.",
"e": 27655,
"s": 26286,
"text": null
},
{
"code": "# Python3 program# for above approachimport mathdef Divide(a, b): dividend = a; divisor = b; # Calculate sign of divisor # i.e., sign will be negative # only if either one of them # is negative otherwise it # will be positive sign = -1 if ((dividend < 0) ^ (divisor < 0)) else 1; # Remove signs of # dividend and divisor dividend = abs(dividend); divisor = abs(divisor); # Zero division Exception. if (divisor == 0): print(\"Cannot Divide by 0\"); if (dividend == 0): print(a, \"/\", b, \"is equal to :\", 0); if (divisor == 1): print(a, \"/\", b, \"is equal to :\", (sign * dividend)); # Using Formula # derived above. print(a, \"/\", b, \"is equal to :\", math.floor(sign * math.exp(math.log(dividend) - math.log(divisor)))); # Driver codea = 10;b = 5; Divide(a, b); a = 49;b = -7;Divide(a, b); # This code is contributed# by mits",
"e": 28642,
"s": 27655,
"text": null
},
{
"code": "// C# program for// above approachusing System; class GFG{static void Divide(int a, int b){ long dividend = (long)a; long divisor = (long)b; // Calculate sign of divisor // i.e., sign will be negative // only if either one of them // is negative otherwise it // will be positive long sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.Abs(dividend); divisor = Math.Abs(divisor); // Zero division Exception. if (divisor == 0) { Console.WriteLine(\"Cannot Divide by 0\"); return; } if (dividend == 0) { Console.WriteLine(a + \" / \" + b + \" is equal to : \" + 0); return; } if (divisor == 1) { Console.WriteLine(a + \" / \" + b + \" is equal to : \" + sign * dividend); return; } // Using Formula // derived above. Console.WriteLine(a + \" / \" + b + \" is equal to : \" + Math.Floor(sign * (Math.Exp(Math.Log(dividend) - Math.Log(divisor)))));} // Driver codepublic static void Main (){ int a = 10, b = 5; Divide(a, b); a = 49; b = -7; Divide(a, b);}} // This code is contributed// by shiv_bhakt.",
"e": 30018,
"s": 28642,
"text": null
},
{
"code": "<?php// PHP program for above approach function Divide($a, $b){ $dividend = $a; $divisor = $b; // Calculate sign of divisor // i.e., sign will be negative // only if either one of them // is negative otherwise it // will be positive $sign = ($dividend < 0) ^ ($divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor $dividend = abs($dividend); $divisor = abs($divisor); // Zero division Exception. if ($divisor == 0) { echo \"Cannot Divide by 0\"; echo\"\"; } if ($dividend == 0) { echo $a , \" / \" , $b , \" is equal to : \" , 0 ; echo \"\"; } if ($divisor == 1) { echo $a , \" / \" , $b , \" is equal to : \", $sign * $dividend. \"\\n\"; echo \"\"; } // Using Formula // derived above. echo $a , \" / \" , $b , \" is equal to : \" , $sign * exp(log($dividend) - log($divisor)). \"\\n\"; echo \"\";} // Driver code$a = 10;$b = 5; Divide($a, $b); $a = 49;$b = -7;Divide($a, $b); // This code is contributed// by shiv_bhakt.?>",
"e": 31147,
"s": 30018,
"text": null
},
{
"code": "<script> // Javascript program for// above approach function Divide(a, b){ var dividend = a; var divisor = b; // Calculate sign of divisor i.e., // sign will be negative only if // either one of them is negative // otherwise it will be positive var sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; // Remove signs of // dividend and divisor dividend = Math.abs(dividend); divisor = Math.abs(divisor); // Zero division Exception. if (divisor == 0) { document.write(\"Cannot Divide by 0\"); return; } if (dividend == 0) { document.write(a + \" / \" + b + \" is equal to : \" + 0 + \"<br>\"); return; } if (divisor == 1) { System.out.println(a + \" / \" + b + \" is equal to : \" + sign * dividend + \"<br>\"); return; } // Using Formula // derived above. document.write(a + \" / \" + b + \" is equal to : \" + Math.floor(sign * (Math.exp(Math.log(dividend) - Math.log(divisor)))) + \"<br>\");} // Driver Codevar a = 10, b = 5; Divide(a, b); a = 49; b = -7;Divide(a, b); // This code is contributed by Kirti </script>",
"e": 32420,
"s": 31147,
"text": null
},
{
"code": null,
"e": 32468,
"s": 32420,
"text": "10 / 5 is equal to : 2\n49 / -7 is equal to : -7"
},
{
"code": null,
"e": 32483,
"s": 32470,
"text": "Vishal_Khoda"
},
{
"code": null,
"e": 32496,
"s": 32483,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32509,
"s": 32496,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 32519,
"s": 32509,
"text": "maths-log"
},
{
"code": null,
"e": 32532,
"s": 32519,
"text": "C++ Programs"
},
{
"code": null,
"e": 32545,
"s": 32532,
"text": "Mathematical"
},
{
"code": null,
"e": 32558,
"s": 32545,
"text": "Mathematical"
},
{
"code": null,
"e": 32656,
"s": 32558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32665,
"s": 32656,
"text": "Comments"
},
{
"code": null,
"e": 32678,
"s": 32665,
"text": "Old Comments"
},
{
"code": null,
"e": 32704,
"s": 32678,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 32715,
"s": 32704,
"text": "cin in C++"
},
{
"code": null,
"e": 32764,
"s": 32715,
"text": "Count substrings that contain all vowels | SET 2"
},
{
"code": null,
"e": 32780,
"s": 32764,
"text": "Generics in C++"
},
{
"code": null,
"e": 32814,
"s": 32780,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 32844,
"s": 32814,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32904,
"s": 32844,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32919,
"s": 32904,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32962,
"s": 32919,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
What is the difference between root.destroy() and root.quit() in Tkinter(Python)?
|
When we invoke the destroy() method with the tkinter window object, it terminates the mainloop process and destroys all the widgets inside the window. Tkinter destroy() method is mainly used to kill and terminate the interpreter running in the background.
However, quit() method can be invoked in order to stop the process after the mainloop() function. We can demonstrate the functionalities of both methods by creating a button Object.
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Set the geometry of frame
win.geometry("650x450")
#Define a function for Button Object
def quit_win():
win.quit()
def destroy_win():
win.destroy()
#Button for Quit Method
Button(win,text="Quit", command=quit_win, font=('Helvetica
bold',20)).pack(pady=5)
#Button for Destroy Method
Button(win, text= "Destroy", command=destroy_win, font=('Helvetica
bold',20)).pack(pady=5)
win.mainloop()
Running the code will display a window with two buttons βQuitβ and βDestroyβ respectively.
Warning β quit() will terminate the application abruptly, hence it is recommended that you close the application from the manager after execution.
|
[
{
"code": null,
"e": 1318,
"s": 1062,
"text": "When we invoke the destroy() method with the tkinter window object, it terminates the mainloop process and destroys all the widgets inside the window. Tkinter destroy() method is mainly used to kill and terminate the interpreter running in the background."
},
{
"code": null,
"e": 1500,
"s": 1318,
"text": "However, quit() method can be invoked in order to stop the process after the mainloop() function. We can demonstrate the functionalities of both methods by creating a button Object."
},
{
"code": null,
"e": 1999,
"s": 1500,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Set the geometry of frame\nwin.geometry(\"650x450\")\n\n#Define a function for Button Object\ndef quit_win():\n win.quit()\ndef destroy_win():\n win.destroy()\n\n#Button for Quit Method\nButton(win,text=\"Quit\", command=quit_win, font=('Helvetica\nbold',20)).pack(pady=5)\n\n#Button for Destroy Method\nButton(win, text= \"Destroy\", command=destroy_win, font=('Helvetica\nbold',20)).pack(pady=5)\nwin.mainloop()"
},
{
"code": null,
"e": 2090,
"s": 1999,
"text": "Running the code will display a window with two buttons βQuitβ and βDestroyβ respectively."
},
{
"code": null,
"e": 2237,
"s": 2090,
"text": "Warning β quit() will terminate the application abruptly, hence it is recommended that you close the application from the manager after execution."
}
] |
Instruction type RAL in 8085 Microprocessor
|
In 8085 Instruction set, there is another mnemonic RAL,which stands or Rotate Accumulator Left and also involving Cy flag in rotation. It rotates the Accumulator contents to the left by 1-bit position. The following Fig. is depicting the execution logic of the instruction.
From the Fig. we can see that the due to left rotation the bit which is coming out from the most significant place will be copied to the Cy flag bit. And the previous Cy bit will be moved to least significant bit place of the Accumulator. Thus it is a 9-bit rotation of Accumulator and Cy contents. Only Cy flag is affected by this instruction execution.
The instruction can be used for multiple purposes.
To find the most significant bit of the Accumulator, performing rotate left.
To find the most significant bit of the Accumulator, performing rotate left.
To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation.
To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation.
As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well.
As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well.
Let us consider the following examples for the better understanding.
35H ---> 0011 0101
0 0110 1010 ---> 6AH (Prev. Cy bit as the Last bit)
Note that Accumulator value has been doubled compared with the previous value.
35H ---> 0011 0101
0 0110 1011 ---> 6BH(Prev. Cy bit as the Last bit)
Here the current Accumulator content is not doubled compared to the initial content of the Accumulator. As in this case because most significant bit of Accumulator was a 1 before rotation.
The timing diagram against this instruction RAL execution is as follows β
Summary β So this instruction RAL requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
|
[
{
"code": null,
"e": 1336,
"s": 1062,
"text": "In 8085 Instruction set, there is another mnemonic RAL,which stands or Rotate Accumulator Left and also involving Cy flag in rotation. It rotates the Accumulator contents to the left by 1-bit position. The following Fig. is depicting the execution logic of the instruction."
},
{
"code": null,
"e": 1691,
"s": 1336,
"text": "From the Fig. we can see that the due to left rotation the bit which is coming out from the most significant place will be copied to the Cy flag bit. And the previous Cy bit will be moved to least significant bit place of the Accumulator. Thus it is a 9-bit rotation of Accumulator and Cy contents. Only Cy flag is affected by this instruction execution."
},
{
"code": null,
"e": 1742,
"s": 1691,
"text": "The instruction can be used for multiple purposes."
},
{
"code": null,
"e": 1819,
"s": 1742,
"text": "To find the most significant bit of the Accumulator, performing rotate left."
},
{
"code": null,
"e": 1896,
"s": 1819,
"text": "To find the most significant bit of the Accumulator, performing rotate left."
},
{
"code": null,
"e": 2018,
"s": 1896,
"text": "To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation."
},
{
"code": null,
"e": 2140,
"s": 2018,
"text": "To perform multiplication by 2. We know that if we multiply a number by 2n then the number will have n-bit left rotation."
},
{
"code": null,
"e": 2279,
"s": 2140,
"text": "As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well."
},
{
"code": null,
"e": 2418,
"s": 2279,
"text": "As during rotation, an empty space will get created. So to put a new bit at that least significant space we can use this mnemonic as well."
},
{
"code": null,
"e": 2487,
"s": 2418,
"text": "Let us consider the following examples for the better understanding."
},
{
"code": null,
"e": 2558,
"s": 2487,
"text": "35H ---> 0011 0101\n0 0110 1010 ---> 6AH (Prev. Cy bit as the Last bit)"
},
{
"code": null,
"e": 2637,
"s": 2558,
"text": "Note that Accumulator value has been doubled compared with the previous value."
},
{
"code": null,
"e": 2707,
"s": 2637,
"text": "35H ---> 0011 0101\n0 0110 1011 ---> 6BH(Prev. Cy bit as the Last bit)"
},
{
"code": null,
"e": 2896,
"s": 2707,
"text": "Here the current Accumulator content is not doubled compared to the initial content of the Accumulator. As in this case because most significant bit of Accumulator was a 1 before rotation."
},
{
"code": null,
"e": 2970,
"s": 2896,
"text": "The timing diagram against this instruction RAL execution is as follows β"
},
{
"code": null,
"e": 3113,
"s": 2970,
"text": "Summary β So this instruction RAL requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram."
}
] |
SAS - Fishers Exact Tests
|
Fisher's exact test is a statistical test used to determine if there are nonrandom associations between two categorical variables.In SAS this is carried out using PROC FREQ. We use the Tables option to use the two variables subjected to Fisher Exact test.
The basic syntax for applying Fisher Exact test in SAS is β
PROC FREQ DATA = dataset ;
TABLES Variable_1*Variable_2 / fisher;
Following is the description of the parameters used β
dataset is the name of the dataset.
dataset is the name of the dataset.
Variable_1*Variable_2 are the variables form the dataset .
Variable_1*Variable_2 are the variables form the dataset .
To apply Fisher's Exact Test, we choose two categorical variables named Test1 and Test2 and their result.We use PROC FREQ to apply the test shown below.
data temp;
input Test1 Test2 Result @@;
datalines;
1 1 3 1 2 1 2 1 1 2 2 3
;
proc freq;
tables Test1*Test2 / fisher;
run;
When the above code is executed, we get the following result β
50 Lectures
5.5 hours
Code And Create
124 Lectures
30 hours
Juan Galvan
162 Lectures
31.5 hours
Yossef Ayman Zedan
35 Lectures
2.5 hours
Ermin Dedic
167 Lectures
45.5 hours
Muslim Helalee
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2839,
"s": 2583,
"text": "Fisher's exact test is a statistical test used to determine if there are nonrandom associations between two categorical variables.In SAS this is carried out using PROC FREQ. We use the Tables option to use the two variables subjected to Fisher Exact test."
},
{
"code": null,
"e": 2899,
"s": 2839,
"text": "The basic syntax for applying Fisher Exact test in SAS is β"
},
{
"code": null,
"e": 2965,
"s": 2899,
"text": "PROC FREQ DATA = dataset ;\nTABLES Variable_1*Variable_2 / fisher;"
},
{
"code": null,
"e": 3019,
"s": 2965,
"text": "Following is the description of the parameters used β"
},
{
"code": null,
"e": 3055,
"s": 3019,
"text": "dataset is the name of the dataset."
},
{
"code": null,
"e": 3091,
"s": 3055,
"text": "dataset is the name of the dataset."
},
{
"code": null,
"e": 3150,
"s": 3091,
"text": "Variable_1*Variable_2 are the variables form the dataset ."
},
{
"code": null,
"e": 3209,
"s": 3150,
"text": "Variable_1*Variable_2 are the variables form the dataset ."
},
{
"code": null,
"e": 3362,
"s": 3209,
"text": "To apply Fisher's Exact Test, we choose two categorical variables named Test1 and Test2 and their result.We use PROC FREQ to apply the test shown below."
},
{
"code": null,
"e": 3487,
"s": 3362,
"text": "data temp;\ninput Test1 Test2 Result @@;\ndatalines;\n1 1 3 1 2 1 2 1 1 2 2 3\n;\nproc freq; \ntables Test1*Test2 / fisher;\nrun;\n"
},
{
"code": null,
"e": 3550,
"s": 3487,
"text": "When the above code is executed, we get the following result β"
},
{
"code": null,
"e": 3585,
"s": 3550,
"text": "\n 50 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3602,
"s": 3585,
"text": " Code And Create"
},
{
"code": null,
"e": 3637,
"s": 3602,
"text": "\n 124 Lectures \n 30 hours \n"
},
{
"code": null,
"e": 3650,
"s": 3637,
"text": " Juan Galvan"
},
{
"code": null,
"e": 3687,
"s": 3650,
"text": "\n 162 Lectures \n 31.5 hours \n"
},
{
"code": null,
"e": 3707,
"s": 3687,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 3742,
"s": 3707,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3755,
"s": 3742,
"text": " Ermin Dedic"
},
{
"code": null,
"e": 3792,
"s": 3755,
"text": "\n 167 Lectures \n 45.5 hours \n"
},
{
"code": null,
"e": 3808,
"s": 3792,
"text": " Muslim Helalee"
},
{
"code": null,
"e": 3815,
"s": 3808,
"text": " Print"
},
{
"code": null,
"e": 3826,
"s": 3815,
"text": " Add Notes"
}
] |
.NET Core - Quick Guide
|
.NET Core is the latest general purpose development platform maintained by Microsoft. It works across different platforms and has been redesigned in a way that makes .NET fast, flexible and modern. This happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in Open Source.
In this tutorial, we will cover .NET Core and a few new innovations including the .NET Framework updates, .NET Standard, and Universal Windows Platform updates, etc.
The following are the major characteristics of .NET Core β
.NET Core is an open source implementation, using MIT and Apache 2 licenses.
.NET Core is an open source implementation, using MIT and Apache 2 licenses.
.NET Core is a .NET Foundation project and is available on GitHub.
.NET Core is a .NET Foundation project and is available on GitHub.
As an open source project, it promotes a more transparent development process and promotes an active and engaged community.
As an open source project, it promotes a more transparent development process and promotes an active and engaged community.
Application implemented in .NET Core can be run and its code can be reused regardless of your platform target.
Application implemented in .NET Core can be run and its code can be reused regardless of your platform target.
It currently supports three main operating systems (OS)
Windows
Linux
MacOS
It currently supports three main operating systems (OS)
Windows
Windows
Linux
Linux
MacOS
MacOS
The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
There can be two types of deployments for .NET Core applications β
Framework-dependent deployment
Self-contained deployment
There can be two types of deployments for .NET Core applications β
Framework-dependent deployment
Framework-dependent deployment
Self-contained deployment
Self-contained deployment
With framework-dependent deployment, your app depends on a system-wide version of .NET Core on which your app and third-party dependencies are installed.
With framework-dependent deployment, your app depends on a system-wide version of .NET Core on which your app and third-party dependencies are installed.
With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions.
With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions.
All product scenarios can be exercised at the command-line.
All product scenarios can be exercised at the command-line.
.NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library
.NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library
.NET Core is released through NuGet in smaller assembly packages.
.NET Core is released through NuGet in smaller assembly packages.
.NET Framework is one large assembly that contains most of the core functionalities.
.NET Framework is one large assembly that contains most of the core functionalities.
.NET Core is made available as smaller feature-centric packages.
.NET Core is made available as smaller feature-centric packages.
This modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app.
This modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app.
The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model.
The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model.
.NET Core Platform contains the following main parts β
.NET Runtime β It provides a type system, assembly loading, a garbage collector, native interop and other basic services.
.NET Runtime β It provides a type system, assembly loading, a garbage collector, native interop and other basic services.
Fundamental Libraries β A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.
Fundamental Libraries β A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.
SDK & Compiler β A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.
SDK & Compiler β A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.
βdotnetβ app host β It is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.
βdotnetβ app host β It is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.
In this chapter, we will discuss the various dependencies that you need to deploy and run. These include the .NET Core applications on Windows machines that are developed using Visual Studio.
.NET Core is supported on the following versions of Windows β
Windows 7 SP1
Windows 8.1
Windows 10
Windows Server 2008 R2 SP1 (Full Server or Server Core)
Windows Server 2012 SP1 (Full Server or Server Core)
Windows Server 2012 R2 SP1 (Full Server or Server Core)
Windows Server 2016 (Full Server, Server Core or Nano Server)
If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable.
If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable.
This dependency is automatically installed for you if you use the .NET Core installer.
This dependency is automatically installed for you if you use the .NET Core installer.
You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application.
You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application.
For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update.
For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update.
To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice.
To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice.
However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions β
Visual Studio 2015
Visual Studio 2017 RC
However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions β
Visual Studio 2015
Visual Studio 2015
Visual Studio 2017 RC
Visual Studio 2017 RC
Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based.
Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based.
In this chapter, we will discuss the Environment Setup of .NET Core. It is a significant redesign of the .NET Framework. To use .NET Core in your application, there are two versions you can use β
Visual Studio 2015
Visual Studio 2017 RC
To use Visual Studio 2015, you must have installed the following β
Microsoft Visual Studio 2015 Update 3
Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2
Microsoft provides a free version of visual studio which also contains the SQL Server and can be downloaded from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx and Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2 can be downloaded from https://www.visualstudio.com/downloads/
You can also follow the installation guidelines on the following Url https://www.microsoft.com/net/core/#windowsvs2017
Follow these steps to install Visual Studio 2015 β
Step 1 β Once the downloading completes, then run the installer. The following dialog box will be displayed.
Step 2 β Click Install to start the installation process.
Step 3 β Once the installation completes, you will see the following dialog box.
Step 4 β Close this dialog and restart your computer if required.
Step 5 β Open Visual Studio from the Start Menu; you will receive the following dialog box. It may take a few minutes to load and finally be used for the first time.
Step 6 β Once it is loaded, you will see the following screen.
Step 7 β Once Visual Studio installation is finished, then close Visual Studio and launch Microsoft .NET Core - VS 2015 Tooling Preview 2.
Step 8 β Check the checkbox and click Install.
Step 9 β Once the installation completes, you will see the following dialog box.
You are now ready to start your application using .NET Core.
In this tutorial, we will be using Visual Studio 2015, but if you want to use Visual Studio 2017, an experimental release of .NET Core tools for Visual Studio is included in Visual Studio 2017 RC and you can see the installation guidelines here https://www.microsoft.com/net/core/#windowsvs2017
Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start building a new .NET Core Application.
In the New Project dialog box, in the Templates list, expand the Visual C# node and select .NET Core and you should see the following three new project templates
Class Library (.NET Core)
Console Application (.NET Core)
ASP.NET Core Web Application (.NET Core)
In the middle pane on the New Project dialog box, select Console Application (.NET Core) and name it "FirstApp", then click OK.
Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project.
To test that .NET core console application is working, let us add the following line.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Program {
public static void Main(string[] args) {
Console.WriteLine("Hello guys, welcome to .NET Core world!");
}
}
}
Now, run the application. You should see the following output.
.NET Core supports the standard numeric integral and floating-point primitives. It also supports the following types β
System.Numerics.BigInteger which is an integral type with no upper or lower bound.
System.Numerics.BigInteger which is an integral type with no upper or lower bound.
System.Numerics.Complex is a type that represents complex numbers.
System.Numerics.Complex is a type that represents complex numbers.
A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace.
A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace.
.NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length. All integers are value types.
The following table represents the integral types and their size;
Each integral type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators.
You can also work with the individual bits in an integer value by using the System.BitConverter class.
.NET Core includes three primitive floating point types, which are shown in the following table.
Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators.
Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators.
You can also work with the individual bits in Double and Single values by using the BitConverter class.
You can also work with the individual bits in Double and Single values by using the BitConverter class.
The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value's individual bits, as well as its own set of methods for performing some additional mathematical operations.
The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value's individual bits, as well as its own set of methods for performing some additional mathematical operations.
System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
The methods of the BigInteger type is closely parallel to those of the other integral types.
The methods of the BigInteger type is closely parallel to those of the other integral types.
The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part
The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part
It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods.
It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods.
The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core.
The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core.
SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors.
SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors.
The SIMD-enabled vector types in .NET Core include the following β
System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single.
The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal.
Two matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix.
The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations.
The SIMD-enabled vector types in .NET Core include the following β
System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single.
System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single.
The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal.
The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal.
Two matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix.
Two matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix.
The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations.
The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations.
In this chapter, we will cover the concept of Garbage collection which is one of most important features of the .NET managed code platform. The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager.
You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory
You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory
An allocation is made any time you declare an object with a βnewβ keyword or a value type is boxed. Allocations are typically very fast
An allocation is made any time you declare an object with a βnewβ keyword or a value type is boxed. Allocations are typically very fast
When there isnβt enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations.
When there isnβt enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations.
This process is known as garbage collection.
This process is known as garbage collection.
Garbage Collection provides the following benefits β
You donβt need to free memory manually while developing your application.
You donβt need to free memory manually while developing your application.
It also allocates objects on the managed heap efficiently.
It also allocates objects on the managed heap efficiently.
When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations.
When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations.
Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.
Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.
It also provides memory safety by making sure that an object cannot use the content of another object.
It also provides memory safety by making sure that an object cannot use the content of another object.
Garbage collection occurs when one of the following conditions is true.
The system has low physical memory.
The system has low physical memory.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs.
The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
The .NET Garbage Collector has 3 generations and each generation has its own heap that that is used for the storage of allocated objects. There is a basic principle that most objects are either short-lived or long-lived.
In Generation 0, objects are first allocated.
In Generation 0, objects are first allocated.
In this generation, objects often donβt live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs.
In this generation, objects often donβt live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs.
Generation 0 is quick to collect because its associated heap is small.
Generation 0 is quick to collect because its associated heap is small.
In Generation 1, objects have a second chance space.
In Generation 1, objects have a second chance space.
Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1.
Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1.
Generation 1 collections are also quick because its associated heap is also small.
Generation 1 collections are also quick because its associated heap is also small.
The first two heaps remain small because objects are either collected or promoted to the next generation heap.
The first two heaps remain small because objects are either collected or promoted to the next generation heap.
In Generation 2, all long objects are lived and its heap can grow to be very large.
In Generation 2, all long objects are lived and its heap can grow to be very large.
The objects in this generation can survive a long time and there is no next generation heap to further promote objects.
The objects in this generation can survive a long time and there is no next generation heap to further promote objects.
The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH).
The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH).
It is reserved for objects that are 85,000 bytes or greater.
It is reserved for objects that are 85,000 bytes or greater.
Large objects are not allocated to the generational heaps but are allocated directly to the LOH
Large objects are not allocated to the generational heaps but are allocated directly to the LOH
Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data.
Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data.
Large server programs are known to have heaps in the 10s of GBs.
Large server programs are known to have heaps in the 10s of GBs.
The GC employs a variety of techniques to reduce the amount of time that it blocks program execution.
The GC employs a variety of techniques to reduce the amount of time that it blocks program execution.
The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution.
The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution.
The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance.
The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance.
In this chapter, we will understand the execution process of .NET Core and compare it with the .NET Framework. The managed execution process includes the following steps.
Choosing a compiler
Compiling your code to MSIL
Compiling MSIL to native code
Running code
It is a multi-language execution environment, the runtime supports a wide variety of data types and language features.
It is a multi-language execution environment, the runtime supports a wide variety of data types and language features.
To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime.
To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime.
Compiling translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata.
Compiling translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata.
Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time.
Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time.
The runtime locates and extracts the metadata from the file as well as from framework class libraries (FCL) as needed during execution.
The runtime locates and extracts the metadata from the file as well as from framework class libraries (FCL) as needed during execution.
At execution time, a just-in-time (JIT) compiler translates the MSIL into native code.
At execution time, a just-in-time (JIT) compiler translates the MSIL into native code.
During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe.
During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe.
The common language runtime provides the infrastructure that enables the execution to take place and services that can be used during execution.
The common language runtime provides the infrastructure that enables the execution to take place and services that can be used during execution.
During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support.
During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support.
Now letβs relate how code executes with .NET Core as compared to .NET Framework. In .NET Core there are many replacements of these components that are the part of the .NET Framework.
In .NET Core now we have a new series of compilers, like we have Roslyn for C# and VB.
In .NET Core now we have a new series of compilers, like we have Roslyn for C# and VB.
You can also make use of the new F# 4.1 compiler if you want to use F# with .NET Core.
You can also make use of the new F# 4.1 compiler if you want to use F# with .NET Core.
Actually these tools are different and we can use Roslyn with .NET Framework as well if we are using C# 6 or later, because C# compiler can only support up to C# 5.
Actually these tools are different and we can use Roslyn with .NET Framework as well if we are using C# 6 or later, because C# compiler can only support up to C# 5.
In .NET Core, we donβt have a framework class libraries (FCL), so a different set of libraries are used and we now have CoreFx.
In .NET Core, we donβt have a framework class libraries (FCL), so a different set of libraries are used and we now have CoreFx.
CoreFx is the reimplementation of the class libraries for .NET Core.
CoreFx is the reimplementation of the class libraries for .NET Core.
We also have a new run time with .NET Core known as CoreCLR and leverages a JIT Compiler.
We also have a new run time with .NET Core known as CoreCLR and leverages a JIT Compiler.
Now the question is why do we have the reimplementation of all these components that we already have in .NET framework.
Now the question is why do we have the reimplementation of all these components that we already have in .NET framework.
So the answer is the same as why Microsoft implemented .NET Core.
So the answer is the same as why Microsoft implemented .NET Core.
It is another consideration of .NET Core to build and implement application that is modular. Instead of installing the entire .NET Framework, your application can now just install what is required. Let us go to the visual studio and see the modularity.
Here is our simple .NET Core application, in Solution Explorer. Let us expand References and you will see reference to .NETCoreApp
Inside .NETCoreApp, you will see package reference to NuGet; let us expand it.
You will see the whole series of NuGet Package references. If you have worked in .NET Framework, then many of these namespaces will look familiar, because you are used to it by using in .NET Framework.
.NET Framework is split into many different pieces and re-implemented with CoreFx; these pieces are further distributed as individual packages.
Now if you expand the NETStandard.Library, you will see addition references. You will even notice System.Console which we are using in this application.
Now if you expand the NETStandard.Library, you will see addition references. You will even notice System.Console which we are using in this application.
Now you donβt have to bring in everything inside the .NET Framework, but just bring in what you need for your application.
Now you donβt have to bring in everything inside the .NET Framework, but just bring in what you need for your application.
There are some other benefits as well; for example, these modules can be updated individually if desired.
There are some other benefits as well; for example, these modules can be updated individually if desired.
Modularity leads to performance benefits and your application can run faster, especially ASP.NET Core application.
In this chapter, we will discuss .NET Core project files and how you can add existing files in your project.
Let us understand a simple example in which we have some files which are already created; we have to add these files in our FirstApp project.
Here is the implementation of the Student.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Student {
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
}
Here is the implementation of the Course.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FirstApp {
public class Course {
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
}
}
Let us now save these three files in your disk and the source folder of your project.
Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio.
Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio.
You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files.
You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files.
One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project.
One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project.
We donβt have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio.
We donβt have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio.
Let us now open the root of your project.
Let us now copy all of the three files into the root of your project.
You can now see all the files copied to the root folder.
Let us now go to Visual Studio; you will receive the following dialog box.
Click Yes to All to reload your project.
You will now that files are automatically included in your project.
In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places.
Let us now go to the source code of .NET Core which is located here β https://github.com/dotnet/corefx
In CoreFx repo, open the src folder β
And you will see the whole list of folders that correspond to different packages. Let us now search Json β
There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you wonβt know where that packages in.
If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/
Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you.
Let us now search for DataContractJson.
You will now see that we get the same package; let us click on the package.
You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods.
Let us open the project.json file.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"System.Runtime.Serialization.Json": "4.0.2"
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project.
Another way is to go to the NuGet Manager and browse the package you want to add.
In this chapter, we will discuss how to create a UWP application using .NET Core. UWP is also known as Windows 10 UWP application. This application does not run on previous versions of Windows but will only run on future version of Windows.
Following are a few exceptions where UWP will run smoothly.
If you want to run it locally you must have Windows 10, you can also develop on Windows 8 and then you will need to run it on Emulator, but it is encouraged to use Windows 10.
If you want to run it locally you must have Windows 10, you can also develop on Windows 8 and then you will need to run it on Emulator, but it is encouraged to use Windows 10.
For UWP application you will also need Windows 10 SDK. Let us open Visual Studio 2015 setup and then modify Visual Studio.
For UWP application you will also need Windows 10 SDK. Let us open Visual Studio 2015 setup and then modify Visual Studio.
On select features page, scroll down and you will see Universal Windows App Development Tools, check that option as shown below.
On select features page, scroll down and you will see Universal Windows App Development Tools, check that option as shown below.
Here you can see the different versions of SDK and the latest update on Tools as well, click Next.
Now, click the Install button.
Once the installation is finished, you will need to restart your system.
Let us now implement the UWP by following these steps.
First, launch Visual Studio 2015.
First, launch Visual Studio 2015.
Click on the File menu and select New β Project; a New Project dialog will show up. You can see the different types of templates on the left pane of the dialog box.
Click on the File menu and select New β Project; a New Project dialog will show up. You can see the different types of templates on the left pane of the dialog box.
In the left pane, you can see the tree view, now select Universal template from Templates β Visual C# β Windows.
In the left pane, you can see the tree view, now select Universal template from Templates β Visual C# β Windows.
From the center pane, select the Blank App (Universal Windows) template.
From the center pane, select the Blank App (Universal Windows) template.
Give a name to the project by typing UWPFirstApp in the Name field and click OK.
Give a name to the project by typing UWPFirstApp in the Name field and click OK.
The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project.
The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project.
Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting.
Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting.
When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files.
When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files.
Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files.
Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files.
To see the running example, let us open MainPage.XAML and add the following code.
To see the running example, let us open MainPage.XAML and add the following code.
<Page
x:Class = "UWPFirstApp.MainPage"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local = "using:UWPFirstApp"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable = "d">
<Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel HorizontalAlignment = "Center">
<TextBlock Text = "Hello, world!"
Margin = "20"
Width = "200"
HorizontalAlignment = "Left"/>
<TextBlock Text = "Write your name."
Margin = "20"
Width = "200"
HorizontalAlignment = "Left"/>
<TextBox x:Name = "txtbox"
Width = "280"
Margin = "20"
HorizontalAlignment = "Left"/>
<Button x:Name = "button" Content = "Click Me"
Margin = "20"
Click = "button_Click"/>
<TextBlock x:Name = "txtblock"
HorizontalAlignment = "Left"
Margin = "20"/>
</StackPanel>
</Grid>
</Page>
Below is the click event of button in C#.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at
// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPHellowWorld {
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page {
public MainPage() {
this.InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e) {
if (txtbox.Text != "")
txtblock.Text = "Hello: " + txtbox.Text;
else
txtblock.Text = "You have not write your name";
}
}
}
Let us now run the above code on the local machine and you will see the following window. Now type any name in the text box and press the Click Me button.
In this chapter, we will discuss what is MSBuild and how it works with .NET Core. MSBuild is the build platform for Microsoft and Visual Studio. In UWP application if you open the project folder, then you will see both project.json and *.csproj files.
But if you open our previous .NET Core Console app, then you will see project.json and *.xproj files.
The .NET Core build system or the project.json build system is not sufficient for UWP needs; this is why UWP is still using *.csproj (MSBuild) Build system.
The .NET Core build system or the project.json build system is not sufficient for UWP needs; this is why UWP is still using *.csproj (MSBuild) Build system.
But project.json will move out as far as the build system is concerned.
But project.json will move out as far as the build system is concerned.
Now if you want to add a few existing files to your UWP application as we have added in the Console app, then you need to add those files in the project folder. Further, you will also need to include in your project in Solution Explorer as well.
Now if you want to add a few existing files to your UWP application as we have added in the Console app, then you need to add those files in the project folder. Further, you will also need to include in your project in Solution Explorer as well.
Let us now consider the following files; copy these files to your project folder.
Let us go back to Visual Studio and open the Solution Explorer.
You can now see that only copying files is not sufficient in case of UWP applications, because in Solution Explorer, we canβt see those files.
You can now see that only copying files is not sufficient in case of UWP applications, because in Solution Explorer, we canβt see those files.
Now we must include those files as well by clicking on the Show All Files icon as highlighted in the above screenshot and you will see now all files in the project folder.
Now we must include those files as well by clicking on the Show All Files icon as highlighted in the above screenshot and you will see now all files in the project folder.
These two files are still not included in our project. To include these files, select these files and right-click on any file and then select Include in Project.
Now these files are also included. One good thing that can be foreseen is the project.json approach of dropping files for *.csproj in the future version of the SKD tools and also to Visual Studio.
In this chapter, we will discuss the references between our Console app and our UWP app. If you look at the References in Solution Explorer of your Console application, you will see the .NETCoreApp as shown below.
.NETCoreApp is a new framework that targeted .NET Core application. Now if you look under the References of UWP application, it will look a bit different as shown below.
The main reason for this is because here in UWP we have the *.csproj, so we are back to the old style of references and we can target only one framework with this project type.
The main reason for this is because here in UWP we have the *.csproj, so we are back to the old style of references and we can target only one framework with this project type.
The references are similar though. You can now see that in UWP application, the Miscrosoft.NETCore.UniversalWindowsPlatform NuGet Package reference is similar to the Microsoft.NETCore.App NuGet reference in Console application.
The references are similar though. You can now see that in UWP application, the Miscrosoft.NETCore.UniversalWindowsPlatform NuGet Package reference is similar to the Microsoft.NETCore.App NuGet reference in Console application.
Both Miscrosoft.NETCore.UniversalWindowsPlatform and Microsoft.NETCore.App are meta-package which means that they are composed of other packages.
Both Miscrosoft.NETCore.UniversalWindowsPlatform and Microsoft.NETCore.App are meta-package which means that they are composed of other packages.
In Console application, we can drill in and see other packages inside Microsoft.NETCore.App, but we canβt do the same Miscrosoft.NETCore.UniversalWindowsPlatform in Solution Explorer.
In Console application, we can drill in and see other packages inside Microsoft.NETCore.App, but we canβt do the same Miscrosoft.NETCore.UniversalWindowsPlatform in Solution Explorer.
However, we can use another tool, the NuGet Package Explorer to look at this. Let us now open this url in the browser β https://npe.codeplex.com/downloads/get/clickOnce/NuGetPackageExplorer.application and you will see a small utility downloading.
However, we can use another tool, the NuGet Package Explorer to look at this. Let us now open this url in the browser β https://npe.codeplex.com/downloads/get/clickOnce/NuGetPackageExplorer.application and you will see a small utility downloading.
Once downloading completes, then double-click on that file.
Once downloading completes, then double-click on that file.
Click Install to start installation on the NuGet Package Explorer.
Click Install to start installation on the NuGet Package Explorer.
When the installation is finished, you will see the following dialog box.
When the installation is finished, you will see the following dialog box.
Let us now click on the Open a package from online feed option.
Let us now click on the Open a package from online feed option.
By default it will search for the nuget.org feed. Let us now search for Microsoft.NETCore.UniversalWindowsPlatform in the search box and you will see 1 result as shown below.
By default it will search for the nuget.org feed. Let us now search for Microsoft.NETCore.UniversalWindowsPlatform in the search box and you will see 1 result as shown below.
Click the open link and it will open the top-level dependencies of this metapackage.
Click the open link and it will open the top-level dependencies of this metapackage.
Let us now open the .NETCore meta package for the .NETCore application and meta-package for UWP application side by side.
Let us now open the .NETCore meta package for the .NETCore application and meta-package for UWP application side by side.
You can now see that each meta-package is composed of different set of packages.
You can now see that each meta-package is composed of different set of packages.
.NET Core is a subset of the classes available in .NET Framework at least at this point of time, but is growing and will be as per the base classes of .NET Framework.
.NET Core is a subset of the classes available in .NET Framework at least at this point of time, but is growing and will be as per the base classes of .NET Framework.
The UWP is based on .NET Core, it is a superset of the APIs available for Windows Store development.
The UWP is based on .NET Core, it is a superset of the APIs available for Windows Store development.
We now have more APIs available for development due to .NET Core.
Windows Runtime components are self-contained objects that you can instantiate and use from any language, including C#, Visual Basic, JavaScript, and C++. In addition to the .NET Core meta-package we saw in the previous chapter, UWP app also has a reference by default to a Universal Windows SDK.
Universal Windows is the reference to Windows Runtime and it has been factored into a series of APIs contracts.
The set of APIs within a device family is broken down into subdivisions known as API contracts. You can find a list of different API contracts here https://msdn.microsoft.com/en-us/library/windows/apps/dn706135.aspx
Most of those APIs inside windows runtime are factored into a single contract. Let us now search for the Universal keyword on the API Contracts page.
You can see links to various APIs and you can also see the Universal family is so big that it has 12 pages of documentation.
You can also search for phone API contract on this page.
Let us now click on the Windows.Phone.PhoneContract and scroll down; you will now see the battery information of phone or the mobile device.
If you want to add this information on top of what you already have, then you should add the references manually. Let us now go to the Visual Studio and right-click on the References in Solution Explorer.
Select Add References...
You can now see the new reference category for Universal Windows; under this category there is Core which refers to the core Universal Windows API contracts
The Extensions allow us to extend the functionality and you will see different references Mobile, Desktop and other Extensions.
The Extensions allow us to extend the functionality and you will see different references Mobile, Desktop and other Extensions.
There are different SKD extensions and you can add on top to get more APIs.
There are different SKD extensions and you can add on top to get more APIs.
You can also see different versions. So, make sure you get the latest version to get the updated APIs and then click OK.
You can also see different versions. So, make sure you get the latest version to get the updated APIs and then click OK.
You can now see that Windows Mobile Extensions for the UWP is added as reference.
A class library defines the types and methods that can be called from any application.
A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library.
A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library.
When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications.
When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications.
Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add β New Project...
In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template.
In the Name text box, enter "UtilityLibrary" as the name of the project, as the following figure shows.
Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add β Class...
Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UtilityLibrary {
public static class StringLib {
public static bool StartsWithUpper(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsUpper(ch);
}
public static bool StartsWithLower(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsLower(ch);
}
public static bool StartsWithNumber(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsNumber(ch);
}
}
}
The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively.
The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively.
In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric.
In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric.
On the menu bar, choose Build, Build Solution. The project should compile without error.
On the menu bar, choose Build, Build Solution. The project should compile without error.
Our .NET Core console project doesn't have access to our class library.
Our .NET Core console project doesn't have access to our class library.
Now to consume this class library we need to add reference of this class library in our console project.
Now to consume this class library we need to add reference of this class library in our console project.
To do so, expand FirstApp and right-click on References and select Add Reference...
In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK.
Let us now open the Program.cs file of the console project and replace all of the code with the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UtilityLibrary;
namespace FirstApp {
public class Program {
public static void Main(string[] args) {
int rows = Console.WindowHeight;
Console.Clear();
do {
if (Console.CursorTop >= rows || Console.CursorTop == 0) {
Console.Clear();
Console.WriteLine("\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\n");
}
string input = Console.ReadLine();
if (String.IsNullOrEmpty(input)) break;
Console.WriteLine("Input: {0} {1,30}: {2}\n", input, "Begins with uppercase? ",
input.StartsWithUpper() ? "Yes" : "No");
} while (true);
}
}
}
Let us now run your application and you will see the following output.
For better understanding, let us make use of the other extension methods of your class library in your project.
In this chapter, we will discuss what is PCL (Portable Class Library), and also why we need PCL. To understand this concept, let us open the class library project folder which we have created in the previous chapter.
In this folder, you can see that in addition to project.json and CS files we also have *.xproj file, and that is because Visual Studio setup .NET Core project type as *.xproj instead of *.csproj.
As mentioned by Microsoft, *.xproj will be going away, but it is still here in preview 2 tooling. As we have covered that UWP application uses the *.csproj.
Now it is actually not feasible to get *.csproj to reference and *.xproj and that functionality is not going to be implemented because *.xproj will move out.
So instead, we need a class library which can be shared between the console app and the UWP app and here comes PCL.
Let us now understand what PCL is β
The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform.
The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform.
You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects.
You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects.
It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily.
It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily.
Portable class libraries can help you reduce the time and costs of developing and testing code.
Portable class libraries can help you reduce the time and costs of developing and testing code.
Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc.
Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc.
Let us now remove the class library which we have created from the Solution Explorer. At the same time, delete it from the Solution folder and further add a new project item.
Select the Visual C# β Windows template in the left pane and select Class Library (Portable) in the middle pane.
Enter StringLibrary in the name field and click OK to create this project.
Now we need to select the target frameworks to reference. Let us select Windows Universal and ASP.NET Core for a moment then we will retarget it. Click OK.
You can see that it has created a new project in PCF format. Let us now right-click StringLibrary project in the Solution Explorer and select Properties.
Click on the Target .NET Platform Standard.
Click Yes; it is now the same class library with one minor difference. The difference is that it can be used by UWP as well, because it contains *.csproj file instead of *.xproj.
Let us now add a new class; for this, you need to right-click on project in Solution Explorer and select Add β Class...
Select class in the middle pane and enter StringLib.cs in the name field and then Click Add. Once the class is added, then replace the following code in StringLib.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StringLibrary {
public static class StringLib {
public static bool StartsWithUpper(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsUpper(ch);
}
public static bool StartsWithLower(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsLower(ch);
}
public static bool StartsWithNumber(this String str) {
if (String.IsNullOrWhiteSpace(str))
return false;
Char ch = str[0];
return Char.IsNumber(ch);
}
}
}
Let us build this portable class library project and it should compile without error. Now we need to add reference of this portable class library in our console project. So, expand FirstApp and right-click on References and select Add Reference...
In the Reference Manager dialog box, select StringLibrary which is our portable class library project, and then click OK.
You can see that the StringLibrary reference is added to the console project and it can be seen in the project.json file as well.
You can now run the application again and you will see the same output.
Let us now use the other extension methods of your portable class library in your project. The same portable library will be consumed in your UWP application as well.
In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project.
You can now see that the PCL project has some references by default. You can also add other references as per your application need.
In the PCL library, you can also see the project.json file.
{
"supports": {},
"dependencies": {
"NETStandard.Library": "1.6.0",
"Microsoft.NETCore.Portable.Compatibility": "1.0.1"
},
"frameworks": {
"netstandard1.3": {}
}
}
One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code.
{
"supports": {},
"dependencies": {
"NETStandard.Library": "1.6.0",
"Microsoft.NETCore.Portable.Compatibility": "1.0.1",
"System.Runtime.Serialization.Json": "4.0.3",
"Microsoft.EntityFrameworkCore": "1.1.0"
},
"frameworks": {
"netstandard1.3": {}
}
}
Let us now save this file and you will see that references are added to your library now.
The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages...
On the Browse tab, you can search any NuGet package; let us say we want to add βSystem.Runtime.Serialization.Primitivesβ package.
Click the Install button, which will display the following screen.
Now, click the OK button.
Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the βSystem.Runtime.Serialization.Primitivesβ NuGet package is added to your library.
In this chapter, we will discuss how to share your library as NuGet Package so that it can be consumed within another project. Creating a package starts with the code you want to package and share with others, either through the public nuget.org gallery or a private gallery within your organization. The package can also include additional files such as a readme that is displayed when the package is installed, and can include transformations to certain project files.
Let us now consider a simple example in which we will create a NuGet package from our library. To do so, open the command prompt and go to the folder where the project.json file of your library project is located.
Let us now run the following command.
dotnet help
At the end, you can see different commands like new, restore and build, etc.
The last command is pack; this will create a NuGet package. Let us now execute the following command.
dotnet pack
You can now see that the NuGet packages are produced in the bin folder; let us open the bin\Debug folder.
Now the question is what is inside the NuGet packages, to see that we can use NuGet Package Explorer. Let us now open the NuGet Package Explorer.
Select the first option Open a local package.
Select the StringLibrary.1.0.0.nupkg and click Open.
You can see that in the Package contents section we have StringLibrary.dll only. In the Package metadata section, you will see a bit of information about this library like Id, Versions and all the of the dependencies.
Let us now open the StringLibrary.1.0.0.symbols.nupkg.
In this NuGet package, you will see the source files and the *.pdb file as well. If you double-click on the StringLib.cs file, you see the source code as well.
Here the question is, how can configure the metadata like version, authors and description, etc.
The project.json file is used on .NET Core projects to define project metadata, compilation information, and dependencies. Let us now open the project.json file and add the following additional information.
{
"authors": [ "Mark Junior" ],
"description": "String Library API",
"version" : "1.0.1-*",
"supports": {},
"dependencies": {
"Microsoft.EntityFrameworkCore": "1.1.0",
"Microsoft.NETCore.Portable.Compatibility": "1.0.1",
"NETStandard.Library": "1.6.0",
"System.Runtime.Serialization.Json": "4.0.3",
"System.Runtime.Serialization.Primitives": "4.3.0"
},
"frameworks": {
"netstandard1.3": {}
}
}
You can now see additional information like author name, description and version added here. Let us save this file, build the library project, then execute the βdotnet packβ command again.
Inside the bin\Debug folder, you can see that the StringLibrary NuGet packages are produced with version 1.0.1; let us open it in NuGet Package Explorer.
You will see the updated metadata. The question now is, how can we use it in another package.
We need to start by publishing somewhere in the NuGet feed and then we can consume it in another project.
There are two options to publish the updated metadata β
Publish it to nuget.org
Push the metadata to private NuGet feed
Here we will be using the private NuGet feed because it is a lot easier than to setup an account on nuget.org. To learn how to publish your package to nuget.org, you can follow all the guidelines specified here https://docs.microsoft.com/en-us/nuget/create-packages/publish-a-package.
Follow these steps to push the updated metadata to private NuGet feed.
Step 1 β To start with, we need the nuget commandline utility and we have to install it. Let us now open the NuGet Package Manager and search for nuget.commandline.
Step 2 β Select Nuget.Commandline and click Install.
Step 3 β Click OK to install Nuget.Commandline. You can also manually install it by downloading it from the following Url https://dist.nuget.org/index.html and then set up the environment variable.
Step 4 β Once the installation is finished, let us open the command prompt again and go to the bin\Debug folder where the NuGet packages are located and specify the following command β
nuget add StringLibrary.1.0.1.nupkg -Source D:\PrivateNugetPackages
Step 5 β In the above command, we add the StringLibrary.1.0.1.nupkg package to our private feed and the location is D:\PrivateNugetPackages, -Source specifies the package source.
Step 6 β You can see that the StringLibrary is installed; the StringLibrary can further be added to the private feed.
Step 7 β Let us go to that folder.
Step 8 β Inside the stringlibrary folder, you will see another folder with the version name and here it is 1.0.1.
The NuGet package is located here.
In this chapter, we will discuss how to consume the NuGet package which we have created and published to a private NuGet feed. So, first we will create a Xamarin.Forms project. We need to first understand what is Xamarin.Forms.
Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces.
Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces.
Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone.
Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone.
The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform.
The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform.
To start Xamarin.Forms, we need some additional features in Visual Studio 2015. Let us modify your Visual Studio 2015 and make sure the following cross-platform mobile development option is selected.
Once the installation is finished, let us update the Xamarin by selecting Tools β Options...
Scroll down and expand Xamarin in the left pane and then select Other. On top right hand corner of the dialog box, click on Check Now to see if updates are available.
You can see that updates are available, let us click on the Download button to start downloading. Once downloading is finished, you will be notified to install the updates.
Let us now open the Visual studio again and select the File β New β Project... menu option.
In the left pane, select the Visual C# β Cross-Platform template and in the middle pane, select Blank Xaml App (Xamarin.Forms Portable). Enter the name in the Name field and click OK.
Select the Target Version and the Minimum Version and click OK.
You will see a series of projects; at the top we have the PCL library which will be shared among all platforms like Android, iOS, UWP, Windows 8.1, and Windows Phone 8.1.
Here, we will focus on the PCL library and will bring some code here. Let us expand the code.
In this Xamarin.Forms template, you can see the generic App.xaml and MainPage.xaml, uses Xamarin.Forms XAML framework which works across these platforms.
We need to import our codes and we also need the private NuGet feed we set up in the last chapter.
Let us now open the NuGet Package Manager. Click on the wheel next to the Package source dropdown list.
We need to add our private feed here, let us click on the plus (+) button.
You will see that another checkbox is added in the Available package sources section, let us specify a name and source path and click OK.
Let us now go to the Browse tab and select PrivateSource from the Package source dropdown list and you will see the StringLibrary NuGet package. Select StringLibrary and click Install.
Click OK and you will see one error.
We canβt use library with .NETPortable profile version 259, we will be fixing this error in the next chapter.
In this chapter, we will be fixing the error we got while installing the NuGet package from our private feed in Xamarin.Forms project.
We will further understand the problem in brief. To start with, let us right-click on the PCL library and select Properties.
On this page, you will see the whole series of frameworks targeted. From the error, you can see that the .NETPortable profile 259 is not compatible with our StringLibrary 1.0.1. However, it is trying to take reference from the .NET Standard 1.1 library.
Let us now see the .NET Standard Library and identify which platform is not compatible with our library.
You can see that Windows Phone Silverlight 8 is compatible with .NET Standard 1.0. If you open the following webpage, then you will see that Profile259 can support only .NET Standard 1.0.
Let us now uncheck Windows Phone Silverlight 8.
Click the OK button.
Now to fix this issue click OK and cancel the Change Targets dialog and then open Package Manager Console and execute the following command.
PM > Uninstall-Package Xamarin.Forms
Let us now go to the Properties of PCL library. Click on the Change button.
Uncheck Windows Phone Silverlight 8 and Click OK.
You can now see that Windows Phone Silverlight 8 is no longer available in Targeted framework. You can also see the profile that is the target now. To see this, let us unload the PCL library and edit the XamarinApp.csproj file.
You can see now that TargetFrameworkProfile is now Profile111.
If you open the documentation, then you will see that Profile111 is supporting .NET Standard 1.1.
Let us now reload the PCL again and open the NuGet Package Manager and try to install the StringLibrary package from private feed.
From the Dependency behavior dropdown list, select Ignore Dependencies and then click Install.
You can see that the StringLibrary package is now installed from the private feed. If you expand the References of PCL, then you will see that the StringLibrary reference is also added as shown below.
We had uninstalled the Xamarin.Forms for the Windows Phone Silverlight 8 issue. The Xamarin.Forms needs to be installed again. It is recommended that the same version is installed.
Once the installation completes, let us use the StringLibrary functionality in your application.
In this chapter, we will discuss how to create a Testing project using .NET Core. Unit testing is a development process for the software that has the smallest testable parts of an application, which are called units. They are individually and independently scrutinized for any proper operation. Unit testing is can either be automated or done manually as well.
Let us now open the New Project dialog box and select Visual C# β .NET Core template.
On this dialog box, you can see that there is no project template for unit testing. To create a unit test project, we should use the command line utility. Let us go to the Solution folder that we created; create a test folder and inside the test folder create another folder and call it StringLibraryTests.
Let us now use the dotnet commandline utility to create a new test project by executing the following command β
dotnet new -t xunittest
You can now see that a new C# project is created; let us look into the folder by executing the v command and you will see project.json and Tests.cs files as shown below.
Here is the code in project.json file.
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable"
},
"dependencies": {
"System.Runtime.Serialization.Primitives": "4.1.1",
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-192208-24"
},
"testRunner": "xunit",
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"imports": [
"dotnet5.4",
"portable-net451+win8"
]
}
}
}
Following is the code in the Test.cs file.
using System;
using Xunit;
namespace Tests {
public class Tests {
[Fact]
public void Test1() {
Assert.True(true);
}
}
}
To fetch the necessary dependencies from NuGet, let us execute the following command β
dotnet restore
We can run the test when the necessary dependencies are restored.
You can see that the compilation succeeded; as you go down you can see some information about the test executed.
Currently we have 1 test executed, 0 error, 0 failed, 0 skipped and the time taken by the execution process also mentioned as information.
In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio.
Let us open the FirstApp solution in Visual Studio.
You can see that it has only two projects and you will not be able to see the test project because we havenβt added that project in our solution.
Let us add a folder first and call it test.
Right-click on the test folder.
Select project.json file and click Open.
The following screenshot shows the code in Tests.cs file as output.
It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method.
using System;
using Xunit;
namespace Tests {
public class Tests {
[Fact]
public void Test1() {
Assert.True(true);
}
}
}
Following is the implementation of project.json file.
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable"
},
"dependencies": {
"System.Runtime.Serialization.Primitives": "4.1.1",
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-192208-24"
},
"testRunner": "xunit",
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"imports": [
"dotnet5.4",
"portable-net451+win8"
]
}
}
}
In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit.
We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework.
You will see the .NETCore.App dependeny below.
To run test in Visual Studio, let us open Test Explorer from the Test β Window β Test Explorer menu option.
And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer.
It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails.
using System;
using Xunit;
namespace Tests {
public class Tests {
[Fact]
public void Test1() {
Assert.True(false);
}
}
}
Let us execute the test again by clicking on the Run All button link.
You can now see the test failure.
In this chapter, we will test our StringLibrary and to do so, we need to rearrange our projects so that we can follow the default convention.
Let us open the global.json file.
{
"projects": [ "src", "test" ],
"sdk": {
"version": "1.0.0-preview2-003131"
}
}
At the top of this file you will see the project settings and it sets up some folder such as src and test by default.
As by convention we must have projects in these folders, this is the new convention and that is going to be used as part of .NET Core.
In the Solution Explorer, you can see that both the console project and the library project are inside the src folder while the Testing project is inside test folder.
And the projects structure in Solution Explorer doesnβt represent where the projects physically exist on the disk. Let us now open the Solution folder and you will see that StringLibrary project is not inside the src folder.
You can see that both src and test folders map to the convention specified in the global.json file. However, we have one project StringLibrary which is out of convention. Let us now add the StringLibrary project inside the src folder.
In the src folder, we have two projects and we need to fix the problem so that we can use all the projects properly. Let us go back to the Visual Studio and right-click on the StringLibrary project and select the Remove option. It wonβt delete it, but it will only remove the project.
Now right-click on the src folder and select Add β Existing Project...
Browse to the StringLibrary project which is now inside the src folder, select the StringLibrary.csproj file and click Open.
We now have to remove the reference of StringLibrary from the project.json file of the console app.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"NuGet.CommandLine": "3.5.0",
"System.Runtime.Serialization.Json": "4.0.3"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": { },
"imports": "dnxcore50"
}
}
}
Save the changes and then add a reference of StringLibrary again in your console project.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
},
"NuGet.CommandLine": "3.5.0",
"System.Runtime.Serialization.Json": "4.0.3"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"StringLibrary": {
"target": "project"
}
},
"imports": "dnxcore50"
}
}
}
Now everything should be working again and you can build StringLibrary and then FirstApp (console project) without any error. Let us now test the StringLibrary functionality using xunit. We need to add reference of StringLibrary into our testing project. Right-click on the References of StringLibraryTests project and select Add Reference...
Click OK which will add a reference of StringLibrary to our testing project. Let us now replace the following code in the Tests.cs file.
using System;
using Xunit;
using StringLibrary;
namespace Tests {
public class Tests {
[Fact]
public void StartsWithUpperCaseTest() {
string input = "Mark";
Assert.True(input.StartsWithUpper());
}
[Fact]
public void StartsWithLowerCaseTest() {
string input = "mark";
Assert.True(input.StartsWithLower());
}
[Fact]
public void StartsWithNumberCaseTest() {
string input = "123";
Assert.True(input.StartsWithNumber());
}
}
}
You can see that we have three test methods which will test the functionality of StringLibrary. Let us click the Run All link and you will see the following output in Test Explorer.
You can also run the tests from the command line. Let us open the command prompt and execute the dotnet test command.
In this chapter, we will discuss the Managed Extensibility Framework (MEF). MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications.
MEF is a library for creating lightweight, extensible applications.
MEF is a library for creating lightweight, extensible applications.
It allows application developers to discover and use extensions with no configuration required.
It allows application developers to discover and use extensions with no configuration required.
MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications.
MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications.
You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.
You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET.
MEF has been ported as Microsoft.Composition to .NET Core as well but partially.
MEF has been ported as Microsoft.Composition to .NET Core as well but partially.
Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we donβt have the catalogs which can load types from assemblies in a directory.
Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we donβt have the catalogs which can load types from assemblies in a directory.
In this chapter, we will only learn how we can use MEF in .NET Core application.
Let us understand a simple example in which we will use MEF in .NET Core console application. Let us now create a new .NET Core console project.
In the left pane, select Templates β Visual C# β .NET Core and then in the middle pane, select Console Application (.NET Core).
Enter the name of the project in the Name field and click OK.
Once the project is created, we need to add reference of Microsoft.Composition so that we can use MEF. To do so, let us right-click on the project in Solution Explorer and Manage NuGet Packages...
Search for Microsoft.Composition and click Install.
Click the OK button.
Click the I Accept button.
When the installation completes, you will find an error in References.
Let us open the project.json file.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.Composition": "1.0.30",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
You can see that the Microsoft.Composition dependency is added, but the problem is that this package is not compatible with dnxcore50. So we need to import portablenet45+win8+wp8+wpa81. Let us now replace your project.json file with the following code.
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.Composition": "1.0.30",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "portable-net45+win8+wp8+wpa81"
}
}
}
Save this file and you will see that the error is rectified.
If you expand the References, then you will see a reference of Microsoft.Composition.
First we need to create an interface that is to be exported and implement the interface and decorate the class with the export attribute. Let us now add a new class.
Enter the name for your class in the Name field and click Add.
Let us add the following code in the PrintData.cs file.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
namespace MEFDemo {
public interface IPrintData {
void Send(string message);
}
[Export(typeof(IPrintData))]
public class PrintData : IPrintData {
public void Send(string message) {
Console.WriteLine(message);
}
}
}
As mentioned above, Catalogs are not available in Microsoft.Composition namespace. So, it will load all the types from the Assembly with export attribute and attach to the import attribute as shown in the Compose method in the Program.cs file.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace MEFDemo {
public class Program {
public static void Main(string[] args) {
Program p = new Program();
p.Run();
}
public void Run() {
Compose();
PrintData.Send("Hello,this is MEF demo");
}
[Import]
public IPrintData PrintData { get; set; }
private void Compose() {
var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly };
var configuration = new ContainerConfiguration()
.WithAssembly(typeof(Program).GetTypeInfo().Assembly);
using (var container = configuration.CreateContainer()) {
PrintData = container.GetExport<IPrintData>();
}
}
}
}
Let us now run your application and you will see that it is running by instantiating the PrintData class.
To learn more about MEF, let us visit the following Url https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx for more details.
In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli
To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section.
You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system.
We are working on preview 1 of .NET Core 2.0.
Let us now look at our current tooling by opening the command prompt and execute the following command.
dotnet --info
You will see information about the currently installed version of .NET Command Line Tools on your system as shown below.
You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command.
dotnet help new
For new command language of project, you can select like C# and F# and the type of project, etc.
Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install.
The following screenshot shows the installation process.
It will start the installation process. One the installation is finished, Close this dialog.
Open the command prompt and execute the following command.
dotnet --info
You will see information of currently installed version of .NET Command Line Tools on your system as shown below.
You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1.
dotnet help new
The command helps you download packages as well to the package cache.
The command opens the following webpage which contains information about the new command in .NET Core 2 preview1.
Let us scroll down, you can now see that we can create the .NET Core application with more templates.
We can now create mstest, web, mvc and webapi projects as well using the command line.
The .NET Core has decided to drop project.json and go back to MSBuild and *.csproj. This is something thatβs already happened in the just released .Net Core 2.0 preview1 tooling. This is fairly disappointing, because the project.json was a breath of fresh air. However, it is understandable and have many advantages as well.
Let us now discuss the advantages that the change brings in β
It would make the transition of the existing Visual Studio solutions to .NET Core straightforward.
It would make the transition of the existing Visual Studio solutions to .NET Core straightforward.
It is a huge change and it will also enable leveraging existing investment in CI/RM based around MSBuild.
It is a huge change and it will also enable leveraging existing investment in CI/RM based around MSBuild.
During build in MSBuild, we can think of incremental compilation, resolving buildtime dependencies, configuration management, etc.
During build in MSBuild, we can think of incremental compilation, resolving buildtime dependencies, configuration management, etc.
A lot of work is required to ship dotnet cli on time, because it is no longer just about ASP.NET Core, but also console apps, UWP apps, etc.
A lot of work is required to ship dotnet cli on time, because it is no longer just about ASP.NET Core, but also console apps, UWP apps, etc.
Following are the changes in MSBuild and *.csproj β
Project.json file (*.xproj) will be replaced by MSBuild (*.csproj).
Project.json file (*.xproj) will be replaced by MSBuild (*.csproj).
Features in project.json will start getting merged back into the the *.csproj.
Features in project.json will start getting merged back into the the *.csproj.
It is not yet clear what they are going to do about the packages list, but it was mentioned they might keep it as json under nuget.json or merge it into the *.csproj.
It is not yet clear what they are going to do about the packages list, but it was mentioned they might keep it as json under nuget.json or merge it into the *.csproj.
Supposedly that transition should be smooth and potentially automatic if using Visual Studio.
Supposedly that transition should be smooth and potentially automatic if using Visual Studio.
MSBuild is open source and available on GitHub and is bound to become fully crossplatform.
MSBuild is open source and available on GitHub and is bound to become fully crossplatform.
MSBuild will dramatically simplify and trim the structure of the *.csproj.
MSBuild will dramatically simplify and trim the structure of the *.csproj.
Microsoft is also introducing a new project system which will enable a lot of scenarios without the need for Visual Studio and the details are given on the this Url https://github.com/dotnet/roslyn-project-system/.
Microsoft is also introducing a new project system which will enable a lot of scenarios without the need for Visual Studio and the details are given on the this Url https://github.com/dotnet/roslyn-project-system/.
The goal is that even with the MSBuild setup, working with builds and project will be as seamless in Visual Studio IDE as outside of it.
The goal is that even with the MSBuild setup, working with builds and project will be as seamless in Visual Studio IDE as outside of it.
Let us now create a new console project with .NET Core preview2 tooling by executing the following command.
dotnet new -t console
To see all the files created within this project, run the dir command.
You can see that two files are created, Program.cs and project.json file.
Let us now create a console app with .NET Core 2 preview1 tooling by executing the following command.
dotnet new console
To see all the files created within this project, run the dir command. You can see that three files are created, Program.cs, NuGet.config and MSBuild.csproj instead of the project.json file.
Let us now compare project.json and MSBuild.csproj files side by side.
To the left, we have the file in json format while on the right, the file is in XML format. You can see that in the project.json file, inside the dependencies section, there is netcoreapp1.0, while in MSBuild.csproj file, you will see the netcoreapp2.0.
In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command.
dotnet help
You will see all the commands like new, restore, build, etc.
Following is the default implementation in Program.cs file.
using System;
namespace MSBuild {
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello World!");
}
}
}
Let us now execute the following command to see the progress.
dotnet build
You will see a lot of errors. These errors need to be rectified.
Let us now run the following command.
dotnet restore
You can see that all the packages are restored. Some new folders and files have also been generated.
To see the directory structure, let us run the following command.
tree /f
Following is the directory structure β
Let us now rebuild the project running the following command again.
dotnet build
Now you project will build successfully without any error(s) and MSBuild.dll is also created.
To see the output, let us run the following command β
dotnet run
You can see the following output on your console.
In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (*.csproj). So, we have an old project which contains the following files.
Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error.
This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command.
dotnet help
In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project.
Let us now run the following command.
dotnet migrate
You will see a summary of the migration process and here you can also see that a project is migrated successfully.
Let us now see the directory structure by using the following command.
tree /f
You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder.
Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command.
dotnet restore
You can now see that all the packages are restored.
You can now build your project with the following command.
dotnet build
You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\bin\Debug\netcoreapp1.0 folder.
The following screenshot shows the directory structure and files.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2755,
"s": 2386,
"text": ".NET Core is the latest general purpose development platform maintained by Microsoft. It works across different platforms and has been redesigned in a way that makes .NET fast, flexible and modern. This happens to be one of the major contributions by Microsoft. Developers can now build Android, iOS, Linux, Mac, and Windows applications with .NET, all in Open Source."
},
{
"code": null,
"e": 2921,
"s": 2755,
"text": "In this tutorial, we will cover .NET Core and a few new innovations including the .NET Framework updates, .NET Standard, and Universal Windows Platform updates, etc."
},
{
"code": null,
"e": 2980,
"s": 2921,
"text": "The following are the major characteristics of .NET Core β"
},
{
"code": null,
"e": 3057,
"s": 2980,
"text": ".NET Core is an open source implementation, using MIT and Apache 2 licenses."
},
{
"code": null,
"e": 3134,
"s": 3057,
"text": ".NET Core is an open source implementation, using MIT and Apache 2 licenses."
},
{
"code": null,
"e": 3201,
"s": 3134,
"text": ".NET Core is a .NET Foundation project and is available on GitHub."
},
{
"code": null,
"e": 3268,
"s": 3201,
"text": ".NET Core is a .NET Foundation project and is available on GitHub."
},
{
"code": null,
"e": 3392,
"s": 3268,
"text": "As an open source project, it promotes a more transparent development process and promotes an active and engaged community."
},
{
"code": null,
"e": 3516,
"s": 3392,
"text": "As an open source project, it promotes a more transparent development process and promotes an active and engaged community."
},
{
"code": null,
"e": 3627,
"s": 3516,
"text": "Application implemented in .NET Core can be run and its code can be reused regardless of your platform target."
},
{
"code": null,
"e": 3738,
"s": 3627,
"text": "Application implemented in .NET Core can be run and its code can be reused regardless of your platform target."
},
{
"code": null,
"e": 3817,
"s": 3738,
"text": "It currently supports three main operating systems (OS)\n\nWindows\nLinux\nMacOS\n\n"
},
{
"code": null,
"e": 3873,
"s": 3817,
"text": "It currently supports three main operating systems (OS)"
},
{
"code": null,
"e": 3881,
"s": 3873,
"text": "Windows"
},
{
"code": null,
"e": 3889,
"s": 3881,
"text": "Windows"
},
{
"code": null,
"e": 3895,
"s": 3889,
"text": "Linux"
},
{
"code": null,
"e": 3901,
"s": 3895,
"text": "Linux"
},
{
"code": null,
"e": 3907,
"s": 3901,
"text": "MacOS"
},
{
"code": null,
"e": 3913,
"s": 3907,
"text": "MacOS"
},
{
"code": null,
"e": 4060,
"s": 3913,
"text": "The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals."
},
{
"code": null,
"e": 4207,
"s": 4060,
"text": "The supported Operating Systems (OS), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals."
},
{
"code": null,
"e": 4334,
"s": 4207,
"text": "There can be two types of deployments for .NET Core applications β\n\nFramework-dependent deployment\nSelf-contained deployment\n\n"
},
{
"code": null,
"e": 4401,
"s": 4334,
"text": "There can be two types of deployments for .NET Core applications β"
},
{
"code": null,
"e": 4432,
"s": 4401,
"text": "Framework-dependent deployment"
},
{
"code": null,
"e": 4463,
"s": 4432,
"text": "Framework-dependent deployment"
},
{
"code": null,
"e": 4489,
"s": 4463,
"text": "Self-contained deployment"
},
{
"code": null,
"e": 4515,
"s": 4489,
"text": "Self-contained deployment"
},
{
"code": null,
"e": 4669,
"s": 4515,
"text": "With framework-dependent deployment, your app depends on a system-wide version of .NET Core on which your app and third-party dependencies are installed."
},
{
"code": null,
"e": 4823,
"s": 4669,
"text": "With framework-dependent deployment, your app depends on a system-wide version of .NET Core on which your app and third-party dependencies are installed."
},
{
"code": null,
"e": 5020,
"s": 4823,
"text": "With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions."
},
{
"code": null,
"e": 5217,
"s": 5020,
"text": "With self-contained deployment, the .NET Core version used to build your application is also deployed along with your app and third-party dependencies and can run side-by-side with other versions."
},
{
"code": null,
"e": 5277,
"s": 5217,
"text": "All product scenarios can be exercised at the command-line."
},
{
"code": null,
"e": 5337,
"s": 5277,
"text": "All product scenarios can be exercised at the command-line."
},
{
"code": null,
"e": 5430,
"s": 5337,
"text": ".NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library"
},
{
"code": null,
"e": 5523,
"s": 5430,
"text": ".NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library"
},
{
"code": null,
"e": 5589,
"s": 5523,
"text": ".NET Core is released through NuGet in smaller assembly packages."
},
{
"code": null,
"e": 5655,
"s": 5589,
"text": ".NET Core is released through NuGet in smaller assembly packages."
},
{
"code": null,
"e": 5740,
"s": 5655,
"text": ".NET Framework is one large assembly that contains most of the core functionalities."
},
{
"code": null,
"e": 5825,
"s": 5740,
"text": ".NET Framework is one large assembly that contains most of the core functionalities."
},
{
"code": null,
"e": 5890,
"s": 5825,
"text": ".NET Core is made available as smaller feature-centric packages."
},
{
"code": null,
"e": 5955,
"s": 5890,
"text": ".NET Core is made available as smaller feature-centric packages."
},
{
"code": null,
"e": 6091,
"s": 5955,
"text": "This modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app."
},
{
"code": null,
"e": 6227,
"s": 6091,
"text": "This modular approach enables the developers to optimize their app by including just those NuGet packages which they need in their app."
},
{
"code": null,
"e": 6390,
"s": 6227,
"text": "The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model."
},
{
"code": null,
"e": 6553,
"s": 6390,
"text": "The benefits of a smaller app surface area include tighter security, reduced servicing, improved performance, and decreased costs in a pay-for-what-you-use model."
},
{
"code": null,
"e": 6608,
"s": 6553,
"text": ".NET Core Platform contains the following main parts β"
},
{
"code": null,
"e": 6730,
"s": 6608,
"text": ".NET Runtime β It provides a type system, assembly loading, a garbage collector, native interop and other basic services."
},
{
"code": null,
"e": 6852,
"s": 6730,
"text": ".NET Runtime β It provides a type system, assembly loading, a garbage collector, native interop and other basic services."
},
{
"code": null,
"e": 6991,
"s": 6852,
"text": "Fundamental Libraries β A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities."
},
{
"code": null,
"e": 7130,
"s": 6991,
"text": "Fundamental Libraries β A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities."
},
{
"code": null,
"e": 7264,
"s": 7130,
"text": "SDK & Compiler β A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK."
},
{
"code": null,
"e": 7398,
"s": 7264,
"text": "SDK & Compiler β A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK."
},
{
"code": null,
"e": 7628,
"s": 7398,
"text": "βdotnetβ app host β It is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way."
},
{
"code": null,
"e": 7858,
"s": 7628,
"text": "βdotnetβ app host β It is used to launch .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way."
},
{
"code": null,
"e": 8050,
"s": 7858,
"text": "In this chapter, we will discuss the various dependencies that you need to deploy and run. These include the .NET Core applications on Windows machines that are developed using Visual Studio."
},
{
"code": null,
"e": 8112,
"s": 8050,
"text": ".NET Core is supported on the following versions of Windows β"
},
{
"code": null,
"e": 8126,
"s": 8112,
"text": "Windows 7 SP1"
},
{
"code": null,
"e": 8138,
"s": 8126,
"text": "Windows 8.1"
},
{
"code": null,
"e": 8149,
"s": 8138,
"text": "Windows 10"
},
{
"code": null,
"e": 8205,
"s": 8149,
"text": "Windows Server 2008 R2 SP1 (Full Server or Server Core)"
},
{
"code": null,
"e": 8258,
"s": 8205,
"text": "Windows Server 2012 SP1 (Full Server or Server Core)"
},
{
"code": null,
"e": 8314,
"s": 8258,
"text": "Windows Server 2012 R2 SP1 (Full Server or Server Core)"
},
{
"code": null,
"e": 8376,
"s": 8314,
"text": "Windows Server 2016 (Full Server, Server Core or Nano Server)"
},
{
"code": null,
"e": 8549,
"s": 8376,
"text": "If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable."
},
{
"code": null,
"e": 8722,
"s": 8549,
"text": "If you are running your .NET Core application on Windows versions earlier than Windows 10 and Windows Server 2016, then it will also require the Visual C++ Redistributable."
},
{
"code": null,
"e": 8809,
"s": 8722,
"text": "This dependency is automatically installed for you if you use the .NET Core installer."
},
{
"code": null,
"e": 8896,
"s": 8809,
"text": "This dependency is automatically installed for you if you use the .NET Core installer."
},
{
"code": null,
"e": 9089,
"s": 8896,
"text": "You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application."
},
{
"code": null,
"e": 9282,
"s": 9089,
"text": "You need to manually install the Visual C++ Redistributable for Visual Studio 2015 if you are installing .NET Core via the installer script or deploying a self-contained .NET Core application."
},
{
"code": null,
"e": 9466,
"s": 9282,
"text": "For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update."
},
{
"code": null,
"e": 9650,
"s": 9466,
"text": "For Windows 7 and Windows Server 2008 machines, you need to make sure that your Windows installation is up-to-date and also includes hotfix KB2533623 installed through Windows Update."
},
{
"code": null,
"e": 9748,
"s": 9650,
"text": "To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice."
},
{
"code": null,
"e": 9846,
"s": 9748,
"text": "To develop .NET Core applications using the .NET Core SDK, you can use any editor of your choice."
},
{
"code": null,
"e": 10018,
"s": 9846,
"text": "However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions β\n\nVisual Studio 2015\nVisual Studio 2017 RC\n\n"
},
{
"code": null,
"e": 10146,
"s": 10018,
"text": "However, if you want to develop .NET Core applications on Windows using Visual Studio, you can use the following two versions β"
},
{
"code": null,
"e": 10165,
"s": 10146,
"text": "Visual Studio 2015"
},
{
"code": null,
"e": 10184,
"s": 10165,
"text": "Visual Studio 2015"
},
{
"code": null,
"e": 10206,
"s": 10184,
"text": "Visual Studio 2017 RC"
},
{
"code": null,
"e": 10228,
"s": 10206,
"text": "Visual Studio 2017 RC"
},
{
"code": null,
"e": 10387,
"s": 10228,
"text": "Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based."
},
{
"code": null,
"e": 10546,
"s": 10387,
"text": "Projects created with Visual Studio 2015 will be project.json-based by default while projects created with Visual Studio 2017 RC will always be MSBuild-based."
},
{
"code": null,
"e": 10742,
"s": 10546,
"text": "In this chapter, we will discuss the Environment Setup of .NET Core. It is a significant redesign of the .NET Framework. To use .NET Core in your application, there are two versions you can use β"
},
{
"code": null,
"e": 10761,
"s": 10742,
"text": "Visual Studio 2015"
},
{
"code": null,
"e": 10783,
"s": 10761,
"text": "Visual Studio 2017 RC"
},
{
"code": null,
"e": 10850,
"s": 10783,
"text": "To use Visual Studio 2015, you must have installed the following β"
},
{
"code": null,
"e": 10888,
"s": 10850,
"text": "Microsoft Visual Studio 2015 Update 3"
},
{
"code": null,
"e": 10942,
"s": 10888,
"text": "Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2"
},
{
"code": null,
"e": 11252,
"s": 10942,
"text": "Microsoft provides a free version of visual studio which also contains the SQL Server and can be downloaded from https://www.visualstudio.com/en-us/downloads/download-visual-studio-vs.aspx and Microsoft .NET Core 1.0.1 - VS 2015 Tooling Preview 2 can be downloaded from https://www.visualstudio.com/downloads/"
},
{
"code": null,
"e": 11371,
"s": 11252,
"text": "You can also follow the installation guidelines on the following Url https://www.microsoft.com/net/core/#windowsvs2017"
},
{
"code": null,
"e": 11422,
"s": 11371,
"text": "Follow these steps to install Visual Studio 2015 β"
},
{
"code": null,
"e": 11531,
"s": 11422,
"text": "Step 1 β Once the downloading completes, then run the installer. The following dialog box will be displayed."
},
{
"code": null,
"e": 11589,
"s": 11531,
"text": "Step 2 β Click Install to start the installation process."
},
{
"code": null,
"e": 11670,
"s": 11589,
"text": "Step 3 β Once the installation completes, you will see the following dialog box."
},
{
"code": null,
"e": 11736,
"s": 11670,
"text": "Step 4 β Close this dialog and restart your computer if required."
},
{
"code": null,
"e": 11902,
"s": 11736,
"text": "Step 5 β Open Visual Studio from the Start Menu; you will receive the following dialog box. It may take a few minutes to load and finally be used for the first time."
},
{
"code": null,
"e": 11965,
"s": 11902,
"text": "Step 6 β Once it is loaded, you will see the following screen."
},
{
"code": null,
"e": 12104,
"s": 11965,
"text": "Step 7 β Once Visual Studio installation is finished, then close Visual Studio and launch Microsoft .NET Core - VS 2015 Tooling Preview 2."
},
{
"code": null,
"e": 12151,
"s": 12104,
"text": "Step 8 β Check the checkbox and click Install."
},
{
"code": null,
"e": 12232,
"s": 12151,
"text": "Step 9 β Once the installation completes, you will see the following dialog box."
},
{
"code": null,
"e": 12293,
"s": 12232,
"text": "You are now ready to start your application using .NET Core."
},
{
"code": null,
"e": 12588,
"s": 12293,
"text": "In this tutorial, we will be using Visual Studio 2015, but if you want to use Visual Studio 2017, an experimental release of .NET Core tools for Visual Studio is included in Visual Studio 2017 RC and you can see the installation guidelines here https://www.microsoft.com/net/core/#windowsvs2017"
},
{
"code": null,
"e": 12876,
"s": 12588,
"text": "Visual Studio 2015 provides a full-featured development environment for developing .NET Core applications. In this chapter, we will be creating a new project inside Visual Studio. Once you have installed the Visual Studio 2015 tooling, you can start building a new .NET Core Application."
},
{
"code": null,
"e": 13038,
"s": 12876,
"text": "In the New Project dialog box, in the Templates list, expand the Visual C# node and select .NET Core and you should see the following three new project templates"
},
{
"code": null,
"e": 13064,
"s": 13038,
"text": "Class Library (.NET Core)"
},
{
"code": null,
"e": 13096,
"s": 13064,
"text": "Console Application (.NET Core)"
},
{
"code": null,
"e": 13137,
"s": 13096,
"text": "ASP.NET Core Web Application (.NET Core)"
},
{
"code": null,
"e": 13265,
"s": 13137,
"text": "In the middle pane on the New Project dialog box, select Console Application (.NET Core) and name it \"FirstApp\", then click OK."
},
{
"code": null,
"e": 13408,
"s": 13265,
"text": "Visual Studio will open the newly created project, and you will see in the Solution Explorer window all of the files that are in this project."
},
{
"code": null,
"e": 13494,
"s": 13408,
"text": "To test that .NET core console application is working, let us add the following line."
},
{
"code": null,
"e": 13784,
"s": 13494,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace FirstApp { \n public class Program { \n public static void Main(string[] args) { \n Console.WriteLine(\"Hello guys, welcome to .NET Core world!\"); \n } \n } \n}"
},
{
"code": null,
"e": 13847,
"s": 13784,
"text": "Now, run the application. You should see the following output."
},
{
"code": null,
"e": 13966,
"s": 13847,
"text": ".NET Core supports the standard numeric integral and floating-point primitives. It also supports the following types β"
},
{
"code": null,
"e": 14049,
"s": 13966,
"text": "System.Numerics.BigInteger which is an integral type with no upper or lower bound."
},
{
"code": null,
"e": 14132,
"s": 14049,
"text": "System.Numerics.BigInteger which is an integral type with no upper or lower bound."
},
{
"code": null,
"e": 14199,
"s": 14132,
"text": "System.Numerics.Complex is a type that represents complex numbers."
},
{
"code": null,
"e": 14266,
"s": 14199,
"text": "System.Numerics.Complex is a type that represents complex numbers."
},
{
"code": null,
"e": 14370,
"s": 14266,
"text": "A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace."
},
{
"code": null,
"e": 14474,
"s": 14370,
"text": "A set of Single Instruction Multiple Data (SIMD)-enabled vector types in the System.Numerics namespace."
},
{
"code": null,
"e": 14617,
"s": 14474,
"text": ".NET Core supports both signed and unsigned integers of different ranges from one byte to eight bytes in length. All integers are value types."
},
{
"code": null,
"e": 14683,
"s": 14617,
"text": "The following table represents the integral types and their size;"
},
{
"code": null,
"e": 14819,
"s": 14683,
"text": "Each integral type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators."
},
{
"code": null,
"e": 14922,
"s": 14819,
"text": "You can also work with the individual bits in an integer value by using the System.BitConverter class."
},
{
"code": null,
"e": 15019,
"s": 14922,
"text": ".NET Core includes three primitive floating point types, which are shown in the following table."
},
{
"code": null,
"e": 15161,
"s": 15019,
"text": "Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators."
},
{
"code": null,
"e": 15303,
"s": 15161,
"text": "Each floating-point type supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators."
},
{
"code": null,
"e": 15407,
"s": 15303,
"text": "You can also work with the individual bits in Double and Single values by using the BitConverter class."
},
{
"code": null,
"e": 15511,
"s": 15407,
"text": "You can also work with the individual bits in Double and Single values by using the BitConverter class."
},
{
"code": null,
"e": 15742,
"s": 15511,
"text": "The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value's individual bits, as well as its own set of methods for performing some additional mathematical operations."
},
{
"code": null,
"e": 15973,
"s": 15742,
"text": "The Decimal structure has its own methods, Decimal.GetBits and Decimal.Decimal(Int32()), for working with a decimal value's individual bits, as well as its own set of methods for performing some additional mathematical operations."
},
{
"code": null,
"e": 16118,
"s": 15973,
"text": "System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds."
},
{
"code": null,
"e": 16263,
"s": 16118,
"text": "System.Numerics.BigInteger is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds."
},
{
"code": null,
"e": 16356,
"s": 16263,
"text": "The methods of the BigInteger type is closely parallel to those of the other integral types."
},
{
"code": null,
"e": 16449,
"s": 16356,
"text": "The methods of the BigInteger type is closely parallel to those of the other integral types."
},
{
"code": null,
"e": 16579,
"s": 16449,
"text": "The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part"
},
{
"code": null,
"e": 16709,
"s": 16579,
"text": "The System.Numerics.Complex type represents a complex number, i.e., a number with a real number part and an imaginary number part"
},
{
"code": null,
"e": 16892,
"s": 16709,
"text": "It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods."
},
{
"code": null,
"e": 17075,
"s": 16892,
"text": "It supports a standard set of arithmetic, comparison, equality, explicit conversion, and implicit conversion operators, as well as mathematical, algebraic, and trigonometric methods."
},
{
"code": null,
"e": 17157,
"s": 17075,
"text": "The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core."
},
{
"code": null,
"e": 17239,
"s": 17157,
"text": "The Numerics namespace includes a set of SIMD-enabled vector types for .NET Core."
},
{
"code": null,
"e": 17443,
"s": 17239,
"text": "SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors."
},
{
"code": null,
"e": 17647,
"s": 17443,
"text": "SIMD allows some operations to be parallelized at the hardware level, which results in huge performance improvements in mathematical, scientific, and graphics apps that perform computations over vectors."
},
{
"code": null,
"e": 18391,
"s": 17647,
"text": "The SIMD-enabled vector types in .NET Core include the following β\n\nSystem.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single.\nThe Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal.\nTwo matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix.\nThe System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations.\n\n"
},
{
"code": null,
"e": 18458,
"s": 18391,
"text": "The SIMD-enabled vector types in .NET Core include the following β"
},
{
"code": null,
"e": 18601,
"s": 18458,
"text": "System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single."
},
{
"code": null,
"e": 18744,
"s": 18601,
"text": "System.Numerics.Vector2, System.Numerics.Vector3, and System.Numerics.Vector4 types, which are 2, 3, and 4-dimensional vectors of type Single."
},
{
"code": null,
"e": 18933,
"s": 18744,
"text": "The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal."
},
{
"code": null,
"e": 19122,
"s": 18933,
"text": "The Vector <T> structure that allows you to create a vector of any primitive numeric type. The primitive numeric types include all numeric types in the System namespace except for Decimal."
},
{
"code": null,
"e": 19260,
"s": 19122,
"text": "Two matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix."
},
{
"code": null,
"e": 19398,
"s": 19260,
"text": "Two matrix types, System.Numerics.Matrix3Γ2, which represents a 3Γ2 matrix; and System.Numerics.Matrix4Γ4, which represents a 4Γ4 matrix."
},
{
"code": null,
"e": 19602,
"s": 19398,
"text": "The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations."
},
{
"code": null,
"e": 19806,
"s": 19602,
"text": "The System.Numerics.Plane type, which represents a three-dimensional plane, and the System.Numerics.Quaternion type, which represents a vector that is used to encode three-dimensional physical rotations."
},
{
"code": null,
"e": 20080,
"s": 19806,
"text": "In this chapter, we will cover the concept of Garbage collection which is one of most important features of the .NET managed code platform. The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager."
},
{
"code": null,
"e": 20198,
"s": 20080,
"text": "You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory"
},
{
"code": null,
"e": 20316,
"s": 20198,
"text": "You do not need to know how to allocate and release memory or manage the lifetime of the objects that use that memory"
},
{
"code": null,
"e": 20452,
"s": 20316,
"text": "An allocation is made any time you declare an object with a βnewβ keyword or a value type is boxed. Allocations are typically very fast"
},
{
"code": null,
"e": 20588,
"s": 20452,
"text": "An allocation is made any time you declare an object with a βnewβ keyword or a value type is boxed. Allocations are typically very fast"
},
{
"code": null,
"e": 20738,
"s": 20588,
"text": "When there isnβt enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations."
},
{
"code": null,
"e": 20888,
"s": 20738,
"text": "When there isnβt enough memory to allocate an object, the GC must collect and dispose of garbage memory to make memory available for new allocations."
},
{
"code": null,
"e": 20933,
"s": 20888,
"text": "This process is known as garbage collection."
},
{
"code": null,
"e": 20978,
"s": 20933,
"text": "This process is known as garbage collection."
},
{
"code": null,
"e": 21031,
"s": 20978,
"text": "Garbage Collection provides the following benefits β"
},
{
"code": null,
"e": 21105,
"s": 21031,
"text": "You donβt need to free memory manually while developing your application."
},
{
"code": null,
"e": 21179,
"s": 21105,
"text": "You donβt need to free memory manually while developing your application."
},
{
"code": null,
"e": 21238,
"s": 21179,
"text": "It also allocates objects on the managed heap efficiently."
},
{
"code": null,
"e": 21297,
"s": 21238,
"text": "It also allocates objects on the managed heap efficiently."
},
{
"code": null,
"e": 21445,
"s": 21297,
"text": "When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations."
},
{
"code": null,
"e": 21593,
"s": 21445,
"text": "When objects are no longer used then it will reclaim those objects by clearing their memory, and keeps the memory available for future allocations."
},
{
"code": null,
"e": 21722,
"s": 21593,
"text": "Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field."
},
{
"code": null,
"e": 21851,
"s": 21722,
"text": "Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field."
},
{
"code": null,
"e": 21954,
"s": 21851,
"text": "It also provides memory safety by making sure that an object cannot use the content of another object."
},
{
"code": null,
"e": 22057,
"s": 21954,
"text": "It also provides memory safety by making sure that an object cannot use the content of another object."
},
{
"code": null,
"e": 22129,
"s": 22057,
"text": "Garbage collection occurs when one of the following conditions is true."
},
{
"code": null,
"e": 22165,
"s": 22129,
"text": "The system has low physical memory."
},
{
"code": null,
"e": 22201,
"s": 22165,
"text": "The system has low physical memory."
},
{
"code": null,
"e": 22362,
"s": 22201,
"text": "The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs."
},
{
"code": null,
"e": 22523,
"s": 22362,
"text": "The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This threshold is continuously adjusted as the process runs."
},
{
"code": null,
"e": 22731,
"s": 22523,
"text": "The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing."
},
{
"code": null,
"e": 22939,
"s": 22731,
"text": "The GC.Collect method is called and in almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing."
},
{
"code": null,
"e": 23160,
"s": 22939,
"text": "The .NET Garbage Collector has 3 generations and each generation has its own heap that that is used for the storage of allocated objects. There is a basic principle that most objects are either short-lived or long-lived."
},
{
"code": null,
"e": 23206,
"s": 23160,
"text": "In Generation 0, objects are first allocated."
},
{
"code": null,
"e": 23252,
"s": 23206,
"text": "In Generation 0, objects are first allocated."
},
{
"code": null,
"e": 23419,
"s": 23252,
"text": "In this generation, objects often donβt live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs."
},
{
"code": null,
"e": 23586,
"s": 23419,
"text": "In this generation, objects often donβt live past the first generation, since they are no longer in use (out of scope) by the time the next garbage collection occurs."
},
{
"code": null,
"e": 23657,
"s": 23586,
"text": "Generation 0 is quick to collect because its associated heap is small."
},
{
"code": null,
"e": 23728,
"s": 23657,
"text": "Generation 0 is quick to collect because its associated heap is small."
},
{
"code": null,
"e": 23781,
"s": 23728,
"text": "In Generation 1, objects have a second chance space."
},
{
"code": null,
"e": 23834,
"s": 23781,
"text": "In Generation 1, objects have a second chance space."
},
{
"code": null,
"e": 23960,
"s": 23834,
"text": "Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1."
},
{
"code": null,
"e": 24086,
"s": 23960,
"text": "Objects that are short-lived but survive the generation 0 collection (often based on coincidental timing) go to generation 1."
},
{
"code": null,
"e": 24169,
"s": 24086,
"text": "Generation 1 collections are also quick because its associated heap is also small."
},
{
"code": null,
"e": 24252,
"s": 24169,
"text": "Generation 1 collections are also quick because its associated heap is also small."
},
{
"code": null,
"e": 24363,
"s": 24252,
"text": "The first two heaps remain small because objects are either collected or promoted to the next generation heap."
},
{
"code": null,
"e": 24474,
"s": 24363,
"text": "The first two heaps remain small because objects are either collected or promoted to the next generation heap."
},
{
"code": null,
"e": 24558,
"s": 24474,
"text": "In Generation 2, all long objects are lived and its heap can grow to be very large."
},
{
"code": null,
"e": 24642,
"s": 24558,
"text": "In Generation 2, all long objects are lived and its heap can grow to be very large."
},
{
"code": null,
"e": 24762,
"s": 24642,
"text": "The objects in this generation can survive a long time and there is no next generation heap to further promote objects."
},
{
"code": null,
"e": 24882,
"s": 24762,
"text": "The objects in this generation can survive a long time and there is no next generation heap to further promote objects."
},
{
"code": null,
"e": 24979,
"s": 24882,
"text": "The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH)."
},
{
"code": null,
"e": 25076,
"s": 24979,
"text": "The Garbage Collector has an additional heap for large objects known as Large Object Heap (LOH)."
},
{
"code": null,
"e": 25137,
"s": 25076,
"text": "It is reserved for objects that are 85,000 bytes or greater."
},
{
"code": null,
"e": 25198,
"s": 25137,
"text": "It is reserved for objects that are 85,000 bytes or greater."
},
{
"code": null,
"e": 25294,
"s": 25198,
"text": "Large objects are not allocated to the generational heaps but are allocated directly to the LOH"
},
{
"code": null,
"e": 25390,
"s": 25294,
"text": "Large objects are not allocated to the generational heaps but are allocated directly to the LOH"
},
{
"code": null,
"e": 25530,
"s": 25390,
"text": "Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data."
},
{
"code": null,
"e": 25670,
"s": 25530,
"text": "Generation 2 and LOH collections can take noticeable time for programs that have run for a long time or operate over large amounts of data."
},
{
"code": null,
"e": 25735,
"s": 25670,
"text": "Large server programs are known to have heaps in the 10s of GBs."
},
{
"code": null,
"e": 25800,
"s": 25735,
"text": "Large server programs are known to have heaps in the 10s of GBs."
},
{
"code": null,
"e": 25902,
"s": 25800,
"text": "The GC employs a variety of techniques to reduce the amount of time that it blocks program execution."
},
{
"code": null,
"e": 26004,
"s": 25902,
"text": "The GC employs a variety of techniques to reduce the amount of time that it blocks program execution."
},
{
"code": null,
"e": 26158,
"s": 26004,
"text": "The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution."
},
{
"code": null,
"e": 26312,
"s": 26158,
"text": "The primary approach is to do as much garbage collection work as possible on a background thread in a way that does not interfere with program execution."
},
{
"code": null,
"e": 26435,
"s": 26312,
"text": "The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance."
},
{
"code": null,
"e": 26558,
"s": 26435,
"text": "The GC also exposes a few ways for developers to influence its behavior, which can be quite useful to improve performance."
},
{
"code": null,
"e": 26729,
"s": 26558,
"text": "In this chapter, we will understand the execution process of .NET Core and compare it with the .NET Framework. The managed execution process includes the following steps."
},
{
"code": null,
"e": 26749,
"s": 26729,
"text": "Choosing a compiler"
},
{
"code": null,
"e": 26777,
"s": 26749,
"text": "Compiling your code to MSIL"
},
{
"code": null,
"e": 26807,
"s": 26777,
"text": "Compiling MSIL to native code"
},
{
"code": null,
"e": 26820,
"s": 26807,
"text": "Running code"
},
{
"code": null,
"e": 26939,
"s": 26820,
"text": "It is a multi-language execution environment, the runtime supports a wide variety of data types and language features."
},
{
"code": null,
"e": 27058,
"s": 26939,
"text": "It is a multi-language execution environment, the runtime supports a wide variety of data types and language features."
},
{
"code": null,
"e": 27191,
"s": 27058,
"text": "To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime."
},
{
"code": null,
"e": 27324,
"s": 27191,
"text": "To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime."
},
{
"code": null,
"e": 27443,
"s": 27324,
"text": "Compiling translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata."
},
{
"code": null,
"e": 27562,
"s": 27443,
"text": "Compiling translates your source code into Microsoft Intermediate Language (MSIL) and generates the required metadata."
},
{
"code": null,
"e": 27778,
"s": 27562,
"text": "Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time."
},
{
"code": null,
"e": 27994,
"s": 27778,
"text": "Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time."
},
{
"code": null,
"e": 28130,
"s": 27994,
"text": "The runtime locates and extracts the metadata from the file as well as from framework class libraries (FCL) as needed during execution."
},
{
"code": null,
"e": 28266,
"s": 28130,
"text": "The runtime locates and extracts the metadata from the file as well as from framework class libraries (FCL) as needed during execution."
},
{
"code": null,
"e": 28353,
"s": 28266,
"text": "At execution time, a just-in-time (JIT) compiler translates the MSIL into native code."
},
{
"code": null,
"e": 28440,
"s": 28353,
"text": "At execution time, a just-in-time (JIT) compiler translates the MSIL into native code."
},
{
"code": null,
"e": 28603,
"s": 28440,
"text": "During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe."
},
{
"code": null,
"e": 28766,
"s": 28603,
"text": "During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe."
},
{
"code": null,
"e": 28911,
"s": 28766,
"text": "The common language runtime provides the infrastructure that enables the execution to take place and services that can be used during execution."
},
{
"code": null,
"e": 29056,
"s": 28911,
"text": "The common language runtime provides the infrastructure that enables the execution to take place and services that can be used during execution."
},
{
"code": null,
"e": 29263,
"s": 29056,
"text": "During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support."
},
{
"code": null,
"e": 29470,
"s": 29263,
"text": "During execution, managed code receives services such as garbage collection, security, interoperability with unmanaged code, cross-language debugging support, and enhanced deployment and versioning support."
},
{
"code": null,
"e": 29653,
"s": 29470,
"text": "Now letβs relate how code executes with .NET Core as compared to .NET Framework. In .NET Core there are many replacements of these components that are the part of the .NET Framework."
},
{
"code": null,
"e": 29740,
"s": 29653,
"text": "In .NET Core now we have a new series of compilers, like we have Roslyn for C# and VB."
},
{
"code": null,
"e": 29827,
"s": 29740,
"text": "In .NET Core now we have a new series of compilers, like we have Roslyn for C# and VB."
},
{
"code": null,
"e": 29914,
"s": 29827,
"text": "You can also make use of the new F# 4.1 compiler if you want to use F# with .NET Core."
},
{
"code": null,
"e": 30001,
"s": 29914,
"text": "You can also make use of the new F# 4.1 compiler if you want to use F# with .NET Core."
},
{
"code": null,
"e": 30166,
"s": 30001,
"text": "Actually these tools are different and we can use Roslyn with .NET Framework as well if we are using C# 6 or later, because C# compiler can only support up to C# 5."
},
{
"code": null,
"e": 30331,
"s": 30166,
"text": "Actually these tools are different and we can use Roslyn with .NET Framework as well if we are using C# 6 or later, because C# compiler can only support up to C# 5."
},
{
"code": null,
"e": 30459,
"s": 30331,
"text": "In .NET Core, we donβt have a framework class libraries (FCL), so a different set of libraries are used and we now have CoreFx."
},
{
"code": null,
"e": 30587,
"s": 30459,
"text": "In .NET Core, we donβt have a framework class libraries (FCL), so a different set of libraries are used and we now have CoreFx."
},
{
"code": null,
"e": 30656,
"s": 30587,
"text": "CoreFx is the reimplementation of the class libraries for .NET Core."
},
{
"code": null,
"e": 30725,
"s": 30656,
"text": "CoreFx is the reimplementation of the class libraries for .NET Core."
},
{
"code": null,
"e": 30815,
"s": 30725,
"text": "We also have a new run time with .NET Core known as CoreCLR and leverages a JIT Compiler."
},
{
"code": null,
"e": 30905,
"s": 30815,
"text": "We also have a new run time with .NET Core known as CoreCLR and leverages a JIT Compiler."
},
{
"code": null,
"e": 31025,
"s": 30905,
"text": "Now the question is why do we have the reimplementation of all these components that we already have in .NET framework."
},
{
"code": null,
"e": 31145,
"s": 31025,
"text": "Now the question is why do we have the reimplementation of all these components that we already have in .NET framework."
},
{
"code": null,
"e": 31211,
"s": 31145,
"text": "So the answer is the same as why Microsoft implemented .NET Core."
},
{
"code": null,
"e": 31277,
"s": 31211,
"text": "So the answer is the same as why Microsoft implemented .NET Core."
},
{
"code": null,
"e": 31530,
"s": 31277,
"text": "It is another consideration of .NET Core to build and implement application that is modular. Instead of installing the entire .NET Framework, your application can now just install what is required. Let us go to the visual studio and see the modularity."
},
{
"code": null,
"e": 31661,
"s": 31530,
"text": "Here is our simple .NET Core application, in Solution Explorer. Let us expand References and you will see reference to .NETCoreApp"
},
{
"code": null,
"e": 31740,
"s": 31661,
"text": "Inside .NETCoreApp, you will see package reference to NuGet; let us expand it."
},
{
"code": null,
"e": 31942,
"s": 31740,
"text": "You will see the whole series of NuGet Package references. If you have worked in .NET Framework, then many of these namespaces will look familiar, because you are used to it by using in .NET Framework."
},
{
"code": null,
"e": 32086,
"s": 31942,
"text": ".NET Framework is split into many different pieces and re-implemented with CoreFx; these pieces are further distributed as individual packages."
},
{
"code": null,
"e": 32239,
"s": 32086,
"text": "Now if you expand the NETStandard.Library, you will see addition references. You will even notice System.Console which we are using in this application."
},
{
"code": null,
"e": 32392,
"s": 32239,
"text": "Now if you expand the NETStandard.Library, you will see addition references. You will even notice System.Console which we are using in this application."
},
{
"code": null,
"e": 32515,
"s": 32392,
"text": "Now you donβt have to bring in everything inside the .NET Framework, but just bring in what you need for your application."
},
{
"code": null,
"e": 32638,
"s": 32515,
"text": "Now you donβt have to bring in everything inside the .NET Framework, but just bring in what you need for your application."
},
{
"code": null,
"e": 32744,
"s": 32638,
"text": "There are some other benefits as well; for example, these modules can be updated individually if desired."
},
{
"code": null,
"e": 32850,
"s": 32744,
"text": "There are some other benefits as well; for example, these modules can be updated individually if desired."
},
{
"code": null,
"e": 32965,
"s": 32850,
"text": "Modularity leads to performance benefits and your application can run faster, especially ASP.NET Core application."
},
{
"code": null,
"e": 33074,
"s": 32965,
"text": "In this chapter, we will discuss .NET Core project files and how you can add existing files in your project."
},
{
"code": null,
"e": 33216,
"s": 33074,
"text": "Let us understand a simple example in which we have some files which are already created; we have to add these files in our FirstApp project."
},
{
"code": null,
"e": 33266,
"s": 33216,
"text": "Here is the implementation of the Student.cs file"
},
{
"code": null,
"e": 33606,
"s": 33266,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace FirstApp { \n public class Student { \n public int ID { get; set; } \n public string LastName { get; set; } \n public string FirstMidName { get; set; } \n public DateTime EnrollmentDate { get; set; } \n } \n}"
},
{
"code": null,
"e": 33656,
"s": 33606,
"text": "Here is the implementation of the Course.cs file."
},
{
"code": null,
"e": 33938,
"s": 33656,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace FirstApp { \n public class Course { \n public int CourseID { get; set; } \n public string Title { get; set; } \n public int Credits { get; set; } \n } \n}"
},
{
"code": null,
"e": 34024,
"s": 33938,
"text": "Let us now save these three files in your disk and the source folder of your project."
},
{
"code": null,
"e": 34212,
"s": 34024,
"text": "Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio."
},
{
"code": null,
"e": 34400,
"s": 34212,
"text": "Now if you are familiar with .NET and this one was a traditional .NET framework console application, it is important to understand how to add these files in your project in Visual Studio."
},
{
"code": null,
"e": 34548,
"s": 34400,
"text": "You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files."
},
{
"code": null,
"e": 34696,
"s": 34548,
"text": "You first need to drag the files to the solution explorer to copy them in your project folder, because your project needs reference to these files."
},
{
"code": null,
"e": 34903,
"s": 34696,
"text": "One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project."
},
{
"code": null,
"e": 35110,
"s": 34903,
"text": "One of the benefits of .NET Core is the approach taken with the project file (project.json); we can just drop files into the root of our project and then these will be automatically included in our project."
},
{
"code": null,
"e": 35237,
"s": 35110,
"text": "We donβt have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio."
},
{
"code": null,
"e": 35364,
"s": 35237,
"text": "We donβt have to manually reference files like we did in the past for traditional .NET Framework application in Visual Studio."
},
{
"code": null,
"e": 35406,
"s": 35364,
"text": "Let us now open the root of your project."
},
{
"code": null,
"e": 35476,
"s": 35406,
"text": "Let us now copy all of the three files into the root of your project."
},
{
"code": null,
"e": 35533,
"s": 35476,
"text": "You can now see all the files copied to the root folder."
},
{
"code": null,
"e": 35608,
"s": 35533,
"text": "Let us now go to Visual Studio; you will receive the following dialog box."
},
{
"code": null,
"e": 35649,
"s": 35608,
"text": "Click Yes to All to reload your project."
},
{
"code": null,
"e": 35717,
"s": 35649,
"text": "You will now that files are automatically included in your project."
},
{
"code": null,
"e": 35921,
"s": 35717,
"text": "In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places."
},
{
"code": null,
"e": 36024,
"s": 35921,
"text": "Let us now go to the source code of .NET Core which is located here β https://github.com/dotnet/corefx"
},
{
"code": null,
"e": 36062,
"s": 36024,
"text": "In CoreFx repo, open the src folder β"
},
{
"code": null,
"e": 36169,
"s": 36062,
"text": "And you will see the whole list of folders that correspond to different packages. Let us now search Json β"
},
{
"code": null,
"e": 36393,
"s": 36169,
"text": "There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you wonβt know where that packages in."
},
{
"code": null,
"e": 36506,
"s": 36393,
"text": "If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/"
},
{
"code": null,
"e": 36641,
"s": 36506,
"text": "Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you."
},
{
"code": null,
"e": 36681,
"s": 36641,
"text": "Let us now search for DataContractJson."
},
{
"code": null,
"e": 36757,
"s": 36681,
"text": "You will now see that we get the same package; let us click on the package."
},
{
"code": null,
"e": 36896,
"s": 36757,
"text": "You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods."
},
{
"code": null,
"e": 36931,
"s": 36896,
"text": "Let us open the project.json file."
},
{
"code": null,
"e": 37247,
"s": 36931,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n } \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"dnxcore50\" \n } \n } \n} "
},
{
"code": null,
"e": 37382,
"s": 37247,
"text": "This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below."
},
{
"code": null,
"e": 37750,
"s": 37382,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }, \n \"System.Runtime.Serialization.Json\": \"4.0.2\" \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"dnxcore50\" \n } \n } \n}"
},
{
"code": null,
"e": 37877,
"s": 37750,
"text": "Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project."
},
{
"code": null,
"e": 37959,
"s": 37877,
"text": "Another way is to go to the NuGet Manager and browse the package you want to add."
},
{
"code": null,
"e": 38200,
"s": 37959,
"text": "In this chapter, we will discuss how to create a UWP application using .NET Core. UWP is also known as Windows 10 UWP application. This application does not run on previous versions of Windows but will only run on future version of Windows."
},
{
"code": null,
"e": 38260,
"s": 38200,
"text": "Following are a few exceptions where UWP will run smoothly."
},
{
"code": null,
"e": 38436,
"s": 38260,
"text": "If you want to run it locally you must have Windows 10, you can also develop on Windows 8 and then you will need to run it on Emulator, but it is encouraged to use Windows 10."
},
{
"code": null,
"e": 38612,
"s": 38436,
"text": "If you want to run it locally you must have Windows 10, you can also develop on Windows 8 and then you will need to run it on Emulator, but it is encouraged to use Windows 10."
},
{
"code": null,
"e": 38735,
"s": 38612,
"text": "For UWP application you will also need Windows 10 SDK. Let us open Visual Studio 2015 setup and then modify Visual Studio."
},
{
"code": null,
"e": 38858,
"s": 38735,
"text": "For UWP application you will also need Windows 10 SDK. Let us open Visual Studio 2015 setup and then modify Visual Studio."
},
{
"code": null,
"e": 38987,
"s": 38858,
"text": "On select features page, scroll down and you will see Universal Windows App Development Tools, check that option as shown below."
},
{
"code": null,
"e": 39116,
"s": 38987,
"text": "On select features page, scroll down and you will see Universal Windows App Development Tools, check that option as shown below."
},
{
"code": null,
"e": 39215,
"s": 39116,
"text": "Here you can see the different versions of SDK and the latest update on Tools as well, click Next."
},
{
"code": null,
"e": 39246,
"s": 39215,
"text": "Now, click the Install button."
},
{
"code": null,
"e": 39319,
"s": 39246,
"text": "Once the installation is finished, you will need to restart your system."
},
{
"code": null,
"e": 39374,
"s": 39319,
"text": "Let us now implement the UWP by following these steps."
},
{
"code": null,
"e": 39408,
"s": 39374,
"text": "First, launch Visual Studio 2015."
},
{
"code": null,
"e": 39442,
"s": 39408,
"text": "First, launch Visual Studio 2015."
},
{
"code": null,
"e": 39607,
"s": 39442,
"text": "Click on the File menu and select New β Project; a New Project dialog will show up. You can see the different types of templates on the left pane of the dialog box."
},
{
"code": null,
"e": 39772,
"s": 39607,
"text": "Click on the File menu and select New β Project; a New Project dialog will show up. You can see the different types of templates on the left pane of the dialog box."
},
{
"code": null,
"e": 39885,
"s": 39772,
"text": "In the left pane, you can see the tree view, now select Universal template from Templates β Visual C# β Windows."
},
{
"code": null,
"e": 39998,
"s": 39885,
"text": "In the left pane, you can see the tree view, now select Universal template from Templates β Visual C# β Windows."
},
{
"code": null,
"e": 40071,
"s": 39998,
"text": "From the center pane, select the Blank App (Universal Windows) template."
},
{
"code": null,
"e": 40144,
"s": 40071,
"text": "From the center pane, select the Blank App (Universal Windows) template."
},
{
"code": null,
"e": 40225,
"s": 40144,
"text": "Give a name to the project by typing UWPFirstApp in the Name field and click OK."
},
{
"code": null,
"e": 40306,
"s": 40225,
"text": "Give a name to the project by typing UWPFirstApp in the Name field and click OK."
},
{
"code": null,
"e": 40442,
"s": 40306,
"text": "The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project."
},
{
"code": null,
"e": 40578,
"s": 40442,
"text": "The target version/minimum version dialog appears. The default settings are fine for this tutorial, so select OK to create the project."
},
{
"code": null,
"e": 40737,
"s": 40578,
"text": "Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting."
},
{
"code": null,
"e": 40896,
"s": 40737,
"text": "Here, we have a single project which can target all Windows 10 Devices, and you will notice that both .NET Core and UWP are simplification of multi-targeting."
},
{
"code": null,
"e": 41098,
"s": 40896,
"text": "When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files."
},
{
"code": null,
"e": 41300,
"s": 41098,
"text": "When a new project opens, its files are displayed on the right hand side of the Solution Explorer pane. You may need to choose the Solution Explorer tab instead of the Properties tab to see your files."
},
{
"code": null,
"e": 41518,
"s": 41300,
"text": "Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files."
},
{
"code": null,
"e": 41736,
"s": 41518,
"text": "Although the Blank App (Universal Window) is a minimal template, it still contains a lot of files. These files are essential to all UWP apps using C#. Every project that you create in Visual Studio contains the files."
},
{
"code": null,
"e": 41818,
"s": 41736,
"text": "To see the running example, let us open MainPage.XAML and add the following code."
},
{
"code": null,
"e": 41900,
"s": 41818,
"text": "To see the running example, let us open MainPage.XAML and add the following code."
},
{
"code": null,
"e": 43119,
"s": 41900,
"text": "<Page \n x:Class = \"UWPFirstApp.MainPage\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:local = \"using:UWPFirstApp\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n mc:Ignorable = \"d\"> \n \n <Grid Background = \"{ThemeResource ApplicationPageBackgroundThemeBrush}\"> \n <StackPanel HorizontalAlignment = \"Center\"> \n <TextBlock Text = \"Hello, world!\" \n Margin = \"20\" \n Width = \"200\" \n HorizontalAlignment = \"Left\"/> \n <TextBlock Text = \"Write your name.\" \n Margin = \"20\" \n Width = \"200\" \n HorizontalAlignment = \"Left\"/> \n <TextBox x:Name = \"txtbox\" \n Width = \"280\" \n Margin = \"20\" \n HorizontalAlignment = \"Left\"/> \n <Button x:Name = \"button\" Content = \"Click Me\" \n Margin = \"20\" \n Click = \"button_Click\"/> \n <TextBlock x:Name = \"txtblock\" \n HorizontalAlignment = \"Left\" \n Margin = \"20\"/> \n </StackPanel> \n </Grid> \n\n</Page> "
},
{
"code": null,
"e": 43161,
"s": 43119,
"text": "Below is the click event of button in C#."
},
{
"code": null,
"e": 44234,
"s": 43161,
"text": "using System; \nusing System.Collections.Generic; \nusing System.IO; \nusing System.Linq; \nusing System.Runtime.InteropServices.WindowsRuntime; \n\nusing Windows.Foundation; \nusing Windows.Foundation.Collections; \n\nusing Windows.UI.Xaml; \nusing Windows.UI.Xaml.Controls; \nusing Windows.UI.Xaml.Controls.Primitives; \nusing Windows.UI.Xaml.Data; \nusing Windows.UI.Xaml.Input; \nusing Windows.UI.Xaml.Media; \nusing Windows.UI.Xaml.Navigation; \n\n// The Blank Page item template is documented at \n// http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 \n\nnamespace UWPHellowWorld { \n /// <summary> \n /// An empty page that can be used on its own or navigated to within a Frame. \n /// </summary> \n public sealed partial class MainPage : Page { \n public MainPage() { \n this.InitializeComponent(); \n } \n private void button_Click(object sender, RoutedEventArgs e) { \n if (txtbox.Text != \"\") \n txtblock.Text = \"Hello: \" + txtbox.Text; \n else \n txtblock.Text = \"You have not write your name\"; \n } \n } \n} "
},
{
"code": null,
"e": 44389,
"s": 44234,
"text": "Let us now run the above code on the local machine and you will see the following window. Now type any name in the text box and press the Click Me button."
},
{
"code": null,
"e": 44641,
"s": 44389,
"text": "In this chapter, we will discuss what is MSBuild and how it works with .NET Core. MSBuild is the build platform for Microsoft and Visual Studio. In UWP application if you open the project folder, then you will see both project.json and *.csproj files."
},
{
"code": null,
"e": 44743,
"s": 44641,
"text": "But if you open our previous .NET Core Console app, then you will see project.json and *.xproj files."
},
{
"code": null,
"e": 44900,
"s": 44743,
"text": "The .NET Core build system or the project.json build system is not sufficient for UWP needs; this is why UWP is still using *.csproj (MSBuild) Build system."
},
{
"code": null,
"e": 45057,
"s": 44900,
"text": "The .NET Core build system or the project.json build system is not sufficient for UWP needs; this is why UWP is still using *.csproj (MSBuild) Build system."
},
{
"code": null,
"e": 45129,
"s": 45057,
"text": "But project.json will move out as far as the build system is concerned."
},
{
"code": null,
"e": 45201,
"s": 45129,
"text": "But project.json will move out as far as the build system is concerned."
},
{
"code": null,
"e": 45447,
"s": 45201,
"text": "Now if you want to add a few existing files to your UWP application as we have added in the Console app, then you need to add those files in the project folder. Further, you will also need to include in your project in Solution Explorer as well."
},
{
"code": null,
"e": 45693,
"s": 45447,
"text": "Now if you want to add a few existing files to your UWP application as we have added in the Console app, then you need to add those files in the project folder. Further, you will also need to include in your project in Solution Explorer as well."
},
{
"code": null,
"e": 45775,
"s": 45693,
"text": "Let us now consider the following files; copy these files to your project folder."
},
{
"code": null,
"e": 45839,
"s": 45775,
"text": "Let us go back to Visual Studio and open the Solution Explorer."
},
{
"code": null,
"e": 45982,
"s": 45839,
"text": "You can now see that only copying files is not sufficient in case of UWP applications, because in Solution Explorer, we canβt see those files."
},
{
"code": null,
"e": 46125,
"s": 45982,
"text": "You can now see that only copying files is not sufficient in case of UWP applications, because in Solution Explorer, we canβt see those files."
},
{
"code": null,
"e": 46297,
"s": 46125,
"text": "Now we must include those files as well by clicking on the Show All Files icon as highlighted in the above screenshot and you will see now all files in the project folder."
},
{
"code": null,
"e": 46469,
"s": 46297,
"text": "Now we must include those files as well by clicking on the Show All Files icon as highlighted in the above screenshot and you will see now all files in the project folder."
},
{
"code": null,
"e": 46631,
"s": 46469,
"text": "These two files are still not included in our project. To include these files, select these files and right-click on any file and then select Include in Project."
},
{
"code": null,
"e": 46828,
"s": 46631,
"text": "Now these files are also included. One good thing that can be foreseen is the project.json approach of dropping files for *.csproj in the future version of the SKD tools and also to Visual Studio."
},
{
"code": null,
"e": 47042,
"s": 46828,
"text": "In this chapter, we will discuss the references between our Console app and our UWP app. If you look at the References in Solution Explorer of your Console application, you will see the .NETCoreApp as shown below."
},
{
"code": null,
"e": 47212,
"s": 47042,
"text": ".NETCoreApp is a new framework that targeted .NET Core application. Now if you look under the References of UWP application, it will look a bit different as shown below."
},
{
"code": null,
"e": 47389,
"s": 47212,
"text": "The main reason for this is because here in UWP we have the *.csproj, so we are back to the old style of references and we can target only one framework with this project type."
},
{
"code": null,
"e": 47566,
"s": 47389,
"text": "The main reason for this is because here in UWP we have the *.csproj, so we are back to the old style of references and we can target only one framework with this project type."
},
{
"code": null,
"e": 47794,
"s": 47566,
"text": "The references are similar though. You can now see that in UWP application, the Miscrosoft.NETCore.UniversalWindowsPlatform NuGet Package reference is similar to the Microsoft.NETCore.App NuGet reference in Console application."
},
{
"code": null,
"e": 48022,
"s": 47794,
"text": "The references are similar though. You can now see that in UWP application, the Miscrosoft.NETCore.UniversalWindowsPlatform NuGet Package reference is similar to the Microsoft.NETCore.App NuGet reference in Console application."
},
{
"code": null,
"e": 48168,
"s": 48022,
"text": "Both Miscrosoft.NETCore.UniversalWindowsPlatform and Microsoft.NETCore.App are meta-package which means that they are composed of other packages."
},
{
"code": null,
"e": 48314,
"s": 48168,
"text": "Both Miscrosoft.NETCore.UniversalWindowsPlatform and Microsoft.NETCore.App are meta-package which means that they are composed of other packages."
},
{
"code": null,
"e": 48498,
"s": 48314,
"text": "In Console application, we can drill in and see other packages inside Microsoft.NETCore.App, but we canβt do the same Miscrosoft.NETCore.UniversalWindowsPlatform in Solution Explorer."
},
{
"code": null,
"e": 48682,
"s": 48498,
"text": "In Console application, we can drill in and see other packages inside Microsoft.NETCore.App, but we canβt do the same Miscrosoft.NETCore.UniversalWindowsPlatform in Solution Explorer."
},
{
"code": null,
"e": 48930,
"s": 48682,
"text": "However, we can use another tool, the NuGet Package Explorer to look at this. Let us now open this url in the browser β https://npe.codeplex.com/downloads/get/clickOnce/NuGetPackageExplorer.application and you will see a small utility downloading."
},
{
"code": null,
"e": 49178,
"s": 48930,
"text": "However, we can use another tool, the NuGet Package Explorer to look at this. Let us now open this url in the browser β https://npe.codeplex.com/downloads/get/clickOnce/NuGetPackageExplorer.application and you will see a small utility downloading."
},
{
"code": null,
"e": 49238,
"s": 49178,
"text": "Once downloading completes, then double-click on that file."
},
{
"code": null,
"e": 49298,
"s": 49238,
"text": "Once downloading completes, then double-click on that file."
},
{
"code": null,
"e": 49365,
"s": 49298,
"text": "Click Install to start installation on the NuGet Package Explorer."
},
{
"code": null,
"e": 49432,
"s": 49365,
"text": "Click Install to start installation on the NuGet Package Explorer."
},
{
"code": null,
"e": 49506,
"s": 49432,
"text": "When the installation is finished, you will see the following dialog box."
},
{
"code": null,
"e": 49580,
"s": 49506,
"text": "When the installation is finished, you will see the following dialog box."
},
{
"code": null,
"e": 49644,
"s": 49580,
"text": "Let us now click on the Open a package from online feed option."
},
{
"code": null,
"e": 49708,
"s": 49644,
"text": "Let us now click on the Open a package from online feed option."
},
{
"code": null,
"e": 49883,
"s": 49708,
"text": "By default it will search for the nuget.org feed. Let us now search for Microsoft.NETCore.UniversalWindowsPlatform in the search box and you will see 1 result as shown below."
},
{
"code": null,
"e": 50058,
"s": 49883,
"text": "By default it will search for the nuget.org feed. Let us now search for Microsoft.NETCore.UniversalWindowsPlatform in the search box and you will see 1 result as shown below."
},
{
"code": null,
"e": 50143,
"s": 50058,
"text": "Click the open link and it will open the top-level dependencies of this metapackage."
},
{
"code": null,
"e": 50228,
"s": 50143,
"text": "Click the open link and it will open the top-level dependencies of this metapackage."
},
{
"code": null,
"e": 50350,
"s": 50228,
"text": "Let us now open the .NETCore meta package for the .NETCore application and meta-package for UWP application side by side."
},
{
"code": null,
"e": 50472,
"s": 50350,
"text": "Let us now open the .NETCore meta package for the .NETCore application and meta-package for UWP application side by side."
},
{
"code": null,
"e": 50553,
"s": 50472,
"text": "You can now see that each meta-package is composed of different set of packages."
},
{
"code": null,
"e": 50634,
"s": 50553,
"text": "You can now see that each meta-package is composed of different set of packages."
},
{
"code": null,
"e": 50801,
"s": 50634,
"text": ".NET Core is a subset of the classes available in .NET Framework at least at this point of time, but is growing and will be as per the base classes of .NET Framework."
},
{
"code": null,
"e": 50968,
"s": 50801,
"text": ".NET Core is a subset of the classes available in .NET Framework at least at this point of time, but is growing and will be as per the base classes of .NET Framework."
},
{
"code": null,
"e": 51069,
"s": 50968,
"text": "The UWP is based on .NET Core, it is a superset of the APIs available for Windows Store development."
},
{
"code": null,
"e": 51170,
"s": 51069,
"text": "The UWP is based on .NET Core, it is a superset of the APIs available for Windows Store development."
},
{
"code": null,
"e": 51236,
"s": 51170,
"text": "We now have more APIs available for development due to .NET Core."
},
{
"code": null,
"e": 51533,
"s": 51236,
"text": "Windows Runtime components are self-contained objects that you can instantiate and use from any language, including C#, Visual Basic, JavaScript, and C++. In addition to the .NET Core meta-package we saw in the previous chapter, UWP app also has a reference by default to a Universal Windows SDK."
},
{
"code": null,
"e": 51645,
"s": 51533,
"text": "Universal Windows is the reference to Windows Runtime and it has been factored into a series of APIs contracts."
},
{
"code": null,
"e": 51861,
"s": 51645,
"text": "The set of APIs within a device family is broken down into subdivisions known as API contracts. You can find a list of different API contracts here https://msdn.microsoft.com/en-us/library/windows/apps/dn706135.aspx"
},
{
"code": null,
"e": 52011,
"s": 51861,
"text": "Most of those APIs inside windows runtime are factored into a single contract. Let us now search for the Universal keyword on the API Contracts page."
},
{
"code": null,
"e": 52136,
"s": 52011,
"text": "You can see links to various APIs and you can also see the Universal family is so big that it has 12 pages of documentation."
},
{
"code": null,
"e": 52193,
"s": 52136,
"text": "You can also search for phone API contract on this page."
},
{
"code": null,
"e": 52334,
"s": 52193,
"text": "Let us now click on the Windows.Phone.PhoneContract and scroll down; you will now see the battery information of phone or the mobile device."
},
{
"code": null,
"e": 52539,
"s": 52334,
"text": "If you want to add this information on top of what you already have, then you should add the references manually. Let us now go to the Visual Studio and right-click on the References in Solution Explorer."
},
{
"code": null,
"e": 52564,
"s": 52539,
"text": "Select Add References..."
},
{
"code": null,
"e": 52721,
"s": 52564,
"text": "You can now see the new reference category for Universal Windows; under this category there is Core which refers to the core Universal Windows API contracts"
},
{
"code": null,
"e": 52849,
"s": 52721,
"text": "The Extensions allow us to extend the functionality and you will see different references Mobile, Desktop and other Extensions."
},
{
"code": null,
"e": 52977,
"s": 52849,
"text": "The Extensions allow us to extend the functionality and you will see different references Mobile, Desktop and other Extensions."
},
{
"code": null,
"e": 53053,
"s": 52977,
"text": "There are different SKD extensions and you can add on top to get more APIs."
},
{
"code": null,
"e": 53129,
"s": 53053,
"text": "There are different SKD extensions and you can add on top to get more APIs."
},
{
"code": null,
"e": 53250,
"s": 53129,
"text": "You can also see different versions. So, make sure you get the latest version to get the updated APIs and then click OK."
},
{
"code": null,
"e": 53371,
"s": 53250,
"text": "You can also see different versions. So, make sure you get the latest version to get the updated APIs and then click OK."
},
{
"code": null,
"e": 53453,
"s": 53371,
"text": "You can now see that Windows Mobile Extensions for the UWP is added as reference."
},
{
"code": null,
"e": 53540,
"s": 53453,
"text": "A class library defines the types and methods that can be called from any application."
},
{
"code": null,
"e": 53735,
"s": 53540,
"text": "A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library."
},
{
"code": null,
"e": 53930,
"s": 53735,
"text": "A class library developed using .NET Core supports the .NET Standard Library, which allows your library to be called by any .NET platform that supports that version of the .NET Standard Library."
},
{
"code": null,
"e": 54139,
"s": 53930,
"text": "When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications."
},
{
"code": null,
"e": 54348,
"s": 54139,
"text": "When you finish your class library, you can decide whether you want to distribute it as a third-party component, or whether you want to include it as a component that is bundled with one or more applications."
},
{
"code": null,
"e": 54506,
"s": 54348,
"text": "Let us start by adding a class library project in our Console application; right-click on the src folder in Solution Explorer and select Add β New Project..."
},
{
"code": null,
"e": 54628,
"s": 54506,
"text": "In the Add New Project dialog box, choose the .NET Core node, then choose the Class Library (.NET Core) project template."
},
{
"code": null,
"e": 54732,
"s": 54628,
"text": "In the Name text box, enter \"UtilityLibrary\" as the name of the project, as the following figure shows."
},
{
"code": null,
"e": 54901,
"s": 54732,
"text": "Click OK to create the class library project. Once the project is created, let us add a new class. Right-click on project in Solution Explorer and select Add β Class..."
},
{
"code": null,
"e": 55077,
"s": 54901,
"text": "Select class in the middle pane and enter StringLib.cs in the name and field and then click Add. Once the class is added, then replace the following code in StringLib.cs file."
},
{
"code": null,
"e": 55866,
"s": 55077,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace UtilityLibrary { \n public static class StringLib { \n public static bool StartsWithUpper(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsUpper(ch); \n } \n public static bool StartsWithLower(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsLower(ch); \n } \n public static bool StartsWithNumber(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsNumber(ch); \n } \n } \n} "
},
{
"code": null,
"e": 56136,
"s": 55866,
"text": "The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively."
},
{
"code": null,
"e": 56406,
"s": 56136,
"text": "The class library, UtilityLibrary.StringLib, contains some methods like, StartsWithUpper, StartsWithLower, and StartsWithNumber which returns a Boolean value that indicates whether the current string instance begins with an uppercase, lowercase and number respectively."
},
{
"code": null,
"e": 56639,
"s": 56406,
"text": "In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric."
},
{
"code": null,
"e": 56872,
"s": 56639,
"text": "In .NET Core, the Char.IsUpper method returns true if a character is in uppercase, the Char.IsLower method returns true if a character is in lowercase, and similarly the Char.IsNumber method returns true if a character is a numeric."
},
{
"code": null,
"e": 56961,
"s": 56872,
"text": "On the menu bar, choose Build, Build Solution. The project should compile without error."
},
{
"code": null,
"e": 57050,
"s": 56961,
"text": "On the menu bar, choose Build, Build Solution. The project should compile without error."
},
{
"code": null,
"e": 57122,
"s": 57050,
"text": "Our .NET Core console project doesn't have access to our class library."
},
{
"code": null,
"e": 57194,
"s": 57122,
"text": "Our .NET Core console project doesn't have access to our class library."
},
{
"code": null,
"e": 57299,
"s": 57194,
"text": "Now to consume this class library we need to add reference of this class library in our console project."
},
{
"code": null,
"e": 57404,
"s": 57299,
"text": "Now to consume this class library we need to add reference of this class library in our console project."
},
{
"code": null,
"e": 57488,
"s": 57404,
"text": "To do so, expand FirstApp and right-click on References and select Add Reference..."
},
{
"code": null,
"e": 57594,
"s": 57488,
"text": "In the Reference Manager dialog box, select UtilityLibrary, our class library project, and then click OK."
},
{
"code": null,
"e": 57706,
"s": 57594,
"text": "Let us now open the Program.cs file of the console project and replace all of the code with the following code."
},
{
"code": null,
"e": 58553,
"s": 57706,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Threading.Tasks; \nusing UtilityLibrary; \n\nnamespace FirstApp { \n public class Program { \n public static void Main(string[] args) { \n int rows = Console.WindowHeight; \n Console.Clear(); \n do { \n if (Console.CursorTop >= rows || Console.CursorTop == 0) { \n Console.Clear(); \n Console.WriteLine(\"\\nPress <Enter> only to exit; otherwise, enter a string and press <Enter>:\\n\"); \n } \n string input = Console.ReadLine(); \n \n if (String.IsNullOrEmpty(input)) break; \n Console.WriteLine(\"Input: {0} {1,30}: {2}\\n\", input, \"Begins with uppercase? \", \n input.StartsWithUpper() ? \"Yes\" : \"No\"); \n } while (true); \n } \n } \n} "
},
{
"code": null,
"e": 58624,
"s": 58553,
"text": "Let us now run your application and you will see the following output."
},
{
"code": null,
"e": 58736,
"s": 58624,
"text": "For better understanding, let us make use of the other extension methods of your class library in your project."
},
{
"code": null,
"e": 58953,
"s": 58736,
"text": "In this chapter, we will discuss what is PCL (Portable Class Library), and also why we need PCL. To understand this concept, let us open the class library project folder which we have created in the previous chapter."
},
{
"code": null,
"e": 59149,
"s": 58953,
"text": "In this folder, you can see that in addition to project.json and CS files we also have *.xproj file, and that is because Visual Studio setup .NET Core project type as *.xproj instead of *.csproj."
},
{
"code": null,
"e": 59306,
"s": 59149,
"text": "As mentioned by Microsoft, *.xproj will be going away, but it is still here in preview 2 tooling. As we have covered that UWP application uses the *.csproj."
},
{
"code": null,
"e": 59464,
"s": 59306,
"text": "Now it is actually not feasible to get *.csproj to reference and *.xproj and that functionality is not going to be implemented because *.xproj will move out."
},
{
"code": null,
"e": 59580,
"s": 59464,
"text": "So instead, we need a class library which can be shared between the console app and the UWP app and here comes PCL."
},
{
"code": null,
"e": 59616,
"s": 59580,
"text": "Let us now understand what PCL is β"
},
{
"code": null,
"e": 59753,
"s": 59616,
"text": "The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform."
},
{
"code": null,
"e": 59890,
"s": 59753,
"text": "The Portable Class Library project enables you to write and build managed assemblies that work on more than one .NET Framework platform."
},
{
"code": null,
"e": 60069,
"s": 59890,
"text": "You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects."
},
{
"code": null,
"e": 60248,
"s": 60069,
"text": "You can create classes that contain code you wish to share across many projects, such as shared business logic, and then reference those classes from different types of projects."
},
{
"code": null,
"e": 60353,
"s": 60248,
"text": "It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily."
},
{
"code": null,
"e": 60458,
"s": 60353,
"text": "It can also help you build cross-platform apps and libraries for Microsoft platforms quickly and easily."
},
{
"code": null,
"e": 60554,
"s": 60458,
"text": "Portable class libraries can help you reduce the time and costs of developing and testing code."
},
{
"code": null,
"e": 60650,
"s": 60554,
"text": "Portable class libraries can help you reduce the time and costs of developing and testing code."
},
{
"code": null,
"e": 60844,
"s": 60650,
"text": "Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc."
},
{
"code": null,
"e": 61038,
"s": 60844,
"text": "Use this project type to write and build portable .NET Framework assemblies, and then reference those assemblies from apps that target multiple platforms such as Windows and Windows Phone, etc."
},
{
"code": null,
"e": 61213,
"s": 61038,
"text": "Let us now remove the class library which we have created from the Solution Explorer. At the same time, delete it from the Solution folder and further add a new project item."
},
{
"code": null,
"e": 61326,
"s": 61213,
"text": "Select the Visual C# β Windows template in the left pane and select Class Library (Portable) in the middle pane."
},
{
"code": null,
"e": 61401,
"s": 61326,
"text": "Enter StringLibrary in the name field and click OK to create this project."
},
{
"code": null,
"e": 61557,
"s": 61401,
"text": "Now we need to select the target frameworks to reference. Let us select Windows Universal and ASP.NET Core for a moment then we will retarget it. Click OK."
},
{
"code": null,
"e": 61711,
"s": 61557,
"text": "You can see that it has created a new project in PCF format. Let us now right-click StringLibrary project in the Solution Explorer and select Properties."
},
{
"code": null,
"e": 61755,
"s": 61711,
"text": "Click on the Target .NET Platform Standard."
},
{
"code": null,
"e": 61934,
"s": 61755,
"text": "Click Yes; it is now the same class library with one minor difference. The difference is that it can be used by UWP as well, because it contains *.csproj file instead of *.xproj."
},
{
"code": null,
"e": 62054,
"s": 61934,
"text": "Let us now add a new class; for this, you need to right-click on project in Solution Explorer and select Add β Class..."
},
{
"code": null,
"e": 62226,
"s": 62054,
"text": "Select class in the middle pane and enter StringLib.cs in the name field and then Click Add. Once the class is added, then replace the following code in StringLib.cs file."
},
{
"code": null,
"e": 63042,
"s": 62226,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks; \n \nnamespace StringLibrary { \n public static class StringLib { \n public static bool StartsWithUpper(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsUpper(ch); \n } \n public static bool StartsWithLower(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsLower(ch); \n } \n public static bool StartsWithNumber(this String str) { \n if (String.IsNullOrWhiteSpace(str)) \n return false; \n Char ch = str[0]; \n return Char.IsNumber(ch); \n } \n } \n} "
},
{
"code": null,
"e": 63290,
"s": 63042,
"text": "Let us build this portable class library project and it should compile without error. Now we need to add reference of this portable class library in our console project. So, expand FirstApp and right-click on References and select Add Reference..."
},
{
"code": null,
"e": 63412,
"s": 63290,
"text": "In the Reference Manager dialog box, select StringLibrary which is our portable class library project, and then click OK."
},
{
"code": null,
"e": 63542,
"s": 63412,
"text": "You can see that the StringLibrary reference is added to the console project and it can be seen in the project.json file as well."
},
{
"code": null,
"e": 63614,
"s": 63542,
"text": "You can now run the application again and you will see the same output."
},
{
"code": null,
"e": 63782,
"s": 63614,
"text": "Let us now use the other extension methods of your portable class library in your project. The same portable library will be consumed in your UWP application as well."
},
{
"code": null,
"e": 63971,
"s": 63782,
"text": "In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project."
},
{
"code": null,
"e": 64104,
"s": 63971,
"text": "You can now see that the PCL project has some references by default. You can also add other references as per your application need."
},
{
"code": null,
"e": 64164,
"s": 64104,
"text": "In the PCL library, you can also see the project.json file."
},
{
"code": null,
"e": 64370,
"s": 64164,
"text": "{ \n \"supports\": {}, \n \"dependencies\": { \n \"NETStandard.Library\": \"1.6.0\", \n \"Microsoft.NETCore.Portable.Compatibility\": \"1.0.1\" \n }, \n \"frameworks\": { \n \"netstandard1.3\": {} \n } \n}"
},
{
"code": null,
"e": 64582,
"s": 64370,
"text": "One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code."
},
{
"code": null,
"e": 64891,
"s": 64582,
"text": "{ \n \"supports\": {}, \n \"dependencies\": { \n \"NETStandard.Library\": \"1.6.0\", \n \"Microsoft.NETCore.Portable.Compatibility\": \"1.0.1\", \n \"System.Runtime.Serialization.Json\": \"4.0.3\", \n \"Microsoft.EntityFrameworkCore\": \"1.1.0\" \n }, \n \"frameworks\": { \n \"netstandard1.3\": {} \n } \n} "
},
{
"code": null,
"e": 64981,
"s": 64891,
"text": "Let us now save this file and you will see that references are added to your library now."
},
{
"code": null,
"e": 65163,
"s": 64981,
"text": "The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages..."
},
{
"code": null,
"e": 65293,
"s": 65163,
"text": "On the Browse tab, you can search any NuGet package; let us say we want to add βSystem.Runtime.Serialization.Primitivesβ package."
},
{
"code": null,
"e": 65360,
"s": 65293,
"text": "Click the Install button, which will display the following screen."
},
{
"code": null,
"e": 65386,
"s": 65360,
"text": "Now, click the OK button."
},
{
"code": null,
"e": 65606,
"s": 65386,
"text": "Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the βSystem.Runtime.Serialization.Primitivesβ NuGet package is added to your library."
},
{
"code": null,
"e": 66077,
"s": 65606,
"text": "In this chapter, we will discuss how to share your library as NuGet Package so that it can be consumed within another project. Creating a package starts with the code you want to package and share with others, either through the public nuget.org gallery or a private gallery within your organization. The package can also include additional files such as a readme that is displayed when the package is installed, and can include transformations to certain project files."
},
{
"code": null,
"e": 66291,
"s": 66077,
"text": "Let us now consider a simple example in which we will create a NuGet package from our library. To do so, open the command prompt and go to the folder where the project.json file of your library project is located."
},
{
"code": null,
"e": 66329,
"s": 66291,
"text": "Let us now run the following command."
},
{
"code": null,
"e": 66343,
"s": 66329,
"text": "dotnet help \n"
},
{
"code": null,
"e": 66420,
"s": 66343,
"text": "At the end, you can see different commands like new, restore and build, etc."
},
{
"code": null,
"e": 66522,
"s": 66420,
"text": "The last command is pack; this will create a NuGet package. Let us now execute the following command."
},
{
"code": null,
"e": 66535,
"s": 66522,
"text": "dotnet pack\n"
},
{
"code": null,
"e": 66641,
"s": 66535,
"text": "You can now see that the NuGet packages are produced in the bin folder; let us open the bin\\Debug folder."
},
{
"code": null,
"e": 66787,
"s": 66641,
"text": "Now the question is what is inside the NuGet packages, to see that we can use NuGet Package Explorer. Let us now open the NuGet Package Explorer."
},
{
"code": null,
"e": 66833,
"s": 66787,
"text": "Select the first option Open a local package."
},
{
"code": null,
"e": 66886,
"s": 66833,
"text": "Select the StringLibrary.1.0.0.nupkg and click Open."
},
{
"code": null,
"e": 67104,
"s": 66886,
"text": "You can see that in the Package contents section we have StringLibrary.dll only. In the Package metadata section, you will see a bit of information about this library like Id, Versions and all the of the dependencies."
},
{
"code": null,
"e": 67159,
"s": 67104,
"text": "Let us now open the StringLibrary.1.0.0.symbols.nupkg."
},
{
"code": null,
"e": 67319,
"s": 67159,
"text": "In this NuGet package, you will see the source files and the *.pdb file as well. If you double-click on the StringLib.cs file, you see the source code as well."
},
{
"code": null,
"e": 67416,
"s": 67319,
"text": "Here the question is, how can configure the metadata like version, authors and description, etc."
},
{
"code": null,
"e": 67623,
"s": 67416,
"text": "The project.json file is used on .NET Core projects to define project metadata, compilation information, and dependencies. Let us now open the project.json file and add the following additional information."
},
{
"code": null,
"e": 68096,
"s": 67623,
"text": "{ \n \"authors\": [ \"Mark Junior\" ], \n \"description\": \"String Library API\", \n \"version\" : \"1.0.1-*\", \n \"supports\": {}, \n \n \"dependencies\": { \n \"Microsoft.EntityFrameworkCore\": \"1.1.0\", \n \"Microsoft.NETCore.Portable.Compatibility\": \"1.0.1\", \n \"NETStandard.Library\": \"1.6.0\", \n \"System.Runtime.Serialization.Json\": \"4.0.3\", \n \"System.Runtime.Serialization.Primitives\": \"4.3.0\" \n }, \n \"frameworks\": { \n \"netstandard1.3\": {} \n } \n}"
},
{
"code": null,
"e": 68285,
"s": 68096,
"text": "You can now see additional information like author name, description and version added here. Let us save this file, build the library project, then execute the βdotnet packβ command again."
},
{
"code": null,
"e": 68439,
"s": 68285,
"text": "Inside the bin\\Debug folder, you can see that the StringLibrary NuGet packages are produced with version 1.0.1; let us open it in NuGet Package Explorer."
},
{
"code": null,
"e": 68533,
"s": 68439,
"text": "You will see the updated metadata. The question now is, how can we use it in another package."
},
{
"code": null,
"e": 68639,
"s": 68533,
"text": "We need to start by publishing somewhere in the NuGet feed and then we can consume it in another project."
},
{
"code": null,
"e": 68695,
"s": 68639,
"text": "There are two options to publish the updated metadata β"
},
{
"code": null,
"e": 68719,
"s": 68695,
"text": "Publish it to nuget.org"
},
{
"code": null,
"e": 68759,
"s": 68719,
"text": "Push the metadata to private NuGet feed"
},
{
"code": null,
"e": 69044,
"s": 68759,
"text": "Here we will be using the private NuGet feed because it is a lot easier than to setup an account on nuget.org. To learn how to publish your package to nuget.org, you can follow all the guidelines specified here https://docs.microsoft.com/en-us/nuget/create-packages/publish-a-package."
},
{
"code": null,
"e": 69115,
"s": 69044,
"text": "Follow these steps to push the updated metadata to private NuGet feed."
},
{
"code": null,
"e": 69280,
"s": 69115,
"text": "Step 1 β To start with, we need the nuget commandline utility and we have to install it. Let us now open the NuGet Package Manager and search for nuget.commandline."
},
{
"code": null,
"e": 69333,
"s": 69280,
"text": "Step 2 β Select Nuget.Commandline and click Install."
},
{
"code": null,
"e": 69531,
"s": 69333,
"text": "Step 3 β Click OK to install Nuget.Commandline. You can also manually install it by downloading it from the following Url https://dist.nuget.org/index.html and then set up the environment variable."
},
{
"code": null,
"e": 69716,
"s": 69531,
"text": "Step 4 β Once the installation is finished, let us open the command prompt again and go to the bin\\Debug folder where the NuGet packages are located and specify the following command β"
},
{
"code": null,
"e": 69786,
"s": 69716,
"text": "nuget add StringLibrary.1.0.1.nupkg -Source D:\\PrivateNugetPackages \n"
},
{
"code": null,
"e": 69965,
"s": 69786,
"text": "Step 5 β In the above command, we add the StringLibrary.1.0.1.nupkg package to our private feed and the location is D:\\PrivateNugetPackages, -Source specifies the package source."
},
{
"code": null,
"e": 70083,
"s": 69965,
"text": "Step 6 β You can see that the StringLibrary is installed; the StringLibrary can further be added to the private feed."
},
{
"code": null,
"e": 70118,
"s": 70083,
"text": "Step 7 β Let us go to that folder."
},
{
"code": null,
"e": 70232,
"s": 70118,
"text": "Step 8 β Inside the stringlibrary folder, you will see another folder with the version name and here it is 1.0.1."
},
{
"code": null,
"e": 70267,
"s": 70232,
"text": "The NuGet package is located here."
},
{
"code": null,
"e": 70495,
"s": 70267,
"text": "In this chapter, we will discuss how to consume the NuGet package which we have created and published to a private NuGet feed. So, first we will create a Xamarin.Forms project. We need to first understand what is Xamarin.Forms."
},
{
"code": null,
"e": 70596,
"s": 70495,
"text": "Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces."
},
{
"code": null,
"e": 70697,
"s": 70596,
"text": "Xamarin.Forms is a framework that allows developers to rapidly create crossplatform user interfaces."
},
{
"code": null,
"e": 70894,
"s": 70697,
"text": "Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone."
},
{
"code": null,
"e": 71091,
"s": 70894,
"text": "Xamarin.Forms is a cross-platform natively backed UI toolkit abstraction that allows developers to easily create user interfaces that can be shared across Android, iOS, Windows, and Windows Phone."
},
{
"code": null,
"e": 71269,
"s": 71091,
"text": "The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform."
},
{
"code": null,
"e": 71447,
"s": 71269,
"text": "The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel for each platform."
},
{
"code": null,
"e": 71647,
"s": 71447,
"text": "To start Xamarin.Forms, we need some additional features in Visual Studio 2015. Let us modify your Visual Studio 2015 and make sure the following cross-platform mobile development option is selected."
},
{
"code": null,
"e": 71740,
"s": 71647,
"text": "Once the installation is finished, let us update the Xamarin by selecting Tools β Options..."
},
{
"code": null,
"e": 71907,
"s": 71740,
"text": "Scroll down and expand Xamarin in the left pane and then select Other. On top right hand corner of the dialog box, click on Check Now to see if updates are available."
},
{
"code": null,
"e": 72080,
"s": 71907,
"text": "You can see that updates are available, let us click on the Download button to start downloading. Once downloading is finished, you will be notified to install the updates."
},
{
"code": null,
"e": 72172,
"s": 72080,
"text": "Let us now open the Visual studio again and select the File β New β Project... menu option."
},
{
"code": null,
"e": 72356,
"s": 72172,
"text": "In the left pane, select the Visual C# β Cross-Platform template and in the middle pane, select Blank Xaml App (Xamarin.Forms Portable). Enter the name in the Name field and click OK."
},
{
"code": null,
"e": 72420,
"s": 72356,
"text": "Select the Target Version and the Minimum Version and click OK."
},
{
"code": null,
"e": 72591,
"s": 72420,
"text": "You will see a series of projects; at the top we have the PCL library which will be shared among all platforms like Android, iOS, UWP, Windows 8.1, and Windows Phone 8.1."
},
{
"code": null,
"e": 72685,
"s": 72591,
"text": "Here, we will focus on the PCL library and will bring some code here. Let us expand the code."
},
{
"code": null,
"e": 72839,
"s": 72685,
"text": "In this Xamarin.Forms template, you can see the generic App.xaml and MainPage.xaml, uses Xamarin.Forms XAML framework which works across these platforms."
},
{
"code": null,
"e": 72938,
"s": 72839,
"text": "We need to import our codes and we also need the private NuGet feed we set up in the last chapter."
},
{
"code": null,
"e": 73042,
"s": 72938,
"text": "Let us now open the NuGet Package Manager. Click on the wheel next to the Package source dropdown list."
},
{
"code": null,
"e": 73117,
"s": 73042,
"text": "We need to add our private feed here, let us click on the plus (+) button."
},
{
"code": null,
"e": 73255,
"s": 73117,
"text": "You will see that another checkbox is added in the Available package sources section, let us specify a name and source path and click OK."
},
{
"code": null,
"e": 73440,
"s": 73255,
"text": "Let us now go to the Browse tab and select PrivateSource from the Package source dropdown list and you will see the StringLibrary NuGet package. Select StringLibrary and click Install."
},
{
"code": null,
"e": 73477,
"s": 73440,
"text": "Click OK and you will see one error."
},
{
"code": null,
"e": 73587,
"s": 73477,
"text": "We canβt use library with .NETPortable profile version 259, we will be fixing this error in the next chapter."
},
{
"code": null,
"e": 73722,
"s": 73587,
"text": "In this chapter, we will be fixing the error we got while installing the NuGet package from our private feed in Xamarin.Forms project."
},
{
"code": null,
"e": 73847,
"s": 73722,
"text": "We will further understand the problem in brief. To start with, let us right-click on the PCL library and select Properties."
},
{
"code": null,
"e": 74101,
"s": 73847,
"text": "On this page, you will see the whole series of frameworks targeted. From the error, you can see that the .NETPortable profile 259 is not compatible with our StringLibrary 1.0.1. However, it is trying to take reference from the .NET Standard 1.1 library."
},
{
"code": null,
"e": 74206,
"s": 74101,
"text": "Let us now see the .NET Standard Library and identify which platform is not compatible with our library."
},
{
"code": null,
"e": 74394,
"s": 74206,
"text": "You can see that Windows Phone Silverlight 8 is compatible with .NET Standard 1.0. If you open the following webpage, then you will see that Profile259 can support only .NET Standard 1.0."
},
{
"code": null,
"e": 74442,
"s": 74394,
"text": "Let us now uncheck Windows Phone Silverlight 8."
},
{
"code": null,
"e": 74463,
"s": 74442,
"text": "Click the OK button."
},
{
"code": null,
"e": 74604,
"s": 74463,
"text": "Now to fix this issue click OK and cancel the Change Targets dialog and then open Package Manager Console and execute the following command."
},
{
"code": null,
"e": 74642,
"s": 74604,
"text": "PM > Uninstall-Package Xamarin.Forms\n"
},
{
"code": null,
"e": 74718,
"s": 74642,
"text": "Let us now go to the Properties of PCL library. Click on the Change button."
},
{
"code": null,
"e": 74768,
"s": 74718,
"text": "Uncheck Windows Phone Silverlight 8 and Click OK."
},
{
"code": null,
"e": 74996,
"s": 74768,
"text": "You can now see that Windows Phone Silverlight 8 is no longer available in Targeted framework. You can also see the profile that is the target now. To see this, let us unload the PCL library and edit the XamarinApp.csproj file."
},
{
"code": null,
"e": 75059,
"s": 74996,
"text": "You can see now that TargetFrameworkProfile is now Profile111."
},
{
"code": null,
"e": 75157,
"s": 75059,
"text": "If you open the documentation, then you will see that Profile111 is supporting .NET Standard 1.1."
},
{
"code": null,
"e": 75288,
"s": 75157,
"text": "Let us now reload the PCL again and open the NuGet Package Manager and try to install the StringLibrary package from private feed."
},
{
"code": null,
"e": 75383,
"s": 75288,
"text": "From the Dependency behavior dropdown list, select Ignore Dependencies and then click Install."
},
{
"code": null,
"e": 75584,
"s": 75383,
"text": "You can see that the StringLibrary package is now installed from the private feed. If you expand the References of PCL, then you will see that the StringLibrary reference is also added as shown below."
},
{
"code": null,
"e": 75765,
"s": 75584,
"text": "We had uninstalled the Xamarin.Forms for the Windows Phone Silverlight 8 issue. The Xamarin.Forms needs to be installed again. It is recommended that the same version is installed."
},
{
"code": null,
"e": 75862,
"s": 75765,
"text": "Once the installation completes, let us use the StringLibrary functionality in your application."
},
{
"code": null,
"e": 76223,
"s": 75862,
"text": "In this chapter, we will discuss how to create a Testing project using .NET Core. Unit testing is a development process for the software that has the smallest testable parts of an application, which are called units. They are individually and independently scrutinized for any proper operation. Unit testing is can either be automated or done manually as well."
},
{
"code": null,
"e": 76309,
"s": 76223,
"text": "Let us now open the New Project dialog box and select Visual C# β .NET Core template."
},
{
"code": null,
"e": 76616,
"s": 76309,
"text": "On this dialog box, you can see that there is no project template for unit testing. To create a unit test project, we should use the command line utility. Let us go to the Solution folder that we created; create a test folder and inside the test folder create another folder and call it StringLibraryTests."
},
{
"code": null,
"e": 76728,
"s": 76616,
"text": "Let us now use the dotnet commandline utility to create a new test project by executing the following command β"
},
{
"code": null,
"e": 76753,
"s": 76728,
"text": "dotnet new -t xunittest\n"
},
{
"code": null,
"e": 76923,
"s": 76753,
"text": "You can now see that a new C# project is created; let us look into the folder by executing the v command and you will see project.json and Tests.cs files as shown below."
},
{
"code": null,
"e": 76962,
"s": 76923,
"text": "Here is the code in project.json file."
},
{
"code": null,
"e": 77569,
"s": 76962,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"debugType\": \"portable\" \n }, \n \"dependencies\": { \n \"System.Runtime.Serialization.Primitives\": \"4.1.1\", \n \"xunit\": \"2.1.0\", \n \"dotnet-test-xunit\": \"1.0.0-rc2-192208-24\" \n }, \n \"testRunner\": \"xunit\", \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n } \n }, \n \"imports\": [ \n \"dotnet5.4\", \n \"portable-net451+win8\" \n ] \n } \n } \n} "
},
{
"code": null,
"e": 77612,
"s": 77569,
"text": "Following is the code in the Test.cs file."
},
{
"code": null,
"e": 77775,
"s": 77612,
"text": "using System; \nusing Xunit; \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(true); \n } \n } \n} "
},
{
"code": null,
"e": 77862,
"s": 77775,
"text": "To fetch the necessary dependencies from NuGet, let us execute the following command β"
},
{
"code": null,
"e": 77878,
"s": 77862,
"text": "dotnet restore\n"
},
{
"code": null,
"e": 77944,
"s": 77878,
"text": "We can run the test when the necessary dependencies are restored."
},
{
"code": null,
"e": 78057,
"s": 77944,
"text": "You can see that the compilation succeeded; as you go down you can see some information about the test executed."
},
{
"code": null,
"e": 78196,
"s": 78057,
"text": "Currently we have 1 test executed, 0 error, 0 failed, 0 skipped and the time taken by the execution process also mentioned as information."
},
{
"code": null,
"e": 78476,
"s": 78196,
"text": "In this chapter, we will discuss how to run tests in Visual Studio. The .NET Core has been designed with testability in mind, so that creating unit tests for your applications is easier than ever before. In this chapter, we will run and execute our test project in Visual Studio."
},
{
"code": null,
"e": 78528,
"s": 78476,
"text": "Let us open the FirstApp solution in Visual Studio."
},
{
"code": null,
"e": 78674,
"s": 78528,
"text": "You can see that it has only two projects and you will not be able to see the test project because we havenβt added that project in our solution."
},
{
"code": null,
"e": 78718,
"s": 78674,
"text": "Let us add a folder first and call it test."
},
{
"code": null,
"e": 78750,
"s": 78718,
"text": "Right-click on the test folder."
},
{
"code": null,
"e": 78791,
"s": 78750,
"text": "Select project.json file and click Open."
},
{
"code": null,
"e": 78859,
"s": 78791,
"text": "The following screenshot shows the code in Tests.cs file as output."
},
{
"code": null,
"e": 79057,
"s": 78859,
"text": "It is the default implementation and it is just testing that True is equal to true. It is the xUnit testing framework and you will see the Fact attribute that annotates and denotes the test method."
},
{
"code": null,
"e": 79223,
"s": 79057,
"text": "using System; \nusing Xunit; \n \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(true); \n } \n } \n} "
},
{
"code": null,
"e": 79277,
"s": 79223,
"text": "Following is the implementation of project.json file."
},
{
"code": null,
"e": 79882,
"s": 79277,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"debugType\": \"portable\" \n }, \n \"dependencies\": { \n \"System.Runtime.Serialization.Primitives\": \"4.1.1\", \n \"xunit\": \"2.1.0\", \n \"dotnet-test-xunit\": \"1.0.0-rc2-192208-24\" \n }, \n \"testRunner\": \"xunit\", \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }\n }, \n \"imports\": [ \n \"dotnet5.4\", \n \"portable-net451+win8\" \n ] \n } \n } \n}"
},
{
"code": null,
"e": 80077,
"s": 79882,
"text": "In project.json file, the most important dependency to the testing framework is the xunit, which brings in the Fact attribute. It brings in the testing framework and APIs for testing with xunit."
},
{
"code": null,
"e": 80327,
"s": 80077,
"text": "We also have the dotnet-test-xunit, this is an adopter so that xunit can work with .NET Core, specifically with dotnet test command line utility. Then you will see the testRunner which will run xunit and you can also see the netcoreapp1.0 framework."
},
{
"code": null,
"e": 80374,
"s": 80327,
"text": "You will see the .NETCore.App dependeny below."
},
{
"code": null,
"e": 80482,
"s": 80374,
"text": "To run test in Visual Studio, let us open Test Explorer from the Test β Window β Test Explorer menu option."
},
{
"code": null,
"e": 80671,
"s": 80482,
"text": "And you can see that Visual Studio automatically detects the test. The name of the test consists of namespace.className.TestMethodName. Let us now click on Run All button in Test Explorer."
},
{
"code": null,
"e": 80853,
"s": 80671,
"text": "It will first build the code and the run the test and you will see the total time taken by the test. Let us change the test method so that we can see the output when the test fails."
},
{
"code": null,
"e": 81020,
"s": 80853,
"text": "using System; \nusing Xunit; \n \nnamespace Tests { \n public class Tests { \n [Fact] \n public void Test1() { \n Assert.True(false); \n } \n } \n} "
},
{
"code": null,
"e": 81090,
"s": 81020,
"text": "Let us execute the test again by clicking on the Run All button link."
},
{
"code": null,
"e": 81124,
"s": 81090,
"text": "You can now see the test failure."
},
{
"code": null,
"e": 81266,
"s": 81124,
"text": "In this chapter, we will test our StringLibrary and to do so, we need to rearrange our projects so that we can follow the default convention."
},
{
"code": null,
"e": 81300,
"s": 81266,
"text": "Let us open the global.json file."
},
{
"code": null,
"e": 81401,
"s": 81300,
"text": "{ \n \"projects\": [ \"src\", \"test\" ], \n \"sdk\": { \n \"version\": \"1.0.0-preview2-003131\" \n } \n}"
},
{
"code": null,
"e": 81519,
"s": 81401,
"text": "At the top of this file you will see the project settings and it sets up some folder such as src and test by default."
},
{
"code": null,
"e": 81654,
"s": 81519,
"text": "As by convention we must have projects in these folders, this is the new convention and that is going to be used as part of .NET Core."
},
{
"code": null,
"e": 81821,
"s": 81654,
"text": "In the Solution Explorer, you can see that both the console project and the library project are inside the src folder while the Testing project is inside test folder."
},
{
"code": null,
"e": 82046,
"s": 81821,
"text": "And the projects structure in Solution Explorer doesnβt represent where the projects physically exist on the disk. Let us now open the Solution folder and you will see that StringLibrary project is not inside the src folder."
},
{
"code": null,
"e": 82281,
"s": 82046,
"text": "You can see that both src and test folders map to the convention specified in the global.json file. However, we have one project StringLibrary which is out of convention. Let us now add the StringLibrary project inside the src folder."
},
{
"code": null,
"e": 82566,
"s": 82281,
"text": "In the src folder, we have two projects and we need to fix the problem so that we can use all the projects properly. Let us go back to the Visual Studio and right-click on the StringLibrary project and select the Remove option. It wonβt delete it, but it will only remove the project."
},
{
"code": null,
"e": 82637,
"s": 82566,
"text": "Now right-click on the src folder and select Add β Existing Project..."
},
{
"code": null,
"e": 82762,
"s": 82637,
"text": "Browse to the StringLibrary project which is now inside the src folder, select the StringLibrary.csproj file and click Open."
},
{
"code": null,
"e": 82862,
"s": 82762,
"text": "We now have to remove the reference of StringLibrary from the project.json file of the console app."
},
{
"code": null,
"e": 83299,
"s": 82862,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }, \n \"NuGet.CommandLine\": \"3.5.0\", \n \"System.Runtime.Serialization.Json\": \"4.0.3\" \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { }, \n \"imports\": \"dnxcore50\" \n } \n } \n} "
},
{
"code": null,
"e": 83389,
"s": 83299,
"text": "Save the changes and then add a reference of StringLibrary again in your console project."
},
{
"code": null,
"e": 83915,
"s": 83389,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n }, \n \"NuGet.CommandLine\": \"3.5.0\", \n \"System.Runtime.Serialization.Json\": \"4.0.3\" \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"dependencies\": { \n \"StringLibrary\": { \n \"target\": \"project\" \n } \n }, \n \"imports\": \"dnxcore50\" \n } \n } \n}"
},
{
"code": null,
"e": 84258,
"s": 83915,
"text": "Now everything should be working again and you can build StringLibrary and then FirstApp (console project) without any error. Let us now test the StringLibrary functionality using xunit. We need to add reference of StringLibrary into our testing project. Right-click on the References of StringLibraryTests project and select Add Reference..."
},
{
"code": null,
"e": 84395,
"s": 84258,
"text": "Click OK which will add a reference of StringLibrary to our testing project. Let us now replace the following code in the Tests.cs file."
},
{
"code": null,
"e": 84956,
"s": 84395,
"text": "using System; \nusing Xunit; \nusing StringLibrary; \n \nnamespace Tests { \n public class Tests { \n [Fact] \n public void StartsWithUpperCaseTest() { \n string input = \"Mark\"; \n Assert.True(input.StartsWithUpper()); \n } \n [Fact] \n public void StartsWithLowerCaseTest() { \n string input = \"mark\"; \n Assert.True(input.StartsWithLower()); \n } \n [Fact] \n public void StartsWithNumberCaseTest() { \n string input = \"123\"; \n Assert.True(input.StartsWithNumber()); \n } \n } \n} "
},
{
"code": null,
"e": 85138,
"s": 84956,
"text": "You can see that we have three test methods which will test the functionality of StringLibrary. Let us click the Run All link and you will see the following output in Test Explorer."
},
{
"code": null,
"e": 85256,
"s": 85138,
"text": "You can also run the tests from the command line. Let us open the command prompt and execute the dotnet test command."
},
{
"code": null,
"e": 85486,
"s": 85256,
"text": "In this chapter, we will discuss the Managed Extensibility Framework (MEF). MEF can be used for third-party plugin extensibility, or it can bring the benefits of a loosely-coupled plugin-like architecture to regular applications."
},
{
"code": null,
"e": 85554,
"s": 85486,
"text": "MEF is a library for creating lightweight, extensible applications."
},
{
"code": null,
"e": 85622,
"s": 85554,
"text": "MEF is a library for creating lightweight, extensible applications."
},
{
"code": null,
"e": 85718,
"s": 85622,
"text": "It allows application developers to discover and use extensions with no configuration required."
},
{
"code": null,
"e": 85814,
"s": 85718,
"text": "It allows application developers to discover and use extensions with no configuration required."
},
{
"code": null,
"e": 86002,
"s": 85814,
"text": "MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications."
},
{
"code": null,
"e": 86190,
"s": 86002,
"text": "MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used that improves the flexibility, maintainability and testability of large applications."
},
{
"code": null,
"e": 86341,
"s": 86190,
"text": "You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET."
},
{
"code": null,
"e": 86492,
"s": 86341,
"text": "You can use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server applications that use ASP.NET."
},
{
"code": null,
"e": 86573,
"s": 86492,
"text": "MEF has been ported as Microsoft.Composition to .NET Core as well but partially."
},
{
"code": null,
"e": 86654,
"s": 86573,
"text": "MEF has been ported as Microsoft.Composition to .NET Core as well but partially."
},
{
"code": null,
"e": 86841,
"s": 86654,
"text": "Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we donβt have the catalogs which can load types from assemblies in a directory."
},
{
"code": null,
"e": 87028,
"s": 86841,
"text": "Only System.Composition is ported, and System.ComponentModel.Composition is not available yet. This means, we donβt have the catalogs which can load types from assemblies in a directory."
},
{
"code": null,
"e": 87109,
"s": 87028,
"text": "In this chapter, we will only learn how we can use MEF in .NET Core application."
},
{
"code": null,
"e": 87254,
"s": 87109,
"text": "Let us understand a simple example in which we will use MEF in .NET Core console application. Let us now create a new .NET Core console project."
},
{
"code": null,
"e": 87382,
"s": 87254,
"text": "In the left pane, select Templates β Visual C# β .NET Core and then in the middle pane, select Console Application (.NET Core)."
},
{
"code": null,
"e": 87444,
"s": 87382,
"text": "Enter the name of the project in the Name field and click OK."
},
{
"code": null,
"e": 87641,
"s": 87444,
"text": "Once the project is created, we need to add reference of Microsoft.Composition so that we can use MEF. To do so, let us right-click on the project in Solution Explorer and Manage NuGet Packages..."
},
{
"code": null,
"e": 87693,
"s": 87641,
"text": "Search for Microsoft.Composition and click Install."
},
{
"code": null,
"e": 87714,
"s": 87693,
"text": "Click the OK button."
},
{
"code": null,
"e": 87741,
"s": 87714,
"text": "Click the I Accept button."
},
{
"code": null,
"e": 87812,
"s": 87741,
"text": "When the installation completes, you will find an error in References."
},
{
"code": null,
"e": 87847,
"s": 87812,
"text": "Let us open the project.json file."
},
{
"code": null,
"e": 88210,
"s": 87847,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \n \"dependencies\": { \n \"Microsoft.Composition\": \"1.0.30\", \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\" \n } \n }, \n \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"dnxcore50\" \n } \n } \n}"
},
{
"code": null,
"e": 88463,
"s": 88210,
"text": "You can see that the Microsoft.Composition dependency is added, but the problem is that this package is not compatible with dnxcore50. So we need to import portablenet45+win8+wp8+wpa81. Let us now replace your project.json file with the following code."
},
{
"code": null,
"e": 88840,
"s": 88463,
"text": "{ \n \"version\": \"1.0.0-*\", \n \"buildOptions\": { \n \"emitEntryPoint\": true \n }, \n \"dependencies\": { \n \"Microsoft.Composition\": \"1.0.30\", \n \"Microsoft.NETCore.App\": { \n \"type\": \"platform\", \n \"version\": \"1.0.1\"\n } \n }, \n \"frameworks\": { \n \"netcoreapp1.0\": { \n \"imports\": \"portable-net45+win8+wp8+wpa81\" \n } \n } \n} "
},
{
"code": null,
"e": 88901,
"s": 88840,
"text": "Save this file and you will see that the error is rectified."
},
{
"code": null,
"e": 88987,
"s": 88901,
"text": "If you expand the References, then you will see a reference of Microsoft.Composition."
},
{
"code": null,
"e": 89153,
"s": 88987,
"text": "First we need to create an interface that is to be exported and implement the interface and decorate the class with the export attribute. Let us now add a new class."
},
{
"code": null,
"e": 89216,
"s": 89153,
"text": "Enter the name for your class in the Name field and click Add."
},
{
"code": null,
"e": 89272,
"s": 89216,
"text": "Let us add the following code in the PrintData.cs file."
},
{
"code": null,
"e": 89671,
"s": 89272,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Composition; \nusing System.Linq; \nusing System.Threading.Tasks; \n \nnamespace MEFDemo { \n public interface IPrintData { \n void Send(string message); \n } \n [Export(typeof(IPrintData))] \n public class PrintData : IPrintData { \n public void Send(string message) { \n Console.WriteLine(message); \n } \n } \n} "
},
{
"code": null,
"e": 89915,
"s": 89671,
"text": "As mentioned above, Catalogs are not available in Microsoft.Composition namespace. So, it will load all the types from the Assembly with export attribute and attach to the import attribute as shown in the Compose method in the Program.cs file."
},
{
"code": null,
"e": 90852,
"s": 89915,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Composition; \nusing System.Composition.Hosting; \nusing System.Linq; \nusing System.Reflection; \nusing System.Threading.Tasks; \n \nnamespace MEFDemo { \n public class Program { \n public static void Main(string[] args) { \n Program p = new Program(); \n p.Run(); \n } \n public void Run() { \n Compose(); \n PrintData.Send(\"Hello,this is MEF demo\"); \n } \n [Import] \n public IPrintData PrintData { get; set; } \n \n private void Compose() { \n var assemblies = new[] { typeof(Program).GetTypeInfo().Assembly }; \n var configuration = new ContainerConfiguration() \n .WithAssembly(typeof(Program).GetTypeInfo().Assembly); \n \n using (var container = configuration.CreateContainer()) { \n PrintData = container.GetExport<IPrintData>(); \n } \n } \n } \n}"
},
{
"code": null,
"e": 90958,
"s": 90852,
"text": "Let us now run your application and you will see that it is running by instantiating the PrintData class."
},
{
"code": null,
"e": 91101,
"s": 90958,
"text": "To learn more about MEF, let us visit the following Url https://msdn.microsoft.com/en-us/library/dd460648%28v=vs.110%29.aspx for more details."
},
{
"code": null,
"e": 91290,
"s": 91101,
"text": "In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli"
},
{
"code": null,
"e": 91447,
"s": 91290,
"text": "To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section."
},
{
"code": null,
"e": 91586,
"s": 91447,
"text": "You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system."
},
{
"code": null,
"e": 91632,
"s": 91586,
"text": "We are working on preview 1 of .NET Core 2.0."
},
{
"code": null,
"e": 91736,
"s": 91632,
"text": "Let us now look at our current tooling by opening the command prompt and execute the following command."
},
{
"code": null,
"e": 91752,
"s": 91736,
"text": "dotnet --info \n"
},
{
"code": null,
"e": 91873,
"s": 91752,
"text": "You will see information about the currently installed version of .NET Command Line Tools on your system as shown below."
},
{
"code": null,
"e": 91994,
"s": 91873,
"text": "You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command."
},
{
"code": null,
"e": 92011,
"s": 91994,
"text": "dotnet help new\n"
},
{
"code": null,
"e": 92108,
"s": 92011,
"text": "For new command language of project, you can select like C# and F# and the type of project, etc."
},
{
"code": null,
"e": 92257,
"s": 92108,
"text": "Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install."
},
{
"code": null,
"e": 92314,
"s": 92257,
"text": "The following screenshot shows the installation process."
},
{
"code": null,
"e": 92407,
"s": 92314,
"text": "It will start the installation process. One the installation is finished, Close this dialog."
},
{
"code": null,
"e": 92466,
"s": 92407,
"text": "Open the command prompt and execute the following command."
},
{
"code": null,
"e": 92481,
"s": 92466,
"text": "dotnet --info\n"
},
{
"code": null,
"e": 92595,
"s": 92481,
"text": "You will see information of currently installed version of .NET Command Line Tools on your system as shown below."
},
{
"code": null,
"e": 92767,
"s": 92595,
"text": "You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1."
},
{
"code": null,
"e": 92784,
"s": 92767,
"text": "dotnet help new\n"
},
{
"code": null,
"e": 92854,
"s": 92784,
"text": "The command helps you download packages as well to the package cache."
},
{
"code": null,
"e": 92968,
"s": 92854,
"text": "The command opens the following webpage which contains information about the new command in .NET Core 2 preview1."
},
{
"code": null,
"e": 93070,
"s": 92968,
"text": "Let us scroll down, you can now see that we can create the .NET Core application with more templates."
},
{
"code": null,
"e": 93157,
"s": 93070,
"text": "We can now create mstest, web, mvc and webapi projects as well using the command line."
},
{
"code": null,
"e": 93482,
"s": 93157,
"text": "The .NET Core has decided to drop project.json and go back to MSBuild and *.csproj. This is something thatβs already happened in the just released .Net Core 2.0 preview1 tooling. This is fairly disappointing, because the project.json was a breath of fresh air. However, it is understandable and have many advantages as well."
},
{
"code": null,
"e": 93544,
"s": 93482,
"text": "Let us now discuss the advantages that the change brings in β"
},
{
"code": null,
"e": 93643,
"s": 93544,
"text": "It would make the transition of the existing Visual Studio solutions to .NET Core straightforward."
},
{
"code": null,
"e": 93742,
"s": 93643,
"text": "It would make the transition of the existing Visual Studio solutions to .NET Core straightforward."
},
{
"code": null,
"e": 93848,
"s": 93742,
"text": "It is a huge change and it will also enable leveraging existing investment in CI/RM based around MSBuild."
},
{
"code": null,
"e": 93954,
"s": 93848,
"text": "It is a huge change and it will also enable leveraging existing investment in CI/RM based around MSBuild."
},
{
"code": null,
"e": 94085,
"s": 93954,
"text": "During build in MSBuild, we can think of incremental compilation, resolving buildtime dependencies, configuration management, etc."
},
{
"code": null,
"e": 94216,
"s": 94085,
"text": "During build in MSBuild, we can think of incremental compilation, resolving buildtime dependencies, configuration management, etc."
},
{
"code": null,
"e": 94357,
"s": 94216,
"text": "A lot of work is required to ship dotnet cli on time, because it is no longer just about ASP.NET Core, but also console apps, UWP apps, etc."
},
{
"code": null,
"e": 94498,
"s": 94357,
"text": "A lot of work is required to ship dotnet cli on time, because it is no longer just about ASP.NET Core, but also console apps, UWP apps, etc."
},
{
"code": null,
"e": 94550,
"s": 94498,
"text": "Following are the changes in MSBuild and *.csproj β"
},
{
"code": null,
"e": 94618,
"s": 94550,
"text": "Project.json file (*.xproj) will be replaced by MSBuild (*.csproj)."
},
{
"code": null,
"e": 94686,
"s": 94618,
"text": "Project.json file (*.xproj) will be replaced by MSBuild (*.csproj)."
},
{
"code": null,
"e": 94765,
"s": 94686,
"text": "Features in project.json will start getting merged back into the the *.csproj."
},
{
"code": null,
"e": 94844,
"s": 94765,
"text": "Features in project.json will start getting merged back into the the *.csproj."
},
{
"code": null,
"e": 95011,
"s": 94844,
"text": "It is not yet clear what they are going to do about the packages list, but it was mentioned they might keep it as json under nuget.json or merge it into the *.csproj."
},
{
"code": null,
"e": 95178,
"s": 95011,
"text": "It is not yet clear what they are going to do about the packages list, but it was mentioned they might keep it as json under nuget.json or merge it into the *.csproj."
},
{
"code": null,
"e": 95272,
"s": 95178,
"text": "Supposedly that transition should be smooth and potentially automatic if using Visual Studio."
},
{
"code": null,
"e": 95366,
"s": 95272,
"text": "Supposedly that transition should be smooth and potentially automatic if using Visual Studio."
},
{
"code": null,
"e": 95457,
"s": 95366,
"text": "MSBuild is open source and available on GitHub and is bound to become fully crossplatform."
},
{
"code": null,
"e": 95548,
"s": 95457,
"text": "MSBuild is open source and available on GitHub and is bound to become fully crossplatform."
},
{
"code": null,
"e": 95623,
"s": 95548,
"text": "MSBuild will dramatically simplify and trim the structure of the *.csproj."
},
{
"code": null,
"e": 95698,
"s": 95623,
"text": "MSBuild will dramatically simplify and trim the structure of the *.csproj."
},
{
"code": null,
"e": 95913,
"s": 95698,
"text": "Microsoft is also introducing a new project system which will enable a lot of scenarios without the need for Visual Studio and the details are given on the this Url https://github.com/dotnet/roslyn-project-system/."
},
{
"code": null,
"e": 96128,
"s": 95913,
"text": "Microsoft is also introducing a new project system which will enable a lot of scenarios without the need for Visual Studio and the details are given on the this Url https://github.com/dotnet/roslyn-project-system/."
},
{
"code": null,
"e": 96265,
"s": 96128,
"text": "The goal is that even with the MSBuild setup, working with builds and project will be as seamless in Visual Studio IDE as outside of it."
},
{
"code": null,
"e": 96402,
"s": 96265,
"text": "The goal is that even with the MSBuild setup, working with builds and project will be as seamless in Visual Studio IDE as outside of it."
},
{
"code": null,
"e": 96510,
"s": 96402,
"text": "Let us now create a new console project with .NET Core preview2 tooling by executing the following command."
},
{
"code": null,
"e": 96534,
"s": 96510,
"text": "dotnet new -t console \n"
},
{
"code": null,
"e": 96605,
"s": 96534,
"text": "To see all the files created within this project, run the dir command."
},
{
"code": null,
"e": 96679,
"s": 96605,
"text": "You can see that two files are created, Program.cs and project.json file."
},
{
"code": null,
"e": 96781,
"s": 96679,
"text": "Let us now create a console app with .NET Core 2 preview1 tooling by executing the following command."
},
{
"code": null,
"e": 96802,
"s": 96781,
"text": "dotnet new console \n"
},
{
"code": null,
"e": 96993,
"s": 96802,
"text": "To see all the files created within this project, run the dir command. You can see that three files are created, Program.cs, NuGet.config and MSBuild.csproj instead of the project.json file."
},
{
"code": null,
"e": 97064,
"s": 96993,
"text": "Let us now compare project.json and MSBuild.csproj files side by side."
},
{
"code": null,
"e": 97318,
"s": 97064,
"text": "To the left, we have the file in json format while on the right, the file is in XML format. You can see that in the project.json file, inside the dependencies section, there is netcoreapp1.0, while in MSBuild.csproj file, you will see the netcoreapp2.0."
},
{
"code": null,
"e": 97534,
"s": 97318,
"text": "In this chapter, we will discuss how to restore and build your MSBuild (*.csproj) file using the command line utility. To see what commands are available in .NET Core 2.0 preview 1, let us run the following command."
},
{
"code": null,
"e": 97548,
"s": 97534,
"text": "dotnet help \n"
},
{
"code": null,
"e": 97609,
"s": 97548,
"text": "You will see all the commands like new, restore, build, etc."
},
{
"code": null,
"e": 97669,
"s": 97609,
"text": "Following is the default implementation in Program.cs file."
},
{
"code": null,
"e": 97830,
"s": 97669,
"text": "using System; \nnamespace MSBuild { \n class Program { \n static void Main(string[] args) { \n Console.WriteLine(\"Hello World!\"); \n } \n } \n} "
},
{
"code": null,
"e": 97892,
"s": 97830,
"text": "Let us now execute the following command to see the progress."
},
{
"code": null,
"e": 97906,
"s": 97892,
"text": "dotnet build\n"
},
{
"code": null,
"e": 97971,
"s": 97906,
"text": "You will see a lot of errors. These errors need to be rectified."
},
{
"code": null,
"e": 98009,
"s": 97971,
"text": "Let us now run the following command."
},
{
"code": null,
"e": 98025,
"s": 98009,
"text": "dotnet restore\n"
},
{
"code": null,
"e": 98126,
"s": 98025,
"text": "You can see that all the packages are restored. Some new folders and files have also been generated."
},
{
"code": null,
"e": 98192,
"s": 98126,
"text": "To see the directory structure, let us run the following command."
},
{
"code": null,
"e": 98202,
"s": 98192,
"text": "tree /f \n"
},
{
"code": null,
"e": 98241,
"s": 98202,
"text": "Following is the directory structure β"
},
{
"code": null,
"e": 98309,
"s": 98241,
"text": "Let us now rebuild the project running the following command again."
},
{
"code": null,
"e": 98323,
"s": 98309,
"text": "dotnet build\n"
},
{
"code": null,
"e": 98417,
"s": 98323,
"text": "Now you project will build successfully without any error(s) and MSBuild.dll is also created."
},
{
"code": null,
"e": 98471,
"s": 98417,
"text": "To see the output, let us run the following command β"
},
{
"code": null,
"e": 98484,
"s": 98471,
"text": "dotnet run \n"
},
{
"code": null,
"e": 98534,
"s": 98484,
"text": "You can see the following output on your console."
},
{
"code": null,
"e": 98735,
"s": 98534,
"text": "In this chapter, we will migrate the console application which contains the project.json file build system instead of MSBuild (*.csproj). So, we have an old project which contains the following files."
},
{
"code": null,
"e": 99020,
"s": 98735,
"text": "Now the question is, why do we need migration? This project is created using .NET Core 1.0 preview 2 tooling and now we have installed .NET Core 2.0 preview 1 tooling. Now when you build this application using .NET Core 2.0 command line utility, then you will see the following error."
},
{
"code": null,
"e": 99223,
"s": 99020,
"text": "This is because the project.json build system is no longer available in .NET Core 2.0, so we need migration so that it can work properly. To see the available commands, let us run the following command."
},
{
"code": null,
"e": 99237,
"s": 99223,
"text": "dotnet help \n"
},
{
"code": null,
"e": 99414,
"s": 99237,
"text": "In the commands section, you can see the different commands and you can also see the migrate command which will migrate a project.json based project to a MSBuild based project."
},
{
"code": null,
"e": 99452,
"s": 99414,
"text": "Let us now run the following command."
},
{
"code": null,
"e": 99469,
"s": 99452,
"text": "dotnet migrate \n"
},
{
"code": null,
"e": 99584,
"s": 99469,
"text": "You will see a summary of the migration process and here you can also see that a project is migrated successfully."
},
{
"code": null,
"e": 99655,
"s": 99584,
"text": "Let us now see the directory structure by using the following command."
},
{
"code": null,
"e": 99665,
"s": 99655,
"text": "tree /f \n"
},
{
"code": null,
"e": 99805,
"s": 99665,
"text": "You will now see the *.csproj file along with Program.cs file in the project root directory and project.json is moved to the backup folder."
},
{
"code": null,
"e": 99944,
"s": 99805,
"text": "Let us open the console.csproj file. Now you can restore and build this project using the MSBuild system by running the following command."
},
{
"code": null,
"e": 99961,
"s": 99944,
"text": "dotnet restore \n"
},
{
"code": null,
"e": 100013,
"s": 99961,
"text": "You can now see that all the packages are restored."
},
{
"code": null,
"e": 100072,
"s": 100013,
"text": "You can now build your project with the following command."
},
{
"code": null,
"e": 100087,
"s": 100072,
"text": "dotnet build \n"
},
{
"code": null,
"e": 100228,
"s": 100087,
"text": "You can now see that the project is built successfully using MSBuild and console.dll is also generated in ..\\bin\\Debug\\netcoreapp1.0 folder."
},
{
"code": null,
"e": 100294,
"s": 100228,
"text": "The following screenshot shows the directory structure and files."
},
{
"code": null,
"e": 100301,
"s": 100294,
"text": " Print"
},
{
"code": null,
"e": 100312,
"s": 100301,
"text": " Add Notes"
}
] |
Program to encrypt a string using Vigenere cipher in Python
|
Suppose we have a lowercase alphabet string text, and have another string called key. We have to find a new string where every letter in text[i] is moved to the right side with offset key[i]. Here the offset represented by key[i]'s position in the alphabet (A=0, B=1 etc.) If the letter overflows, it gets wrapped around the other side.
So, if the input is like text = "code", key = "team", then the output will be "vsdq"
To solve this, we will follow these steps β
cip := a new list
start := ASCII of 'a'
for each l from text and k from key, doshift := (ASCII of k) - startpos := start +((ASCII of l) - start + shift) mod 26insert character of pos at the end of cip
shift := (ASCII of k) - start
pos := start +((ASCII of l) - start + shift) mod 26
insert character of pos at the end of cip
join strings of cip and return
Let us see the following implementation to get better understanding β
Live Demo
class Solution:
def solve(self, text, key):
cip = []
start = ord('a')
for l, k in zip(text, key):
shift = ord(k) - start
pos = start + (ord(l) - start + shift) % 26
cip.append(chr(pos))
return ''.join([l for l in cip])
ob = Solution()
text = "code"
key = "team"
print(ob.solve(text, key))
"code", "team"
vsdq
|
[
{
"code": null,
"e": 1399,
"s": 1062,
"text": "Suppose we have a lowercase alphabet string text, and have another string called key. We have to find a new string where every letter in text[i] is moved to the right side with offset key[i]. Here the offset represented by key[i]'s position in the alphabet (A=0, B=1 etc.) If the letter overflows, it gets wrapped around the other side."
},
{
"code": null,
"e": 1484,
"s": 1399,
"text": "So, if the input is like text = \"code\", key = \"team\", then the output will be \"vsdq\""
},
{
"code": null,
"e": 1528,
"s": 1484,
"text": "To solve this, we will follow these steps β"
},
{
"code": null,
"e": 1546,
"s": 1528,
"text": "cip := a new list"
},
{
"code": null,
"e": 1568,
"s": 1546,
"text": "start := ASCII of 'a'"
},
{
"code": null,
"e": 1729,
"s": 1568,
"text": "for each l from text and k from key, doshift := (ASCII of k) - startpos := start +((ASCII of l) - start + shift) mod 26insert character of pos at the end of cip"
},
{
"code": null,
"e": 1759,
"s": 1729,
"text": "shift := (ASCII of k) - start"
},
{
"code": null,
"e": 1811,
"s": 1759,
"text": "pos := start +((ASCII of l) - start + shift) mod 26"
},
{
"code": null,
"e": 1853,
"s": 1811,
"text": "insert character of pos at the end of cip"
},
{
"code": null,
"e": 1884,
"s": 1853,
"text": "join strings of cip and return"
},
{
"code": null,
"e": 1954,
"s": 1884,
"text": "Let us see the following implementation to get better understanding β"
},
{
"code": null,
"e": 1965,
"s": 1954,
"text": " Live Demo"
},
{
"code": null,
"e": 2308,
"s": 1965,
"text": "class Solution:\n def solve(self, text, key):\n cip = []\n start = ord('a')\n for l, k in zip(text, key):\n shift = ord(k) - start\n pos = start + (ord(l) - start + shift) % 26\n cip.append(chr(pos))\n return ''.join([l for l in cip])\nob = Solution()\ntext = \"code\"\nkey = \"team\"\nprint(ob.solve(text, key))"
},
{
"code": null,
"e": 2323,
"s": 2308,
"text": "\"code\", \"team\""
},
{
"code": null,
"e": 2328,
"s": 2323,
"text": "vsdq"
}
] |
Program for converting hours into minutes and seconds - GeeksforGeeks
|
01 Apr, 2021
Given an integer n which is the number of hours, the task is to convert it into minutes and seconds.Examples:
Input: 5 Output: Minutes = 300, Seconds = 18000Input: 2 Output: Minutes = 120, Seconds = 7200
Approach:
h hours = h * 60 minutes as 1 hour = 60 minutes.
Similarly h hours = h * 3600 seconds.
Note: To convert m minutes back into hours, do n / 60 and for s seconds s / 3600.Below is the implementation of the above approach:
C++
Java
C#
PHP
Python3
Javascript
// C++ program to convert hours// into minutes and seconds#include <bits/stdc++.h>using namespace std; // Function to convert hours// into minutes and secondsvoid ConvertHours(int n){ long long int minutes, seconds; minutes = n * 60; seconds = n * 3600; cout << "Minutes = " << minutes << ", Seconds = " << seconds << endl;} // Driver codeint main(){ int n = 5; ConvertHours(n); return 0;}
// Java program to convert hours// into minutes and seconds import java.io.*; class GFG { // Function to convert hours// into minutes and seconds static void ConvertHours(int n){ int minutes, seconds; minutes = n * 60; seconds = n * 3600; System.out.println( "Minutes = " + minutes + ", Seconds = " + seconds);} // Driver code public static void main (String[] args) { int n = 5; ConvertHours(n); } }// This code is contributed by inder_verma..
// C# program to convert hours// into minutes and secondsusing System; class GFG{ // Function to convert hours into// minutes and secondsstatic void ConvertHours(int n){int minutes, seconds; minutes = n * 60; seconds = n * 3600; Console.WriteLine("Minutes = " + minutes + ", Seconds = " + seconds);} // Driver codepublic static void Main (){ int n = 5; ConvertHours(n);}} // This code is contributed by Ryuga
<?php// PHP program to convert hours// into minutes and seconds // Function to convert hours// into minutes and secondsfunction ConvertHours($n){ $minutes = $n * 60; $seconds = $n * 3600; echo "Minutes = " . $minutes . ", Seconds = " . $seconds . "\n";} // Driver code$n = 5;ConvertHours($n); // This code is contributed// by Akanksha Rai?>
# C++ program to convert hours# into minutes and seconds # Function to convert hours# into minutes and secondsdef ConvertHours(n): minutes = n * 60; seconds = n * 3600; print("Minutes = ", minutes \ ,", Seconds = " , seconds); # Driver coden = 5;ConvertHours(n); # This code contributed by Rajput-Ji
<script> // JavaScript program to convert hours// into minutes and seconds // Function to convert hours // into minutes and seconds function ConvertHours(n) { var minutes, seconds; minutes = n * 60; seconds = n * 3600; document.write("Minutes = " + minutes + ", Seconds = " + seconds); } // Driver code var n = 5; ConvertHours(n); // This code contributed by Rajput-Ji </script>
Minutes = 300, Seconds = 18000
Time Complexity : O(1)
inderDuMCA
ankthon
Akanksha_Rai
VishalBachchas
Rajput-Ji
date-time-program
Technical Scripter 2018
C++ Programs
School Programming
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
cin in C++
delete keyword in C++
Shallow Copy and Deep Copy in C++
Check if given number is perfect square
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects
|
[
{
"code": null,
"e": 24505,
"s": 24477,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 24617,
"s": 24505,
"text": "Given an integer n which is the number of hours, the task is to convert it into minutes and seconds.Examples: "
},
{
"code": null,
"e": 24713,
"s": 24617,
"text": "Input: 5 Output: Minutes = 300, Seconds = 18000Input: 2 Output: Minutes = 120, Seconds = 7200 "
},
{
"code": null,
"e": 24727,
"s": 24715,
"text": "Approach: "
},
{
"code": null,
"e": 24776,
"s": 24727,
"text": "h hours = h * 60 minutes as 1 hour = 60 minutes."
},
{
"code": null,
"e": 24814,
"s": 24776,
"text": "Similarly h hours = h * 3600 seconds."
},
{
"code": null,
"e": 24948,
"s": 24814,
"text": "Note: To convert m minutes back into hours, do n / 60 and for s seconds s / 3600.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 24952,
"s": 24948,
"text": "C++"
},
{
"code": null,
"e": 24957,
"s": 24952,
"text": "Java"
},
{
"code": null,
"e": 24960,
"s": 24957,
"text": "C#"
},
{
"code": null,
"e": 24964,
"s": 24960,
"text": "PHP"
},
{
"code": null,
"e": 24972,
"s": 24964,
"text": "Python3"
},
{
"code": null,
"e": 24983,
"s": 24972,
"text": "Javascript"
},
{
"code": "// C++ program to convert hours// into minutes and seconds#include <bits/stdc++.h>using namespace std; // Function to convert hours// into minutes and secondsvoid ConvertHours(int n){ long long int minutes, seconds; minutes = n * 60; seconds = n * 3600; cout << \"Minutes = \" << minutes << \", Seconds = \" << seconds << endl;} // Driver codeint main(){ int n = 5; ConvertHours(n); return 0;}",
"e": 25404,
"s": 24983,
"text": null
},
{
"code": "// Java program to convert hours// into minutes and seconds import java.io.*; class GFG { // Function to convert hours// into minutes and seconds static void ConvertHours(int n){ int minutes, seconds; minutes = n * 60; seconds = n * 3600; System.out.println( \"Minutes = \" + minutes + \", Seconds = \" + seconds);} // Driver code public static void main (String[] args) { int n = 5; ConvertHours(n); } }// This code is contributed by inder_verma..",
"e": 25884,
"s": 25404,
"text": null
},
{
"code": "// C# program to convert hours// into minutes and secondsusing System; class GFG{ // Function to convert hours into// minutes and secondsstatic void ConvertHours(int n){int minutes, seconds; minutes = n * 60; seconds = n * 3600; Console.WriteLine(\"Minutes = \" + minutes + \", Seconds = \" + seconds);} // Driver codepublic static void Main (){ int n = 5; ConvertHours(n);}} // This code is contributed by Ryuga",
"e": 26331,
"s": 25884,
"text": null
},
{
"code": "<?php// PHP program to convert hours// into minutes and seconds // Function to convert hours// into minutes and secondsfunction ConvertHours($n){ $minutes = $n * 60; $seconds = $n * 3600; echo \"Minutes = \" . $minutes . \", Seconds = \" . $seconds . \"\\n\";} // Driver code$n = 5;ConvertHours($n); // This code is contributed// by Akanksha Rai?>",
"e": 26690,
"s": 26331,
"text": null
},
{
"code": "# C++ program to convert hours# into minutes and seconds # Function to convert hours# into minutes and secondsdef ConvertHours(n): minutes = n * 60; seconds = n * 3600; print(\"Minutes = \", minutes \\ ,\", Seconds = \" , seconds); # Driver coden = 5;ConvertHours(n); # This code contributed by Rajput-Ji",
"e": 27015,
"s": 26690,
"text": null
},
{
"code": "<script> // JavaScript program to convert hours// into minutes and seconds // Function to convert hours // into minutes and seconds function ConvertHours(n) { var minutes, seconds; minutes = n * 60; seconds = n * 3600; document.write(\"Minutes = \" + minutes + \", Seconds = \" + seconds); } // Driver code var n = 5; ConvertHours(n); // This code contributed by Rajput-Ji </script>",
"e": 27456,
"s": 27015,
"text": null
},
{
"code": null,
"e": 27487,
"s": 27456,
"text": "Minutes = 300, Seconds = 18000"
},
{
"code": null,
"e": 27513,
"s": 27489,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 27524,
"s": 27513,
"text": "inderDuMCA"
},
{
"code": null,
"e": 27532,
"s": 27524,
"text": "ankthon"
},
{
"code": null,
"e": 27545,
"s": 27532,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27560,
"s": 27545,
"text": "VishalBachchas"
},
{
"code": null,
"e": 27570,
"s": 27560,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 27588,
"s": 27570,
"text": "date-time-program"
},
{
"code": null,
"e": 27612,
"s": 27588,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27625,
"s": 27612,
"text": "C++ Programs"
},
{
"code": null,
"e": 27644,
"s": 27625,
"text": "School Programming"
},
{
"code": null,
"e": 27663,
"s": 27644,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27761,
"s": 27663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27770,
"s": 27761,
"text": "Comments"
},
{
"code": null,
"e": 27783,
"s": 27770,
"text": "Old Comments"
},
{
"code": null,
"e": 27809,
"s": 27783,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27820,
"s": 27809,
"text": "cin in C++"
},
{
"code": null,
"e": 27842,
"s": 27820,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 27876,
"s": 27842,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 27916,
"s": 27876,
"text": "Check if given number is perfect square"
},
{
"code": null,
"e": 27934,
"s": 27916,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27950,
"s": 27934,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 27975,
"s": 27950,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 27994,
"s": 27975,
"text": "Inheritance in C++"
}
] |
Python - Construct dictionary Key-Value pairs separated by delimiter - GeeksforGeeks
|
01 Jul, 2021
Given a String with key-value pairs separated by delim, construct a dictionary.
Input : test_str = βgfg#3, is#9, best#10β, delim = β#β Output : {βgfgβ: β3β, βisβ: β9β, βbestβ: β10β} Explanation : gfg paired with 3, as separated with # delim.Input : test_str = βgfg.10β, delim = β.β Output : {βgfgβ: β10β} Explanation : gfg paired with 10, as separated with . delim.
Method #1 : Using split() + loop
In this, we perform a split on comma, to get key value pairs, and again a split on custom delim to get key value pairs separated. Then assigned to dictionary using loop.
Python3
# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + loop # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint("The original string is : " + str(test_str)) # initializing delimdelim = "$" # split by comma for getting different dict valuesdicts = test_str.split(', ') res = dict()for sub in dicts: # 2nd split for forming Key-Values for dictionary res[sub.split(delim)[0]] = sub.split(delim)[1] # printing resultprint("The constructed dictionary : " + str(res))
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}
Method #2 : Using dictionary comprehension + split()
Similar to above method, just the difference being that dictionary comprehension is used for performing task of dictionary construction.
Python3
# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + dictionary comprehension # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint("The original string is : " + str(test_str)) # initializing delimdelim = "$" # split by comma for getting different dict valuesdicts = test_str.split(', ') # dictionary comprehension to form dictionaryres = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts} # printing resultprint("The constructed dictionary : " + str(res))
The original string is : gfg$3, is$9, best$10
The constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}
surinderdawra388
Python dictionary-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n01 Jul, 2021"
},
{
"code": null,
"e": 23981,
"s": 23901,
"text": "Given a String with key-value pairs separated by delim, construct a dictionary."
},
{
"code": null,
"e": 24269,
"s": 23981,
"text": "Input : test_str = βgfg#3, is#9, best#10β, delim = β#β Output : {βgfgβ: β3β, βisβ: β9β, βbestβ: β10β} Explanation : gfg paired with 3, as separated with # delim.Input : test_str = βgfg.10β, delim = β.β Output : {βgfgβ: β10β} Explanation : gfg paired with 10, as separated with . delim. "
},
{
"code": null,
"e": 24302,
"s": 24269,
"text": "Method #1 : Using split() + loop"
},
{
"code": null,
"e": 24472,
"s": 24302,
"text": "In this, we perform a split on comma, to get key value pairs, and again a split on custom delim to get key value pairs separated. Then assigned to dictionary using loop."
},
{
"code": null,
"e": 24480,
"s": 24472,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + loop # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing delimdelim = \"$\" # split by comma for getting different dict valuesdicts = test_str.split(', ') res = dict()for sub in dicts: # 2nd split for forming Key-Values for dictionary res[sub.split(delim)[0]] = sub.split(delim)[1] # printing resultprint(\"The constructed dictionary : \" + str(res))",
"e": 25045,
"s": 24480,
"text": null
},
{
"code": null,
"e": 25158,
"s": 25045,
"text": "The original string is : gfg$3, is$9, best$10\nThe constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}"
},
{
"code": null,
"e": 25211,
"s": 25158,
"text": "Method #2 : Using dictionary comprehension + split()"
},
{
"code": null,
"e": 25348,
"s": 25211,
"text": "Similar to above method, just the difference being that dictionary comprehension is used for performing task of dictionary construction."
},
{
"code": null,
"e": 25356,
"s": 25348,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Contruct dictionary Key-Value pairs separated by delim# Using split() + dictionary comprehension # initializing stringstest_str = 'gfg$3, is$9, best$10' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing delimdelim = \"$\" # split by comma for getting different dict valuesdicts = test_str.split(', ') # dictionary comprehension to form dictionaryres = {sub.split(delim)[0] : sub.split(delim)[1] for sub in dicts} # printing resultprint(\"The constructed dictionary : \" + str(res))",
"e": 25918,
"s": 25356,
"text": null
},
{
"code": null,
"e": 26031,
"s": 25918,
"text": "The original string is : gfg$3, is$9, best$10\nThe constructed dictionary : {'gfg': '3', 'is': '9', 'best': '10'}"
},
{
"code": null,
"e": 26048,
"s": 26031,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26075,
"s": 26048,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 26098,
"s": 26075,
"text": "Python string-programs"
},
{
"code": null,
"e": 26105,
"s": 26098,
"text": "Python"
},
{
"code": null,
"e": 26121,
"s": 26105,
"text": "Python Programs"
},
{
"code": null,
"e": 26219,
"s": 26121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26228,
"s": 26219,
"text": "Comments"
},
{
"code": null,
"e": 26241,
"s": 26228,
"text": "Old Comments"
},
{
"code": null,
"e": 26273,
"s": 26241,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26329,
"s": 26273,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26371,
"s": 26329,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26413,
"s": 26371,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26449,
"s": 26413,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26471,
"s": 26449,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26510,
"s": 26471,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26556,
"s": 26510,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 26613,
"s": 26556,
"text": "Python program to check whether a number is Prime or not"
}
] |
Deep Learning using Transfer Learning -Python Code for ResNet50 | by Renu Khandelwal | Towards Data Science
|
This is the second part of the series where we will write code to apply Transfer Learning using ResNet50 . Here we will use transfer learning suing a Pre-trained ResNet50 model and then fine-tune ResNet50.
Transfer Learning Concept part 1
For code implementation, we will use ResNet50. ResNet is short for Residual Network. It is a 50 layer Residual Network
When we add more layers to our deep neural networks, the performance becomes stagnant or starts to degrade. This happens due to vanishing gradient problem. When gradients are backpropagated through the deep neural network and repeatedly multiplied, this makes gradients extremely small causing vanishing gradient problem.
ResNet solves the vanishing gradient problem by using Identity shortcut connection or skip connections that skip one or more layers. Shortcut connections are connecting output on layer N to the input of layer N+Z
We will use Cats and Dogs data set for demonstrating Transfer Learning using
Pre-trained ResNet50 model as a feature extractor
Fine-tuning the pre-trained model ResNet50
Importing the basic libraries. We will import additional libraries when required
import globimport numpy as npimport pandas as pdimport osimport shutil import matplotlib.pyplot as pltfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img%matplotlib inline
I have stored all the images of cats and dogs in the folder dogs-vs-cats folder. We read the cat and dog files. We have 25003 images each of cats and dogs
files = glob.glob('E:\\Data\\Images\\dogs-vs-cats\\*') cat_files = [fn for fn in files if 'cat' in fn] dog_files = [fn for fn in files if 'dog' in fn] len(cat_files), len(dog_files)
I am training on a smaller set of data so reducing the size of my training, test and validation data set. This step is not required if you want to train on all the images.
Train data set will have 1500 images each of cats and dogs, Test data set will have 500 images each of cats and dogs and Validation data set will also have 500 images each of cats and dogs
cat_train = np.random.choice(cat_files, size=1500, replace=False) dog_train = np.random.choice(dog_files, size=1500, replace=False) cat_files = list(set(cat_files) β set(cat_train)) dog_files = list(set(dog_files) β set(dog_train)) cat_val = np.random.choice(cat_files, size=500, replace=False) dog_val = np.random.choice(dog_files, size=500, replace=False) cat_files = list(set(cat_files) β set(cat_val)) dog_files = list(set(dog_files) β set(dog_val)) cat_test = np.random.choice(cat_files, size=500, replace=False) dog_test = np.random.choice(dog_files, size=500, replace=False) print(βCat datasets:β, cat_train.shape, cat_val.shape, cat_test.shape) print(βDog datasets:β, dog_train.shape, dog_val.shape, dog_test.shape)
Loading the training and validation data set. The dimension of our image will be 300 by 300 pixel
IMG_WIDTH=300IMG_HEIGHT=300IMG_DIM = (IMG_WIDTH, IMG_HEIGHT)train_files = glob.glob(βE:\\Data\\Images\\dogs-vs-cats\\training_data\\*β)train_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in train_files]train_imgs = np.array(train_imgs)train_labels = [fn.split(β\\β)[-1].split(β.β)[0].strip() for fn in train_files]validation_files = glob.glob(βE:\\Data\\Images\\dogs-vs-cats\\validation_data\\*β)validation_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in validation_files]validation_imgs = np.array(validation_imgs)validation_labels = [fn.split(β\\β)[-1].split(β.β)[0].strip() for fn in validation_files]print(βTrain dataset shape:β, train_imgs.shape, β\tValidation dataset shape:β, validation_imgs.shape)
Each image is now of size 300 x 300 and has three channels for Red, Green, and Blue (RGB).
Pixel values for images are between 0 and 255. Deep Neural networks work well with smaller input values. Scaling each image with values between 0 and 1.
train_imgs_scaled = train_imgs.astype(βfloat32β) validation_imgs_scaled = validation_imgs.astype(βfloat32β) train_imgs_scaled /= 255 validation_imgs_scaled /= 255 # visualize a sample image print(train_imgs[0].shape) array_to_img(train_imgs[0]
Encoding text category labels of Cats and Dogs
# encode text category labels from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(train_labels) train_labels_enc = le.transform(train_labels) validation_labels_enc = le.transform(validation_labels) print(train_labels[1495:1505], train_labels_enc[1495:1505])
Keras framework has an excellent utility called ImageDataGenerator. It generates batches of tensor image data with real-time data augmentation.
For our training and validation datasets, we will zoom the image randomly by a factor of 0.3 using the zoom_range parameter. We rotate the image randomly by 50 degrees using the rotation_range parameter. Translating the image randomly horizontally or vertically by a 0.2 factor of the imageβs width or height using the width_shift_range and the height_shift_range parameters. Applying shear-based transformations randomly using the shear_range parameter. Randomly flipping half of the images horizontally using the horizontal_flip parameter. Leveraging the fill_mode parameter to fill in new pixels for images after we apply any of the preceding operations (especially rotation or translation). In this case, we just fill in the new pixels with their nearest surrounding pixel values.
train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, rotation_range=50, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, horizontal_flip=True, fill_mode=βnearestβ)val_datagen = ImageDataGenerator(rescale=1./255)
Letβs see how some of the augmented images looks like. We will take two sample images from our training dataset to illustrate the same. The first image is an image of a cat and the second image is of a dog
img_id = 2500cat_generator = train_datagen.flow(train_imgs[img_id:img_id+1], train_labels[img_id:img_id+1], batch_size=1) cat = [next(cat_generator) for i in range(0,5)] fig, ax = plt.subplots(1,5, figsize=(16, 6))print(βLabels:β, [item[1][0] for item in cat]) l = [ax[i].imshow(cat[i][0][0]) for i in range(0,5)]
img_id = 4001 dog_generator = train_datagen.flow(train_imgs[img_id:img_id+1], train_labels[img_id:img_id+1], batch_size=1) dog = [next(dog_generator) for i in range(0,5)] fig, ax = plt.subplots(1,5, figsize=(15, 6)) print(βLabels:β, [item[1][0] for item in dog]) l = [ax[i].imshow(dog[i][0][0]) for i in range(0,5)]
For our test generator, we need to send the original test images to the model for evaluation. We just scale the image pixels between 0 and 1 and do not apply any transformations.
We just apply image augmentation transformations only to our training set images and validation images
train_generator = train_datagen.flow(train_imgs, train_labels_enc,batch_size=30)val_generator = val_datagen.flow(validation_imgs, validation_labels_enc, batch_size=30)
We use ResNet50 deep learning model as the pre-trained model for feature extraction for Transfer Learning.
To implement Transfer learning, we will remove the last predicting layer of the pre-trained ResNet50 model and replace them with our own predicting layers. FC-T1 and FC_T2 as shown below
Weights of ResNet50 pre-trained model is used as feature extractor
Weights of the pre-trained model are frozen and are not updated during the training
We do not want to load the last fully connected layers which act as the classifier. We accomplish that by using βinclude_top=Falseβ. We do this so that we can add our own fully connected layers on top of the ResNet50 model for our task-specific classification.
We freeze the weights of the model by setting trainable as βFalseβ. This stops any updates to the pre-trained weights during training We do not want to train ResNet layers as we want to leverage the knowledge learned by the deep neural network trained from the previous data set which in our case is βimagenetβ
from keras.applications.resnet50 import ResNet50from keras.models import Modelimport kerasrestnet = ResNet50(include_top=False, weights='imagenet', input_shape=(IMG_HEIGHT,IMG_WIDTH,3))output = restnet.layers[-1].outputoutput = keras.layers.Flatten()(output)restnet = Model(restnet.input, output=output)for layer in restnet.layers: layer.trainable = Falserestnet.summary()
We now create our model using Transfer Learning using Pre-trained ResNet50 by adding our own fully connected layer and the final classifier using sigmoid activation function.
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayerfrom keras.models import Sequentialfrom keras import optimizersmodel = Sequential()model.add(restnet)model.add(Dense(512, activation='relu', input_dim=input_shape))model.add(Dropout(0.3))model.add(Dense(512, activation='relu'))model.add(Dropout(0.3))model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=2e-5), metrics=['accuracy'])model.summary()
We see that the weights of ResNet50 are not trainable as we had frozen them.
we now run the model
history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=val_generator, validation_steps=50, verbose=1)
Saving the trained weights
model.save(βcats_dogs_tlearn_img_aug_cnn_restnet50.h5β)
We can use deep neural networks like VGG-16, VGG-19, Inception V3, ResNet-50, Xception as pre-trained model
To implement Transfer learning with fine-tuning, we remove the last predicting layer of the pre-trained model and replace them with our own predicting layers. FC-T1 and FC_T2 as shown below.
Initial lower layers of the network learn very generic features from the pre-trained model. To achieve this initial layers weights of pre-trained models frozen and not updated during the training
Higher layers are used for learning task-specific features. Higher layers of pre-trained models are trainable or fine-tuned
Improves performance with less training time
We already have the data set created with image augmentation and we have created the base ResNet50 model.
we will now fine-tune Transfer learning with image augmentation using ResNet50. We do this by unfreezing a few of the last convolution blocks while keeping the first early conv blocks frozen. This will help us to learn very generic features using early layers. Higher layers of pre-trained models will be trainable or fine-tuned.
restnet.trainable = Trueset_trainable = Falsefor layer in restnet.layers: if layer.name in ['res5c_branch2b', 'res5c_branch2c', 'activation_97']: set_trainable = True if set_trainable: layer.trainable = True else: layer.trainable = Falselayers = [(layer, layer.name, layer.trainable) for layer in restnet.layers]pd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])
We see that we have set the training for early layers of ResNet50 to false and the last few layers of ResNet50 are now trainable.
we now add our own fully connected layer and classifier on top of the ResNet50. We have already removed the last fully connected layer and the classifier layer from ResNet50
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayerfrom keras.models import Sequentialfrom keras import optimizersmodel_finetuned = Sequential()model_finetuned.add(restnet)model_finetuned.add(Dense(512, activation='relu', input_dim=input_shape))model_finetuned.add(Dropout(0.3))model_finetuned.add(Dense(512, activation='relu'))model_finetuned.add(Dropout(0.3))model_finetuned.add(Dense(1, activation='sigmoid'))model_finetuned.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-5), metrics=['accuracy'])model_finetuned.summary()
We finally run the model
history_1 = model_finetuned.fit_generator(train_generator, steps_per_epoch=100, epochs=2, validation_data=val_generator, validation_steps=100, verbose=1)
saving the weights of the fine-tuned model
model.save(βcats_dogs_tlearn_finetune_img_aug_restnet50.h5β)
A Survey on Transfer Learning by Sinno Jialin Pan and Qiang Yang
A comprehensive hands-on-guide-to-transfer-learning-with-real-world-applications-in-deep-learning
GitHub for Hands-on Transfer Learning with Python
|
[
{
"code": null,
"e": 378,
"s": 172,
"text": "This is the second part of the series where we will write code to apply Transfer Learning using ResNet50 . Here we will use transfer learning suing a Pre-trained ResNet50 model and then fine-tune ResNet50."
},
{
"code": null,
"e": 411,
"s": 378,
"text": "Transfer Learning Concept part 1"
},
{
"code": null,
"e": 530,
"s": 411,
"text": "For code implementation, we will use ResNet50. ResNet is short for Residual Network. It is a 50 layer Residual Network"
},
{
"code": null,
"e": 852,
"s": 530,
"text": "When we add more layers to our deep neural networks, the performance becomes stagnant or starts to degrade. This happens due to vanishing gradient problem. When gradients are backpropagated through the deep neural network and repeatedly multiplied, this makes gradients extremely small causing vanishing gradient problem."
},
{
"code": null,
"e": 1065,
"s": 852,
"text": "ResNet solves the vanishing gradient problem by using Identity shortcut connection or skip connections that skip one or more layers. Shortcut connections are connecting output on layer N to the input of layer N+Z"
},
{
"code": null,
"e": 1142,
"s": 1065,
"text": "We will use Cats and Dogs data set for demonstrating Transfer Learning using"
},
{
"code": null,
"e": 1192,
"s": 1142,
"text": "Pre-trained ResNet50 model as a feature extractor"
},
{
"code": null,
"e": 1235,
"s": 1192,
"text": "Fine-tuning the pre-trained model ResNet50"
},
{
"code": null,
"e": 1316,
"s": 1235,
"text": "Importing the basic libraries. We will import additional libraries when required"
},
{
"code": null,
"e": 1531,
"s": 1316,
"text": "import globimport numpy as npimport pandas as pdimport osimport shutil import matplotlib.pyplot as pltfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img%matplotlib inline"
},
{
"code": null,
"e": 1686,
"s": 1531,
"text": "I have stored all the images of cats and dogs in the folder dogs-vs-cats folder. We read the cat and dog files. We have 25003 images each of cats and dogs"
},
{
"code": null,
"e": 1869,
"s": 1686,
"text": "files = glob.glob('E:\\\\Data\\\\Images\\\\dogs-vs-cats\\\\*') cat_files = [fn for fn in files if 'cat' in fn] dog_files = [fn for fn in files if 'dog' in fn] len(cat_files), len(dog_files)"
},
{
"code": null,
"e": 2041,
"s": 1869,
"text": "I am training on a smaller set of data so reducing the size of my training, test and validation data set. This step is not required if you want to train on all the images."
},
{
"code": null,
"e": 2230,
"s": 2041,
"text": "Train data set will have 1500 images each of cats and dogs, Test data set will have 500 images each of cats and dogs and Validation data set will also have 500 images each of cats and dogs"
},
{
"code": null,
"e": 2957,
"s": 2230,
"text": "cat_train = np.random.choice(cat_files, size=1500, replace=False) dog_train = np.random.choice(dog_files, size=1500, replace=False) cat_files = list(set(cat_files) β set(cat_train)) dog_files = list(set(dog_files) β set(dog_train)) cat_val = np.random.choice(cat_files, size=500, replace=False) dog_val = np.random.choice(dog_files, size=500, replace=False) cat_files = list(set(cat_files) β set(cat_val)) dog_files = list(set(dog_files) β set(dog_val)) cat_test = np.random.choice(cat_files, size=500, replace=False) dog_test = np.random.choice(dog_files, size=500, replace=False) print(βCat datasets:β, cat_train.shape, cat_val.shape, cat_test.shape) print(βDog datasets:β, dog_train.shape, dog_val.shape, dog_test.shape)"
},
{
"code": null,
"e": 3055,
"s": 2957,
"text": "Loading the training and validation data set. The dimension of our image will be 300 by 300 pixel"
},
{
"code": null,
"e": 3801,
"s": 3055,
"text": "IMG_WIDTH=300IMG_HEIGHT=300IMG_DIM = (IMG_WIDTH, IMG_HEIGHT)train_files = glob.glob(βE:\\\\Data\\\\Images\\\\dogs-vs-cats\\\\training_data\\\\*β)train_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in train_files]train_imgs = np.array(train_imgs)train_labels = [fn.split(β\\\\β)[-1].split(β.β)[0].strip() for fn in train_files]validation_files = glob.glob(βE:\\\\Data\\\\Images\\\\dogs-vs-cats\\\\validation_data\\\\*β)validation_imgs = [img_to_array(load_img(img, target_size=IMG_DIM)) for img in validation_files]validation_imgs = np.array(validation_imgs)validation_labels = [fn.split(β\\\\β)[-1].split(β.β)[0].strip() for fn in validation_files]print(βTrain dataset shape:β, train_imgs.shape, β\\tValidation dataset shape:β, validation_imgs.shape)"
},
{
"code": null,
"e": 3892,
"s": 3801,
"text": "Each image is now of size 300 x 300 and has three channels for Red, Green, and Blue (RGB)."
},
{
"code": null,
"e": 4045,
"s": 3892,
"text": "Pixel values for images are between 0 and 255. Deep Neural networks work well with smaller input values. Scaling each image with values between 0 and 1."
},
{
"code": null,
"e": 4290,
"s": 4045,
"text": "train_imgs_scaled = train_imgs.astype(βfloat32β) validation_imgs_scaled = validation_imgs.astype(βfloat32β) train_imgs_scaled /= 255 validation_imgs_scaled /= 255 # visualize a sample image print(train_imgs[0].shape) array_to_img(train_imgs[0]"
},
{
"code": null,
"e": 4337,
"s": 4290,
"text": "Encoding text category labels of Cats and Dogs"
},
{
"code": null,
"e": 4619,
"s": 4337,
"text": "# encode text category labels from sklearn.preprocessing import LabelEncoder le = LabelEncoder() le.fit(train_labels) train_labels_enc = le.transform(train_labels) validation_labels_enc = le.transform(validation_labels) print(train_labels[1495:1505], train_labels_enc[1495:1505])"
},
{
"code": null,
"e": 4763,
"s": 4619,
"text": "Keras framework has an excellent utility called ImageDataGenerator. It generates batches of tensor image data with real-time data augmentation."
},
{
"code": null,
"e": 5548,
"s": 4763,
"text": "For our training and validation datasets, we will zoom the image randomly by a factor of 0.3 using the zoom_range parameter. We rotate the image randomly by 50 degrees using the rotation_range parameter. Translating the image randomly horizontally or vertically by a 0.2 factor of the imageβs width or height using the width_shift_range and the height_shift_range parameters. Applying shear-based transformations randomly using the shear_range parameter. Randomly flipping half of the images horizontally using the horizontal_flip parameter. Leveraging the fill_mode parameter to fill in new pixels for images after we apply any of the preceding operations (especially rotation or translation). In this case, we just fill in the new pixels with their nearest surrounding pixel values."
},
{
"code": null,
"e": 5790,
"s": 5548,
"text": "train_datagen = ImageDataGenerator(rescale=1./255, zoom_range=0.3, rotation_range=50, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, horizontal_flip=True, fill_mode=βnearestβ)val_datagen = ImageDataGenerator(rescale=1./255)"
},
{
"code": null,
"e": 5996,
"s": 5790,
"text": "Letβs see how some of the augmented images looks like. We will take two sample images from our training dataset to illustrate the same. The first image is an image of a cat and the second image is of a dog"
},
{
"code": null,
"e": 6312,
"s": 5996,
"text": "img_id = 2500cat_generator = train_datagen.flow(train_imgs[img_id:img_id+1], train_labels[img_id:img_id+1], batch_size=1) cat = [next(cat_generator) for i in range(0,5)] fig, ax = plt.subplots(1,5, figsize=(16, 6))print(βLabels:β, [item[1][0] for item in cat]) l = [ax[i].imshow(cat[i][0][0]) for i in range(0,5)]"
},
{
"code": null,
"e": 6630,
"s": 6312,
"text": "img_id = 4001 dog_generator = train_datagen.flow(train_imgs[img_id:img_id+1], train_labels[img_id:img_id+1], batch_size=1) dog = [next(dog_generator) for i in range(0,5)] fig, ax = plt.subplots(1,5, figsize=(15, 6)) print(βLabels:β, [item[1][0] for item in dog]) l = [ax[i].imshow(dog[i][0][0]) for i in range(0,5)]"
},
{
"code": null,
"e": 6809,
"s": 6630,
"text": "For our test generator, we need to send the original test images to the model for evaluation. We just scale the image pixels between 0 and 1 and do not apply any transformations."
},
{
"code": null,
"e": 6912,
"s": 6809,
"text": "We just apply image augmentation transformations only to our training set images and validation images"
},
{
"code": null,
"e": 7080,
"s": 6912,
"text": "train_generator = train_datagen.flow(train_imgs, train_labels_enc,batch_size=30)val_generator = val_datagen.flow(validation_imgs, validation_labels_enc, batch_size=30)"
},
{
"code": null,
"e": 7187,
"s": 7080,
"text": "We use ResNet50 deep learning model as the pre-trained model for feature extraction for Transfer Learning."
},
{
"code": null,
"e": 7374,
"s": 7187,
"text": "To implement Transfer learning, we will remove the last predicting layer of the pre-trained ResNet50 model and replace them with our own predicting layers. FC-T1 and FC_T2 as shown below"
},
{
"code": null,
"e": 7441,
"s": 7374,
"text": "Weights of ResNet50 pre-trained model is used as feature extractor"
},
{
"code": null,
"e": 7525,
"s": 7441,
"text": "Weights of the pre-trained model are frozen and are not updated during the training"
},
{
"code": null,
"e": 7786,
"s": 7525,
"text": "We do not want to load the last fully connected layers which act as the classifier. We accomplish that by using βinclude_top=Falseβ. We do this so that we can add our own fully connected layers on top of the ResNet50 model for our task-specific classification."
},
{
"code": null,
"e": 8097,
"s": 7786,
"text": "We freeze the weights of the model by setting trainable as βFalseβ. This stops any updates to the pre-trained weights during training We do not want to train ResNet layers as we want to leverage the knowledge learned by the deep neural network trained from the previous data set which in our case is βimagenetβ"
},
{
"code": null,
"e": 8473,
"s": 8097,
"text": "from keras.applications.resnet50 import ResNet50from keras.models import Modelimport kerasrestnet = ResNet50(include_top=False, weights='imagenet', input_shape=(IMG_HEIGHT,IMG_WIDTH,3))output = restnet.layers[-1].outputoutput = keras.layers.Flatten()(output)restnet = Model(restnet.input, output=output)for layer in restnet.layers: layer.trainable = Falserestnet.summary()"
},
{
"code": null,
"e": 8648,
"s": 8473,
"text": "We now create our model using Transfer Learning using Pre-trained ResNet50 by adding our own fully connected layer and the final classifier using sigmoid activation function."
},
{
"code": null,
"e": 9165,
"s": 8648,
"text": "from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayerfrom keras.models import Sequentialfrom keras import optimizersmodel = Sequential()model.add(restnet)model.add(Dense(512, activation='relu', input_dim=input_shape))model.add(Dropout(0.3))model.add(Dense(512, activation='relu'))model.add(Dropout(0.3))model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=2e-5), metrics=['accuracy'])model.summary()"
},
{
"code": null,
"e": 9242,
"s": 9165,
"text": "We see that the weights of ResNet50 are not trainable as we had frozen them."
},
{
"code": null,
"e": 9263,
"s": 9242,
"text": "we now run the model"
},
{
"code": null,
"e": 9555,
"s": 9263,
"text": "history = model.fit_generator(train_generator, steps_per_epoch=100, epochs=100, validation_data=val_generator, validation_steps=50, verbose=1)"
},
{
"code": null,
"e": 9582,
"s": 9555,
"text": "Saving the trained weights"
},
{
"code": null,
"e": 9638,
"s": 9582,
"text": "model.save(βcats_dogs_tlearn_img_aug_cnn_restnet50.h5β)"
},
{
"code": null,
"e": 9746,
"s": 9638,
"text": "We can use deep neural networks like VGG-16, VGG-19, Inception V3, ResNet-50, Xception as pre-trained model"
},
{
"code": null,
"e": 9937,
"s": 9746,
"text": "To implement Transfer learning with fine-tuning, we remove the last predicting layer of the pre-trained model and replace them with our own predicting layers. FC-T1 and FC_T2 as shown below."
},
{
"code": null,
"e": 10133,
"s": 9937,
"text": "Initial lower layers of the network learn very generic features from the pre-trained model. To achieve this initial layers weights of pre-trained models frozen and not updated during the training"
},
{
"code": null,
"e": 10257,
"s": 10133,
"text": "Higher layers are used for learning task-specific features. Higher layers of pre-trained models are trainable or fine-tuned"
},
{
"code": null,
"e": 10302,
"s": 10257,
"text": "Improves performance with less training time"
},
{
"code": null,
"e": 10408,
"s": 10302,
"text": "We already have the data set created with image augmentation and we have created the base ResNet50 model."
},
{
"code": null,
"e": 10738,
"s": 10408,
"text": "we will now fine-tune Transfer learning with image augmentation using ResNet50. We do this by unfreezing a few of the last convolution blocks while keeping the first early conv blocks frozen. This will help us to learn very generic features using early layers. Higher layers of pre-trained models will be trainable or fine-tuned."
},
{
"code": null,
"e": 11158,
"s": 10738,
"text": "restnet.trainable = Trueset_trainable = Falsefor layer in restnet.layers: if layer.name in ['res5c_branch2b', 'res5c_branch2c', 'activation_97']: set_trainable = True if set_trainable: layer.trainable = True else: layer.trainable = Falselayers = [(layer, layer.name, layer.trainable) for layer in restnet.layers]pd.DataFrame(layers, columns=['Layer Type', 'Layer Name', 'Layer Trainable'])"
},
{
"code": null,
"e": 11288,
"s": 11158,
"text": "We see that we have set the training for early layers of ResNet50 to false and the last few layers of ResNet50 are now trainable."
},
{
"code": null,
"e": 11462,
"s": 11288,
"text": "we now add our own fully connected layer and classifier on top of the ResNet50. We have already removed the last fully connected layer and the classifier layer from ResNet50"
},
{
"code": null,
"e": 12069,
"s": 11462,
"text": "from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, InputLayerfrom keras.models import Sequentialfrom keras import optimizersmodel_finetuned = Sequential()model_finetuned.add(restnet)model_finetuned.add(Dense(512, activation='relu', input_dim=input_shape))model_finetuned.add(Dropout(0.3))model_finetuned.add(Dense(512, activation='relu'))model_finetuned.add(Dropout(0.3))model_finetuned.add(Dense(1, activation='sigmoid'))model_finetuned.compile(loss='binary_crossentropy', optimizer=optimizers.RMSprop(lr=1e-5), metrics=['accuracy'])model_finetuned.summary()"
},
{
"code": null,
"e": 12094,
"s": 12069,
"text": "We finally run the model"
},
{
"code": null,
"e": 12417,
"s": 12094,
"text": "history_1 = model_finetuned.fit_generator(train_generator, steps_per_epoch=100, epochs=2, validation_data=val_generator, validation_steps=100, verbose=1)"
},
{
"code": null,
"e": 12460,
"s": 12417,
"text": "saving the weights of the fine-tuned model"
},
{
"code": null,
"e": 12521,
"s": 12460,
"text": "model.save(βcats_dogs_tlearn_finetune_img_aug_restnet50.h5β)"
},
{
"code": null,
"e": 12586,
"s": 12521,
"text": "A Survey on Transfer Learning by Sinno Jialin Pan and Qiang Yang"
},
{
"code": null,
"e": 12684,
"s": 12586,
"text": "A comprehensive hands-on-guide-to-transfer-learning-with-real-world-applications-in-deep-learning"
}
] |
Next Greater Element - GeeksforGeeks
|
02 Dec, 2021
Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1.
Examples:
For an array, the rightmost element always has the next greater element as -1.For an array that is sorted in decreasing order, all elements have the next greater element as -1.For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.
For an array, the rightmost element always has the next greater element as -1.
For an array that is sorted in decreasing order, all elements have the next greater element as -1.
For the input array [4, 5, 2, 25], the next greater elements for each element are as follows.
Element NGE
4 --> 5
5 --> 25
2 --> 25
25 --> -1
d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows.
Element NGE
13 --> -1
7 --> 12
6 --> 12
12 --> -1
Method 1 (Simple) Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by the outer loop. If a greater element is found then that element is printed as next, otherwise, -1 is printed.
Below is the implementation of the above approach:
C++
C
Java
Python
C#
PHP
Javascript
// Simple C++ program to print// next greater elements in a// given array#include<iostream>using namespace std; /* prints element and NGE pairfor all elements of arr[] of size n */void printNGE(int arr[], int n){ int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } cout << arr[i] << " -- " << next << endl; }} // Driver Codeint main(){ int arr[] = {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNGE(arr, n); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)
// Simple C program to print next greater elements// in a given array#include<stdio.h> /* prints element and NGE pair for all elements ofarr[] of size n */void printNGE(int arr[], int n){ int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } printf("%d -- %dn", arr[i], next); }} int main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNGE(arr, n); return 0;}
// Simple Java program to print next// greater elements in a given array class Main{ /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int arr[], int n) { int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } System.out.println(arr[i]+" -- "+next); } } public static void main(String args[]) { int arr[]= {11, 13, 21, 3}; int n = arr.length; printNGE(arr, n); }}
# Function to print element and NGE pair for all elements of listdef printNGE(arr): for i in range(0, len(arr), 1): next = -1 for j in range(i+1, len(arr), 1): if arr[i] < arr[j]: next = arr[j] break print(str(arr[i]) + " -- " + str(next)) # Driver program to test above functionarr = [11,13,21,3]printNGE(arr) # This code is contributed by Sunny Karira
// Simple C# program to print next// greater elements in a given arrayusing System; class GFG{ /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int []arr, int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } Console.WriteLine(arr[i] + " -- " + next); } } // driver code public static void Main() { int []arr= {11, 13, 21, 3}; int n = arr.Length; printNGE(arr, n); }} // This code is contributed by Sam007
<?php// Simple PHP program to print next// greater elements in a given array /* prints element and NGE pair for all elements of arr[] of size n */function printNGE($arr, $n){ for ($i = 0; $i < $n; $i++) { $next = -1; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] < $arr[$j]) { $next = $arr[$j]; break; } } echo $arr[$i]." -- ". $next."\n"; }} // Driver Code $arr= array(11, 13, 21, 3); $n = count($arr); printNGE($arr, $n); // This code is contributed by Sam007?>
<script> // Simple JavaScript program to print // next greater elements in a // given array /* prints element and NGE pair for all elements of arr[] of size n */ function printNGE(arr, n) { var next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } document.write(arr[i] + " -- " + next); document.write("<br>"); } } // Driver Code var arr = [11, 13, 21, 3]; var n = arr.length; printNGE(arr, n); // This code is contributed by rdtank. </script>
11 -- 13
13 -- 21
21 -- -1
3 -- -1
Time Complexity: O(N2) Auxiliary Space: O(1)
Method 2 (Using Stack)
Push the first element to stack.
Pick rest of the elements one by one and follow the following steps in loop. Mark the current element as next.If stack is not empty, compare top element of stack with next.If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
Mark the current element as next.If stack is not empty, compare top element of stack with next.If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
Mark the current element as next.
If stack is not empty, compare top element of stack with next.
If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.
Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements.
Finally, push the next in the stack.
After the loop in step 2 is over, pop all the elements from the stack and print -1 as the next element for them.
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
C++
C
Java
Python
C#
Javascript
// A Stack based C++ program to find next// greater element for all array elements.#include <bits/stdc++.h>using namespace std; /* prints element and NGE pair for allelements of arr[] of size n */void printNGE(int arr[], int n){ stack<int> s; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (s.empty() == false && s.top() < arr[i]) { cout << s.top() << " --> " << arr[i] << endl; s.pop(); } /* push next to stack so that we can find next greater for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.empty() == false) { cout << s.top() << " --> " << -1 << endl; s.pop(); }} /* Driver code */int main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNGE(arr, n); return 0;}
// A Stack based C program to find next// greater element for all array elements.#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#define STACKSIZE 100 // stack structurestruct stack { int top; int items[STACKSIZE];}; // Stack Functions to be used by printNGE()void push(struct stack* ps, int x){ if (ps->top == STACKSIZE - 1) { printf("Error: stack overflown"); getchar(); exit(0); } else { ps->top += 1; int top = ps->top; ps->items[top] = x; }} bool isEmpty(struct stack* ps){ return (ps->top == -1) ? true : false;} int pop(struct stack* ps){ int temp; if (ps->top == -1) { printf("Error: stack underflow n"); getchar(); exit(0); } else { int top = ps->top; temp = ps->items[top]; ps->top -= 1; return temp; }} /* prints element and NGE pair for all elements ofarr[] of size n */void printNGE(int arr[], int n){ int i = 0; struct stack s; s.top = -1; int element, next; /* push the first element to stack */ push(&s, arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (isEmpty(&s) == false) { // if stack is not empty, then pop an element // from stack element = pop(&s); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { printf("n %d --> %d", element, next); if (isEmpty(&s) == true) break; element = pop(&s); } /* If element is greater than next, then push the element back */ if (element > next) push(&s, element); } /* push next to stack so that we can find next greater for it */ push(&s, next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (isEmpty(&s) == false) { element = pop(&s); next = -1; printf("n %d --> %d", element, next); }} /* Driver code */int main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNGE(arr, n); getchar(); return 0;}
// Java program to print next// greater element using stack public class NGE { static class stack { int top; int items[] = new int[100]; // Stack functions to be used by printNGE void push(int x) { if (top == 99) { System.out.println("Stack full"); } else { items[++top] = x; } } int pop() { if (top == -1) { System.out.println("Underflow error"); return -1; } else { int element = items[top]; top--; return element; } } boolean isEmpty() { return (top == -1) ? true : false; } } /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int arr[], int n) { int i = 0; stack s = new stack(); s.top = -1; int element, next; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (s.isEmpty() == false) { // if stack is not empty, then // pop an element from stack element = s.pop(); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { System.out.println(element + " --> " + next); if (s.isEmpty() == true) break; element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) s.push(element); } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.isEmpty() == false) { element = s.pop(); next = -1; System.out.println(element + " -- " + next); } } // Driver Code public static void main(String[] args) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNGE(arr, n); }} // Thanks to Rishabh Mahrsee for contributing this code
# Python program to print next greater element using stack # Stack Functions to be used by printNGE() def createStack(): stack = [] return stack def isEmpty(stack): return len(stack) == 0 def push(stack, x): stack.append(x) def pop(stack): if isEmpty(stack): print("Error : stack underflow") else: return stack.pop() '''prints element and NGE pair for all elements of arr[] ''' def printNGE(arr): s = createStack() element = 0 next = 0 # push the first element to stack push(s, arr[0]) # iterate for rest of the elements for i in range(1, len(arr), 1): next = arr[i] if isEmpty(s) == False: # if stack is not empty, then pop an element from stack element = pop(s) '''If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty ''' while element < next: print(str(element) + " -- " + str(next)) if isEmpty(s) == True: break element = pop(s) '''If element is greater than next, then push the element back ''' if element > next: push(s, element) '''push next to stack so that we can find next greater for it ''' push(s, next) '''After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them ''' while isEmpty(s) == False: element = pop(s) next = -1 print(str(element) + " -- " + str(next)) # Driver codearr = [11, 13, 21, 3]printNGE(arr) # This code is contributed by Sunny Karira
using System; // c# program to print next// greater element using stack public class NGE { public class stack { public int top; public int[] items = new int[100]; // Stack functions to be used by printNGE public virtual void push(int x) { if (top == 99) { Console.WriteLine("Stack full"); } else { items[++top] = x; } } public virtual int pop() { if (top == -1) { Console.WriteLine("Underflow error"); return -1; } else { int element = items[top]; top--; return element; } } public virtual bool Empty { get { return (top == -1) ? true : false; } } } /* prints element and NGE pair for all elements of arr[] of size n */ public static void printNGE(int[] arr, int n) { int i = 0; stack s = new stack(); s.top = -1; int element, next; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (s.Empty == false) { // if stack is not empty, then // pop an element from stack element = s.pop(); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { Console.WriteLine(element + " --> " + next); if (s.Empty == true) { break; } element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) { s.push(element); } } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.Empty == false) { element = s.pop(); next = -1; Console.WriteLine(element + " -- " + next); } } // Driver Code public static void Main(string[] args) { int[] arr = new int[] { 11, 13, 21, 3 }; int n = arr.Length; printNGE(arr, n); }} // This code is contributed by Shrikant13
<script> // A Stack based Javascript program to find next// greater element for all array elements. /* prints element and NGE pair for allelements of arr[] of size n */function printNGE(arr, n){ var s = []; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (var i = 1; i < n; i++) { if (s.length == 0) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (s.length ==0 == false && s[s.length-1] < arr[i]) { document.write( s[s.length-1] + " --> " + arr[i]+"<br>"); s.pop(); } /* push next to stack so that we can find next greater for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.length !=0) { document.write( s[s.length-1] + " --> " + -1+ "<br>" ); s.pop(); }} /* Driver code */var arr = [11, 13, 21, 3];var n = arr.length;printNGE(arr, n); </script>
11 --> 13
13 --> 21
3 --> -1
21 --> -1
Time Complexity: O(N) Auxiliary Space: O(N)
The worst case occurs when all elements are sorted in decreasing order. If elements are sorted in decreasing order, then every element is processed at most 4 times.
Initially pushed to the stack.Popped from the stack when next element is being processed.Pushed back to the stack because the next element is smaller.Popped from the stack in step 3 of the algorithm.
Initially pushed to the stack.
Popped from the stack when next element is being processed.
Pushed back to the stack because the next element is smaller.
Popped from the stack in step 3 of the algorithm.
How to get elements in the same order as input?
The above approach may not produce output elements in the same order as the input. To achieve the same order, we can traverse the same in reverse order
Below is the implementation of the above approach:
C++
Java
C#
Javascript
// A Stack based C++ program to find next// greater element for all array elements// in same order as input.#include <bits/stdc++.h> using namespace std; /* prints element and res pair for allelements of arr[] of size n */void printNGE(int arr[], int n){ stack<int> s; int res[n]; for (int i = n - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (!s.empty()) { while (!s.empty() && s.top() <= arr[i]) { s.pop(); } } res[i] = s.empty() ? -1 : s.top(); s.push(arr[i]); } for (int i = 0; i < n; i++) cout << arr[i] << " --> " << res[i] << endl;}// Driver Codeint main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, n); return 0;}
// A Stack based Java program to find next// greater element for all array elements// in same order as input.import java.util.Stack; class NextGreaterElement { static int arr[] = { 11, 13, 21, 3 }; /* prints element and NGE pair for all elements of arr[] of size n */ public static void printNGE() { Stack<Integer> s = new Stack<>(); int nge[] = new int[arr.length]; // iterate for rest of the elements for (int i = arr.length - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (!s.empty()) { while (!s.empty() && s.peek() <= arr[i]) { s.pop(); } } nge[i] = s.empty() ? -1 : s.peek(); s.push(arr[i]); } for (int i = 0; i < arr.length; i++) System.out.println(arr[i] + " --> " + nge[i]); } /* Driver Code */ public static void main(String[] args) { // NextGreaterElement nge = new // NextGreaterElement(); printNGE(); }}
// A Stack based C# program to find next// greater element for all array elements// in same order as input.using System;using System.Collections.Generic; class GFG { private int[] arr = new int[] { 11, 13, 21, 3 }; /* prints element and NGE pair for all elements of arr[] of size n */ private void printNGE() { Stack<int> s = new Stack<int>(); int[] nge = new int[arr.Length]; // iterate for rest of the elements for (int i = arr.Length - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (s.Count > 0) { while (s.Count > 0 && s.Peek() <= arr[i]) { s.Pop(); } } nge[i] = s.Count == 0 ? -1 : s.Peek(); s.Push(arr[i]); } for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i] + " --> " + nge[i]); } } // Driver Code public static void Main(string[] args) { GFG nge = new GFG(); nge.printNGE(); }}
<script> // Javascript program for the above approach /* prints element and NGE pair for all elements of arr[] of size n */ function printNGE(arr, n) { var s = []; let res = new Array(n); // iterate for rest of the elements for (let i = n - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (s.length != 0) { while (s.length != 0 && s[s.length-1] <= arr[i]) { s.pop(); } } res[i] = s.length == 0 ? -1 : s[s.length-1]; s.push(arr[i]); } for (let i = 0; i < arr.length; i++) document.write(arr[i] + " --> " + res[i] + "<br/>"); } // Driver Code let arr = [ 11, 13, 21, 3 ]; let n = arr.length; // Function call prletNGE(arr, n); // This code is contributed by splevel62.</script>
11 ---> 13
13 ---> 21
21 ---> -1
3 ---> -1
Time Complexity: O(N) Auxiliary Space: O(N)
Method 3:
1. This is same as above method but the elements are pushed and popped only once into the stack. The array is changed in place. The array elements are pushed into the stack until it finds a greatest element in the right of array. In other words the elements are popped from stack when top of the stack value is smaller in the current array element.
2. Once all the elements are processed in the array but stack is not empty. The left out elements in the stack doesnβt encounter any greatest element . So pop the element from stack and change itβs index value as -1 in the array.
Python3
# Python3 codeclass Solution: def nextLargerElement(self,arr,n): #code here s=[] for i in range(len(arr)): while s and s[-1].get("value") < arr[i]: d = s.pop() arr[d.get("ind")] = arr[i] s.append({"value": arr[i], "ind": i}) while s: d = s.pop() arr[d.get("ind")] = -1 return arr if __name__ == "__main__": print(Solution().nextLargerElement([6,8,0,1,3],5))
[8, -1, 1, 3, -1]
Time Complexity: O(N) Auxiliary Space: O(N)
Please see for an optimized solution for printing in same order.
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
Sam007
ashishfk
Akanksha_Rai
shrikanth13
sanskar27jain
IndavarapuAneesh
tornado
ankita bajpai 1
pawki
rdtank
famously
umaparvat
kargiloutlook
splevel62
arorakashish0911
Amazon
CouponDunia
Informatica
Payu
Samsung
Snapdeal
Zoho
Arrays
Stack
Zoho
Amazon
Samsung
Snapdeal
Payu
Informatica
CouponDunia
Arrays
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Stack Class in Java
Stack in Python
Inorder Tree Traversal without Recursion
Check for Balanced Brackets in an expression (well-formedness) using Stack
Queue using Stacks
|
[
{
"code": null,
"e": 24741,
"s": 24713,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 25008,
"s": 24741,
"text": "Given an array, print the Next Greater Element (NGE) for every element. The Next greater Element for an element x is the first greater element on the right side of x in the array. Elements for which no greater element exist, consider the next greater element as -1. "
},
{
"code": null,
"e": 25019,
"s": 25008,
"text": "Examples: "
},
{
"code": null,
"e": 25289,
"s": 25019,
"text": "For an array, the rightmost element always has the next greater element as -1.For an array that is sorted in decreasing order, all elements have the next greater element as -1.For the input array [4, 5, 2, 25], the next greater elements for each element are as follows."
},
{
"code": null,
"e": 25368,
"s": 25289,
"text": "For an array, the rightmost element always has the next greater element as -1."
},
{
"code": null,
"e": 25467,
"s": 25368,
"text": "For an array that is sorted in decreasing order, all elements have the next greater element as -1."
},
{
"code": null,
"e": 25561,
"s": 25467,
"text": "For the input array [4, 5, 2, 25], the next greater elements for each element are as follows."
},
{
"code": null,
"e": 25654,
"s": 25561,
"text": "Element NGE\n 4 --> 5\n 5 --> 25\n 2 --> 25\n 25 --> -1"
},
{
"code": null,
"e": 25754,
"s": 25654,
"text": "d) For the input array [13, 7, 6, 12}, the next greater elements for each element are as follows. "
},
{
"code": null,
"e": 25862,
"s": 25754,
"text": " Element NGE\n 13 --> -1\n 7 --> 12\n 6 --> 12\n 12 --> -1"
},
{
"code": null,
"e": 26132,
"s": 25862,
"text": "Method 1 (Simple) Use two loops: The outer loop picks all the elements one by one. The inner loop looks for the first greater element for the element picked by the outer loop. If a greater element is found then that element is printed as next, otherwise, -1 is printed."
},
{
"code": null,
"e": 26183,
"s": 26132,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26187,
"s": 26183,
"text": "C++"
},
{
"code": null,
"e": 26189,
"s": 26187,
"text": "C"
},
{
"code": null,
"e": 26194,
"s": 26189,
"text": "Java"
},
{
"code": null,
"e": 26201,
"s": 26194,
"text": "Python"
},
{
"code": null,
"e": 26204,
"s": 26201,
"text": "C#"
},
{
"code": null,
"e": 26208,
"s": 26204,
"text": "PHP"
},
{
"code": null,
"e": 26219,
"s": 26208,
"text": "Javascript"
},
{
"code": "// Simple C++ program to print// next greater elements in a// given array#include<iostream>using namespace std; /* prints element and NGE pairfor all elements of arr[] of size n */void printNGE(int arr[], int n){ int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } cout << arr[i] << \" -- \" << next << endl; }} // Driver Codeint main(){ int arr[] = {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNGE(arr, n); return 0;} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 26920,
"s": 26219,
"text": null
},
{
"code": "// Simple C program to print next greater elements// in a given array#include<stdio.h> /* prints element and NGE pair for all elements ofarr[] of size n */void printNGE(int arr[], int n){ int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } printf(\"%d -- %dn\", arr[i], next); }} int main(){ int arr[]= {11, 13, 21, 3}; int n = sizeof(arr)/sizeof(arr[0]); printNGE(arr, n); return 0;}",
"e": 27497,
"s": 26920,
"text": null
},
{
"code": "// Simple Java program to print next// greater elements in a given array class Main{ /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int arr[], int n) { int next, i, j; for (i=0; i<n; i++) { next = -1; for (j = i+1; j<n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } System.out.println(arr[i]+\" -- \"+next); } } public static void main(String args[]) { int arr[]= {11, 13, 21, 3}; int n = arr.length; printNGE(arr, n); }}",
"e": 28189,
"s": 27497,
"text": null
},
{
"code": "# Function to print element and NGE pair for all elements of listdef printNGE(arr): for i in range(0, len(arr), 1): next = -1 for j in range(i+1, len(arr), 1): if arr[i] < arr[j]: next = arr[j] break print(str(arr[i]) + \" -- \" + str(next)) # Driver program to test above functionarr = [11,13,21,3]printNGE(arr) # This code is contributed by Sunny Karira",
"e": 28623,
"s": 28189,
"text": null
},
{
"code": "// Simple C# program to print next// greater elements in a given arrayusing System; class GFG{ /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int []arr, int n) { int next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } Console.WriteLine(arr[i] + \" -- \" + next); } } // driver code public static void Main() { int []arr= {11, 13, 21, 3}; int n = arr.Length; printNGE(arr, n); }} // This code is contributed by Sam007",
"e": 29391,
"s": 28623,
"text": null
},
{
"code": "<?php// Simple PHP program to print next// greater elements in a given array /* prints element and NGE pair for all elements of arr[] of size n */function printNGE($arr, $n){ for ($i = 0; $i < $n; $i++) { $next = -1; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] < $arr[$j]) { $next = $arr[$j]; break; } } echo $arr[$i].\" -- \". $next.\"\\n\"; }} // Driver Code $arr= array(11, 13, 21, 3); $n = count($arr); printNGE($arr, $n); // This code is contributed by Sam007?>",
"e": 29992,
"s": 29391,
"text": null
},
{
"code": "<script> // Simple JavaScript program to print // next greater elements in a // given array /* prints element and NGE pair for all elements of arr[] of size n */ function printNGE(arr, n) { var next, i, j; for (i = 0; i < n; i++) { next = -1; for (j = i + 1; j < n; j++) { if (arr[i] < arr[j]) { next = arr[j]; break; } } document.write(arr[i] + \" -- \" + next); document.write(\"<br>\"); } } // Driver Code var arr = [11, 13, 21, 3]; var n = arr.length; printNGE(arr, n); // This code is contributed by rdtank. </script>",
"e": 30729,
"s": 29992,
"text": null
},
{
"code": null,
"e": 30764,
"s": 30729,
"text": "11 -- 13\n13 -- 21\n21 -- -1\n3 -- -1"
},
{
"code": null,
"e": 30810,
"s": 30764,
"text": "Time Complexity: O(N2) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 30834,
"s": 30810,
"text": "Method 2 (Using Stack) "
},
{
"code": null,
"e": 30867,
"s": 30834,
"text": "Push the first element to stack."
},
{
"code": null,
"e": 31303,
"s": 30867,
"text": "Pick rest of the elements one by one and follow the following steps in loop. Mark the current element as next.If stack is not empty, compare top element of stack with next.If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements."
},
{
"code": null,
"e": 31662,
"s": 31303,
"text": "Mark the current element as next.If stack is not empty, compare top element of stack with next.If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element.Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements."
},
{
"code": null,
"e": 31696,
"s": 31662,
"text": "Mark the current element as next."
},
{
"code": null,
"e": 31759,
"s": 31696,
"text": "If stack is not empty, compare top element of stack with next."
},
{
"code": null,
"e": 31881,
"s": 31759,
"text": "If next is greater than the top element, Pop element from stack. next is the next greater element for the popped element."
},
{
"code": null,
"e": 32024,
"s": 31881,
"text": "Keep popping from the stack while the popped element is smaller than next. next becomes the next greater element for all such popped elements."
},
{
"code": null,
"e": 32061,
"s": 32024,
"text": "Finally, push the next in the stack."
},
{
"code": null,
"e": 32174,
"s": 32061,
"text": "After the loop in step 2 is over, pop all the elements from the stack and print -1 as the next element for them."
},
{
"code": null,
"e": 32223,
"s": 32174,
"text": "Below image is a dry run of the above approach: "
},
{
"code": null,
"e": 32275,
"s": 32223,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32279,
"s": 32275,
"text": "C++"
},
{
"code": null,
"e": 32281,
"s": 32279,
"text": "C"
},
{
"code": null,
"e": 32286,
"s": 32281,
"text": "Java"
},
{
"code": null,
"e": 32293,
"s": 32286,
"text": "Python"
},
{
"code": null,
"e": 32296,
"s": 32293,
"text": "C#"
},
{
"code": null,
"e": 32307,
"s": 32296,
"text": "Javascript"
},
{
"code": "// A Stack based C++ program to find next// greater element for all array elements.#include <bits/stdc++.h>using namespace std; /* prints element and NGE pair for allelements of arr[] of size n */void printNGE(int arr[], int n){ stack<int> s; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (int i = 1; i < n; i++) { if (s.empty()) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (s.empty() == false && s.top() < arr[i]) { cout << s.top() << \" --> \" << arr[i] << endl; s.pop(); } /* push next to stack so that we can find next greater for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.empty() == false) { cout << s.top() << \" --> \" << -1 << endl; s.pop(); }} /* Driver code */int main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNGE(arr, n); return 0;}",
"e": 33692,
"s": 32307,
"text": null
},
{
"code": "// A Stack based C program to find next// greater element for all array elements.#include <stdbool.h>#include <stdio.h>#include <stdlib.h>#define STACKSIZE 100 // stack structurestruct stack { int top; int items[STACKSIZE];}; // Stack Functions to be used by printNGE()void push(struct stack* ps, int x){ if (ps->top == STACKSIZE - 1) { printf(\"Error: stack overflown\"); getchar(); exit(0); } else { ps->top += 1; int top = ps->top; ps->items[top] = x; }} bool isEmpty(struct stack* ps){ return (ps->top == -1) ? true : false;} int pop(struct stack* ps){ int temp; if (ps->top == -1) { printf(\"Error: stack underflow n\"); getchar(); exit(0); } else { int top = ps->top; temp = ps->items[top]; ps->top -= 1; return temp; }} /* prints element and NGE pair for all elements ofarr[] of size n */void printNGE(int arr[], int n){ int i = 0; struct stack s; s.top = -1; int element, next; /* push the first element to stack */ push(&s, arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (isEmpty(&s) == false) { // if stack is not empty, then pop an element // from stack element = pop(&s); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { printf(\"n %d --> %d\", element, next); if (isEmpty(&s) == true) break; element = pop(&s); } /* If element is greater than next, then push the element back */ if (element > next) push(&s, element); } /* push next to stack so that we can find next greater for it */ push(&s, next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (isEmpty(&s) == false) { element = pop(&s); next = -1; printf(\"n %d --> %d\", element, next); }} /* Driver code */int main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); printNGE(arr, n); getchar(); return 0;}",
"e": 36122,
"s": 33692,
"text": null
},
{
"code": "// Java program to print next// greater element using stack public class NGE { static class stack { int top; int items[] = new int[100]; // Stack functions to be used by printNGE void push(int x) { if (top == 99) { System.out.println(\"Stack full\"); } else { items[++top] = x; } } int pop() { if (top == -1) { System.out.println(\"Underflow error\"); return -1; } else { int element = items[top]; top--; return element; } } boolean isEmpty() { return (top == -1) ? true : false; } } /* prints element and NGE pair for all elements of arr[] of size n */ static void printNGE(int arr[], int n) { int i = 0; stack s = new stack(); s.top = -1; int element, next; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (s.isEmpty() == false) { // if stack is not empty, then // pop an element from stack element = s.pop(); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { System.out.println(element + \" --> \" + next); if (s.isEmpty() == true) break; element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) s.push(element); } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.isEmpty() == false) { element = s.pop(); next = -1; System.out.println(element + \" -- \" + next); } } // Driver Code public static void main(String[] args) { int arr[] = { 11, 13, 21, 3 }; int n = arr.length; printNGE(arr, n); }} // Thanks to Rishabh Mahrsee for contributing this code",
"e": 38853,
"s": 36122,
"text": null
},
{
"code": "# Python program to print next greater element using stack # Stack Functions to be used by printNGE() def createStack(): stack = [] return stack def isEmpty(stack): return len(stack) == 0 def push(stack, x): stack.append(x) def pop(stack): if isEmpty(stack): print(\"Error : stack underflow\") else: return stack.pop() '''prints element and NGE pair for all elements of arr[] ''' def printNGE(arr): s = createStack() element = 0 next = 0 # push the first element to stack push(s, arr[0]) # iterate for rest of the elements for i in range(1, len(arr), 1): next = arr[i] if isEmpty(s) == False: # if stack is not empty, then pop an element from stack element = pop(s) '''If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty ''' while element < next: print(str(element) + \" -- \" + str(next)) if isEmpty(s) == True: break element = pop(s) '''If element is greater than next, then push the element back ''' if element > next: push(s, element) '''push next to stack so that we can find next greater for it ''' push(s, next) '''After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them ''' while isEmpty(s) == False: element = pop(s) next = -1 print(str(element) + \" -- \" + str(next)) # Driver codearr = [11, 13, 21, 3]printNGE(arr) # This code is contributed by Sunny Karira",
"e": 40619,
"s": 38853,
"text": null
},
{
"code": "using System; // c# program to print next// greater element using stack public class NGE { public class stack { public int top; public int[] items = new int[100]; // Stack functions to be used by printNGE public virtual void push(int x) { if (top == 99) { Console.WriteLine(\"Stack full\"); } else { items[++top] = x; } } public virtual int pop() { if (top == -1) { Console.WriteLine(\"Underflow error\"); return -1; } else { int element = items[top]; top--; return element; } } public virtual bool Empty { get { return (top == -1) ? true : false; } } } /* prints element and NGE pair for all elements of arr[] of size n */ public static void printNGE(int[] arr, int n) { int i = 0; stack s = new stack(); s.top = -1; int element, next; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (i = 1; i < n; i++) { next = arr[i]; if (s.Empty == false) { // if stack is not empty, then // pop an element from stack element = s.pop(); /* If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (element < next) { Console.WriteLine(element + \" --> \" + next); if (s.Empty == true) { break; } element = s.pop(); } /* If element is greater than next, then push the element back */ if (element > next) { s.push(element); } } /* push next to stack so that we can find next greater for it */ s.push(next); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.Empty == false) { element = s.pop(); next = -1; Console.WriteLine(element + \" -- \" + next); } } // Driver Code public static void Main(string[] args) { int[] arr = new int[] { 11, 13, 21, 3 }; int n = arr.Length; printNGE(arr, n); }} // This code is contributed by Shrikant13",
"e": 43377,
"s": 40619,
"text": null
},
{
"code": "<script> // A Stack based Javascript program to find next// greater element for all array elements. /* prints element and NGE pair for allelements of arr[] of size n */function printNGE(arr, n){ var s = []; /* push the first element to stack */ s.push(arr[0]); // iterate for rest of the elements for (var i = 1; i < n; i++) { if (s.length == 0) { s.push(arr[i]); continue; } /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ while (s.length ==0 == false && s[s.length-1] < arr[i]) { document.write( s[s.length-1] + \" --> \" + arr[i]+\"<br>\"); s.pop(); } /* push next to stack so that we can find next greater for it */ s.push(arr[i]); } /* After iterating over the loop, the remaining elements in stack do not have the next greater element, so print -1 for them */ while (s.length !=0) { document.write( s[s.length-1] + \" --> \" + -1+ \"<br>\" ); s.pop(); }} /* Driver code */var arr = [11, 13, 21, 3];var n = arr.length;printNGE(arr, n); </script>",
"e": 44710,
"s": 43377,
"text": null
},
{
"code": null,
"e": 44749,
"s": 44710,
"text": "11 --> 13\n13 --> 21\n3 --> -1\n21 --> -1"
},
{
"code": null,
"e": 44794,
"s": 44749,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 44961,
"s": 44794,
"text": "The worst case occurs when all elements are sorted in decreasing order. If elements are sorted in decreasing order, then every element is processed at most 4 times. "
},
{
"code": null,
"e": 45161,
"s": 44961,
"text": "Initially pushed to the stack.Popped from the stack when next element is being processed.Pushed back to the stack because the next element is smaller.Popped from the stack in step 3 of the algorithm."
},
{
"code": null,
"e": 45192,
"s": 45161,
"text": "Initially pushed to the stack."
},
{
"code": null,
"e": 45252,
"s": 45192,
"text": "Popped from the stack when next element is being processed."
},
{
"code": null,
"e": 45314,
"s": 45252,
"text": "Pushed back to the stack because the next element is smaller."
},
{
"code": null,
"e": 45364,
"s": 45314,
"text": "Popped from the stack in step 3 of the algorithm."
},
{
"code": null,
"e": 45412,
"s": 45364,
"text": "How to get elements in the same order as input?"
},
{
"code": null,
"e": 45564,
"s": 45412,
"text": "The above approach may not produce output elements in the same order as the input. To achieve the same order, we can traverse the same in reverse order"
},
{
"code": null,
"e": 45615,
"s": 45564,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 45621,
"s": 45617,
"text": "C++"
},
{
"code": null,
"e": 45626,
"s": 45621,
"text": "Java"
},
{
"code": null,
"e": 45629,
"s": 45626,
"text": "C#"
},
{
"code": null,
"e": 45640,
"s": 45629,
"text": "Javascript"
},
{
"code": "// A Stack based C++ program to find next// greater element for all array elements// in same order as input.#include <bits/stdc++.h> using namespace std; /* prints element and res pair for allelements of arr[] of size n */void printNGE(int arr[], int n){ stack<int> s; int res[n]; for (int i = n - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (!s.empty()) { while (!s.empty() && s.top() <= arr[i]) { s.pop(); } } res[i] = s.empty() ? -1 : s.top(); s.push(arr[i]); } for (int i = 0; i < n; i++) cout << arr[i] << \" --> \" << res[i] << endl;}// Driver Codeint main(){ int arr[] = { 11, 13, 21, 3 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printNGE(arr, n); return 0;}",
"e": 46642,
"s": 45640,
"text": null
},
{
"code": "// A Stack based Java program to find next// greater element for all array elements// in same order as input.import java.util.Stack; class NextGreaterElement { static int arr[] = { 11, 13, 21, 3 }; /* prints element and NGE pair for all elements of arr[] of size n */ public static void printNGE() { Stack<Integer> s = new Stack<>(); int nge[] = new int[arr.length]; // iterate for rest of the elements for (int i = arr.length - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (!s.empty()) { while (!s.empty() && s.peek() <= arr[i]) { s.pop(); } } nge[i] = s.empty() ? -1 : s.peek(); s.push(arr[i]); } for (int i = 0; i < arr.length; i++) System.out.println(arr[i] + \" --> \" + nge[i]); } /* Driver Code */ public static void main(String[] args) { // NextGreaterElement nge = new // NextGreaterElement(); printNGE(); }}",
"e": 47991,
"s": 46642,
"text": null
},
{
"code": "// A Stack based C# program to find next// greater element for all array elements// in same order as input.using System;using System.Collections.Generic; class GFG { private int[] arr = new int[] { 11, 13, 21, 3 }; /* prints element and NGE pair for all elements of arr[] of size n */ private void printNGE() { Stack<int> s = new Stack<int>(); int[] nge = new int[arr.Length]; // iterate for rest of the elements for (int i = arr.Length - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (s.Count > 0) { while (s.Count > 0 && s.Peek() <= arr[i]) { s.Pop(); } } nge[i] = s.Count == 0 ? -1 : s.Peek(); s.Push(arr[i]); } for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i] + \" --> \" + nge[i]); } } // Driver Code public static void Main(string[] args) { GFG nge = new GFG(); nge.printNGE(); }}",
"e": 49300,
"s": 47991,
"text": null
},
{
"code": "<script> // Javascript program for the above approach /* prints element and NGE pair for all elements of arr[] of size n */ function printNGE(arr, n) { var s = []; let res = new Array(n); // iterate for rest of the elements for (let i = n - 1; i >= 0; i--) { /* if stack is not empty, then pop an element from stack. If the popped element is smaller than next, then a) print the pair b) keep popping while elements are smaller and stack is not empty */ if (s.length != 0) { while (s.length != 0 && s[s.length-1] <= arr[i]) { s.pop(); } } res[i] = s.length == 0 ? -1 : s[s.length-1]; s.push(arr[i]); } for (let i = 0; i < arr.length; i++) document.write(arr[i] + \" --> \" + res[i] + \"<br/>\"); } // Driver Code let arr = [ 11, 13, 21, 3 ]; let n = arr.length; // Function call prletNGE(arr, n); // This code is contributed by splevel62.</script>",
"e": 50497,
"s": 49300,
"text": null
},
{
"code": null,
"e": 50540,
"s": 50497,
"text": "11 ---> 13\n13 ---> 21\n21 ---> -1\n3 ---> -1"
},
{
"code": null,
"e": 50585,
"s": 50540,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 50595,
"s": 50585,
"text": "Method 3:"
},
{
"code": null,
"e": 50944,
"s": 50595,
"text": "1. This is same as above method but the elements are pushed and popped only once into the stack. The array is changed in place. The array elements are pushed into the stack until it finds a greatest element in the right of array. In other words the elements are popped from stack when top of the stack value is smaller in the current array element."
},
{
"code": null,
"e": 51174,
"s": 50944,
"text": "2. Once all the elements are processed in the array but stack is not empty. The left out elements in the stack doesnβt encounter any greatest element . So pop the element from stack and change itβs index value as -1 in the array."
},
{
"code": null,
"e": 51182,
"s": 51174,
"text": "Python3"
},
{
"code": "# Python3 codeclass Solution: def nextLargerElement(self,arr,n): #code here s=[] for i in range(len(arr)): while s and s[-1].get(\"value\") < arr[i]: d = s.pop() arr[d.get(\"ind\")] = arr[i] s.append({\"value\": arr[i], \"ind\": i}) while s: d = s.pop() arr[d.get(\"ind\")] = -1 return arr if __name__ == \"__main__\": print(Solution().nextLargerElement([6,8,0,1,3],5))",
"e": 51663,
"s": 51182,
"text": null
},
{
"code": null,
"e": 51681,
"s": 51663,
"text": "[8, -1, 1, 3, -1]"
},
{
"code": null,
"e": 51725,
"s": 51681,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 51791,
"s": 51725,
"text": "Please see for an optimized solution for printing in same order. "
},
{
"code": null,
"e": 51910,
"s": 51791,
"text": "Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. "
},
{
"code": null,
"e": 51917,
"s": 51910,
"text": "Sam007"
},
{
"code": null,
"e": 51926,
"s": 51917,
"text": "ashishfk"
},
{
"code": null,
"e": 51939,
"s": 51926,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 51951,
"s": 51939,
"text": "shrikanth13"
},
{
"code": null,
"e": 51965,
"s": 51951,
"text": "sanskar27jain"
},
{
"code": null,
"e": 51982,
"s": 51965,
"text": "IndavarapuAneesh"
},
{
"code": null,
"e": 51990,
"s": 51982,
"text": "tornado"
},
{
"code": null,
"e": 52006,
"s": 51990,
"text": "ankita bajpai 1"
},
{
"code": null,
"e": 52012,
"s": 52006,
"text": "pawki"
},
{
"code": null,
"e": 52019,
"s": 52012,
"text": "rdtank"
},
{
"code": null,
"e": 52028,
"s": 52019,
"text": "famously"
},
{
"code": null,
"e": 52038,
"s": 52028,
"text": "umaparvat"
},
{
"code": null,
"e": 52052,
"s": 52038,
"text": "kargiloutlook"
},
{
"code": null,
"e": 52062,
"s": 52052,
"text": "splevel62"
},
{
"code": null,
"e": 52079,
"s": 52062,
"text": "arorakashish0911"
},
{
"code": null,
"e": 52086,
"s": 52079,
"text": "Amazon"
},
{
"code": null,
"e": 52098,
"s": 52086,
"text": "CouponDunia"
},
{
"code": null,
"e": 52110,
"s": 52098,
"text": "Informatica"
},
{
"code": null,
"e": 52115,
"s": 52110,
"text": "Payu"
},
{
"code": null,
"e": 52123,
"s": 52115,
"text": "Samsung"
},
{
"code": null,
"e": 52132,
"s": 52123,
"text": "Snapdeal"
},
{
"code": null,
"e": 52137,
"s": 52132,
"text": "Zoho"
},
{
"code": null,
"e": 52144,
"s": 52137,
"text": "Arrays"
},
{
"code": null,
"e": 52150,
"s": 52144,
"text": "Stack"
},
{
"code": null,
"e": 52155,
"s": 52150,
"text": "Zoho"
},
{
"code": null,
"e": 52162,
"s": 52155,
"text": "Amazon"
},
{
"code": null,
"e": 52170,
"s": 52162,
"text": "Samsung"
},
{
"code": null,
"e": 52179,
"s": 52170,
"text": "Snapdeal"
},
{
"code": null,
"e": 52184,
"s": 52179,
"text": "Payu"
},
{
"code": null,
"e": 52196,
"s": 52184,
"text": "Informatica"
},
{
"code": null,
"e": 52208,
"s": 52196,
"text": "CouponDunia"
},
{
"code": null,
"e": 52215,
"s": 52208,
"text": "Arrays"
},
{
"code": null,
"e": 52221,
"s": 52215,
"text": "Stack"
},
{
"code": null,
"e": 52319,
"s": 52221,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52328,
"s": 52319,
"text": "Comments"
},
{
"code": null,
"e": 52341,
"s": 52328,
"text": "Old Comments"
},
{
"code": null,
"e": 52364,
"s": 52341,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 52396,
"s": 52364,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 52417,
"s": 52396,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 52462,
"s": 52417,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 52516,
"s": 52462,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
},
{
"code": null,
"e": 52536,
"s": 52516,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 52552,
"s": 52536,
"text": "Stack in Python"
},
{
"code": null,
"e": 52593,
"s": 52552,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 52668,
"s": 52593,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Using python package to build your custom dataset β MLDatasetBuilder | by Karthick Nagarajan | Towards Data Science
|
As an ML Newbie, I need to figure out the best way to prepare the dataset for our machine learning training model. As per my last article, I came up with a Python package for this process!
Whenever you are training a custom model the important thing is the dataset. Yes, of course, the dataset plays the main role in deep learning. The accuracy of your model will be based on the dataset. So, before you train a custom model, you need to plan how to build a dataset? Here, Iβm going to share my ideas on the easy way to build your dataset.
pypi.org
Whenever we begin a machine learning project, the first thing that we need is a dataset. Datasets will be the pillar of the training model. You can build the dataset either automatically or manually. MLDatasetBuilder is a python package which is helping to prepare the image for your ML dataset.
github.com
We can install MLDatasetBuilder package using the below command
pip install MLDatasetBuilder
When you run python3 in the terminal, it will produce output like this:
Python 3.6.9 (default, Apr 18 2020, 01:56:04) [GCC 8.4.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>>
Run the following code to you can get the Initialize process output for the MLDatasetBuilder package.
>>> from MLDatasetBuilder import *>>> MLDatasetBuilder()
PrepareImage β Remove unwanted format images and Rename your images
#PrepareImage(folder_name, image_name)PrepareImage('images', 'dog')
ExtractImages β Extract images from video file
#ExtractImages(video_path, file_name, frame_size)ExtractImages('video.mp4', 'frame', 10)#OR#ExtractImages(video_path, filename)ExtractImages('video.mp4', 'frame')#Default FPS will be 5
Yes, we can get images from Google. Using the Download All Images browser extension we can easily get images in a few minutes. You can check out here for more details about this extension!
Once you have downloaded the images using this extension, you can create a python file called test.py the same directory as below.
download_image_folder/| _14e839ba-9691-11ea-a968-2ed746e9a968.jpg| 5e5f7af12600004018b602c0.jpeg| A471529_Alice_b-1.jpg| image1.png| image2.png| ...test.py
Inside the images folder, you can see lots of PNG images and random filenames.
MLDatasetBuilder provides a method called PrepareImage. Using this method to we can remove the unwanted images and rename your image files which are already you have downloaded from the browserβs extensions.
PrepareImage(folder_path, class_name)#PrepareImage('download_image_folder', 'dog')
As per the above code, we need to mention the image folder path and class name.
After completing the process your image folder structure will look like below
download_image_folder/| dog_0.jpg| dog_1.jpg| dog_2.jpg| dog_3.png| dog_4.png| ...test.py
This process very helps to annotate your images while labeling. And of course, it will be like one of the standardized things.
MLDatasetBuilder also provides a method called ExtractImages. Using this method we can extract the images from the video files.
download_image_folder/video.mp4test.py
As per the below code, we need to mention the video path, folder name, and framesize. Folder name will the class name and framesizeβs default value 5 and itβs not mandatory.
ExtractImages(video_path, folder_name, framesize)#ExtractImages('video.mp4', 'frame', 10)ExtractImages(video_path, folder_name)#ExtractImages('video.mp4', 'frame')
After completing the process your image folder structure will look like below
download_image_folder/dog/| dog_0.jpg| dog_1.jpg| dog_2.jpg| dog_3.png| dog_4.png| ...dog.mp4test.py
I have planned to release version 2.0.0 on next month, This will include some additional features.
I mean this package will provide more than 100 objects images with annotations file :)
All issues and pull requests are welcome! To run the code locally, first, fork the repository and then run the following commands on your computer:
git clone https://github.com/<your-username>/ML-Dataset-Builder.gitcd ML-Dataset-Builder# Recommended creating a virtual environment before the next steppip3 install -r requirements.txt
When adding code, be sure to write unit tests where necessary.
MLDatasetBuilder was created by Karthick Nagarajan. Feel free to reach out on Twitter Linkedin or through Email!
Originally published at www.spritle.com
|
[
{
"code": null,
"e": 361,
"s": 172,
"text": "As an ML Newbie, I need to figure out the best way to prepare the dataset for our machine learning training model. As per my last article, I came up with a Python package for this process!"
},
{
"code": null,
"e": 712,
"s": 361,
"text": "Whenever you are training a custom model the important thing is the dataset. Yes, of course, the dataset plays the main role in deep learning. The accuracy of your model will be based on the dataset. So, before you train a custom model, you need to plan how to build a dataset? Here, Iβm going to share my ideas on the easy way to build your dataset."
},
{
"code": null,
"e": 721,
"s": 712,
"text": "pypi.org"
},
{
"code": null,
"e": 1017,
"s": 721,
"text": "Whenever we begin a machine learning project, the first thing that we need is a dataset. Datasets will be the pillar of the training model. You can build the dataset either automatically or manually. MLDatasetBuilder is a python package which is helping to prepare the image for your ML dataset."
},
{
"code": null,
"e": 1028,
"s": 1017,
"text": "github.com"
},
{
"code": null,
"e": 1092,
"s": 1028,
"text": "We can install MLDatasetBuilder package using the below command"
},
{
"code": null,
"e": 1121,
"s": 1092,
"text": "pip install MLDatasetBuilder"
},
{
"code": null,
"e": 1193,
"s": 1121,
"text": "When you run python3 in the terminal, it will produce output like this:"
},
{
"code": null,
"e": 1334,
"s": 1193,
"text": "Python 3.6.9 (default, Apr 18 2020, 01:56:04) [GCC 8.4.0] on linuxType \"help\", \"copyright\", \"credits\" or \"license\" for more information.>>> "
},
{
"code": null,
"e": 1436,
"s": 1334,
"text": "Run the following code to you can get the Initialize process output for the MLDatasetBuilder package."
},
{
"code": null,
"e": 1493,
"s": 1436,
"text": ">>> from MLDatasetBuilder import *>>> MLDatasetBuilder()"
},
{
"code": null,
"e": 1561,
"s": 1493,
"text": "PrepareImage β Remove unwanted format images and Rename your images"
},
{
"code": null,
"e": 1629,
"s": 1561,
"text": "#PrepareImage(folder_name, image_name)PrepareImage('images', 'dog')"
},
{
"code": null,
"e": 1676,
"s": 1629,
"text": "ExtractImages β Extract images from video file"
},
{
"code": null,
"e": 1861,
"s": 1676,
"text": "#ExtractImages(video_path, file_name, frame_size)ExtractImages('video.mp4', 'frame', 10)#OR#ExtractImages(video_path, filename)ExtractImages('video.mp4', 'frame')#Default FPS will be 5"
},
{
"code": null,
"e": 2050,
"s": 1861,
"text": "Yes, we can get images from Google. Using the Download All Images browser extension we can easily get images in a few minutes. You can check out here for more details about this extension!"
},
{
"code": null,
"e": 2181,
"s": 2050,
"text": "Once you have downloaded the images using this extension, you can create a python file called test.py the same directory as below."
},
{
"code": null,
"e": 2349,
"s": 2181,
"text": "download_image_folder/| _14e839ba-9691-11ea-a968-2ed746e9a968.jpg| 5e5f7af12600004018b602c0.jpeg| A471529_Alice_b-1.jpg| image1.png| image2.png| ...test.py"
},
{
"code": null,
"e": 2428,
"s": 2349,
"text": "Inside the images folder, you can see lots of PNG images and random filenames."
},
{
"code": null,
"e": 2636,
"s": 2428,
"text": "MLDatasetBuilder provides a method called PrepareImage. Using this method to we can remove the unwanted images and rename your image files which are already you have downloaded from the browserβs extensions."
},
{
"code": null,
"e": 2719,
"s": 2636,
"text": "PrepareImage(folder_path, class_name)#PrepareImage('download_image_folder', 'dog')"
},
{
"code": null,
"e": 2799,
"s": 2719,
"text": "As per the above code, we need to mention the image folder path and class name."
},
{
"code": null,
"e": 2877,
"s": 2799,
"text": "After completing the process your image folder structure will look like below"
},
{
"code": null,
"e": 2979,
"s": 2877,
"text": "download_image_folder/| dog_0.jpg| dog_1.jpg| dog_2.jpg| dog_3.png| dog_4.png| ...test.py"
},
{
"code": null,
"e": 3106,
"s": 2979,
"text": "This process very helps to annotate your images while labeling. And of course, it will be like one of the standardized things."
},
{
"code": null,
"e": 3234,
"s": 3106,
"text": "MLDatasetBuilder also provides a method called ExtractImages. Using this method we can extract the images from the video files."
},
{
"code": null,
"e": 3273,
"s": 3234,
"text": "download_image_folder/video.mp4test.py"
},
{
"code": null,
"e": 3447,
"s": 3273,
"text": "As per the below code, we need to mention the video path, folder name, and framesize. Folder name will the class name and framesizeβs default value 5 and itβs not mandatory."
},
{
"code": null,
"e": 3611,
"s": 3447,
"text": "ExtractImages(video_path, folder_name, framesize)#ExtractImages('video.mp4', 'frame', 10)ExtractImages(video_path, folder_name)#ExtractImages('video.mp4', 'frame')"
},
{
"code": null,
"e": 3689,
"s": 3611,
"text": "After completing the process your image folder structure will look like below"
},
{
"code": null,
"e": 3802,
"s": 3689,
"text": "download_image_folder/dog/| dog_0.jpg| dog_1.jpg| dog_2.jpg| dog_3.png| dog_4.png| ...dog.mp4test.py"
},
{
"code": null,
"e": 3901,
"s": 3802,
"text": "I have planned to release version 2.0.0 on next month, This will include some additional features."
},
{
"code": null,
"e": 3988,
"s": 3901,
"text": "I mean this package will provide more than 100 objects images with annotations file :)"
},
{
"code": null,
"e": 4136,
"s": 3988,
"text": "All issues and pull requests are welcome! To run the code locally, first, fork the repository and then run the following commands on your computer:"
},
{
"code": null,
"e": 4322,
"s": 4136,
"text": "git clone https://github.com/<your-username>/ML-Dataset-Builder.gitcd ML-Dataset-Builder# Recommended creating a virtual environment before the next steppip3 install -r requirements.txt"
},
{
"code": null,
"e": 4385,
"s": 4322,
"text": "When adding code, be sure to write unit tests where necessary."
},
{
"code": null,
"e": 4498,
"s": 4385,
"text": "MLDatasetBuilder was created by Karthick Nagarajan. Feel free to reach out on Twitter Linkedin or through Email!"
}
] |
How to use multiple threads in android?
|
Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to use multiple threads in android.
Step 1 β Create a new project in Android Studio, go to File β New Project and fill all required details to create a new project.
Step 2 β Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter string" />
<Button
android:id="@+id/click"
android:layout_marginTop="50dp"
style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:background="#c1c1c1"
android:textColor="#FFF"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update both textviewβs with thread name.
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.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText edit_query;
TextView textView;
TextView text1;
boolean twice = false;
Thread t = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
textView = findViewById(R.id.text);
text1 = findViewById(R.id.text1);
findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runthread();
runthread1();
}
});
}
private void runthread1() {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
text1.setText("tutorialspoint.com");
}
});
}
private void runthread() {
twice = true;
if (twice) {
final String s1 = edit_query.getText().toString();
t = new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(t.getName());
twice = false;
}
});
}
});
t.start();
t.setName(s1);
t.setPriority(Thread.MAX_PRIORITY);
}
}
}
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 some text in edit text and click on button, It will append the data to thread and take the data from thread as get name method and append to textview in thread 1. Second thread works in the background and update textview as tuorialspoint.com.
Click here to download the project code
|
[
{
"code": null,
"e": 1297,
"s": 1062,
"text": "Before getting into an example, we should know what thread is. A thread is a lightweight sub-process, it going to do background operations without interrupt to ui. This example demonstrate about How to use multiple threads in android."
},
{
"code": null,
"e": 1426,
"s": 1297,
"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": 1491,
"s": 1426,
"text": "Step 2 β Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2667,
"s": 1491,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\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_horizontal\"\n android:layout_marginTop=\"100dp\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/edit_query\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Enter string\" />\n <Button\n android:id=\"@+id/click\"\n android:layout_marginTop=\"50dp\"\n style=\"@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored\"\n android:layout_width=\"wrap_content\"\n android:background=\"#c1c1c1\"\n android:textColor=\"#FFF\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\" />\n <TextView\n android:id=\"@+id/text\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/text1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2838,
"s": 2667,
"text": "In the above code, we have taken edittext and textview. When user enter some text into edittext, it going to wait till 5000ms and update both textviewβs with thread name."
},
{
"code": null,
"e": 2895,
"s": 2838,
"text": "Step 3 β Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 4712,
"s": 2895,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText edit_query;\n TextView textView;\n TextView text1;\n boolean twice = false;\n Thread t = null;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n edit_query = findViewById(R.id.edit_query);\n textView = findViewById(R.id.text);\n text1 = findViewById(R.id.text1);\n findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n runthread();\n runthread1();\n }\n });\n }\n\n private void runthread1() {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n text1.setText(\"tutorialspoint.com\");\n }\n });\n }\n\n private void runthread() {\n twice = true;\n if (twice) {\n final String s1 = edit_query.getText().toString();\n t = new Thread(new Runnable() {\n @Override\n public void run() {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(t.getName());\n twice = false;\n }\n });\n }\n });\n t.start();\n t.setName(s1);\n t.setPriority(Thread.MAX_PRIORITY);\n }\n }\n}"
},
{
"code": null,
"e": 5059,
"s": 4712,
"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": 5329,
"s": 5059,
"text": "In the above result, Enter some text in edit text and click on button, It will append the data to thread and take the data from thread as get name method and append to textview in thread 1. Second thread works in the background and update textview as tuorialspoint.com."
},
{
"code": null,
"e": 5369,
"s": 5329,
"text": "Click here to download the project code"
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
|
29 Sep, 2021
Consider a machine with a byte addressable main memory of 220 bytes, block size of 16 bytes and a direct mapped cache having 212 cache lines. Let the addresses of two consecutive bytes in main memory be (E201F)16 and (E2020)16. What are the tag and cache line address (in hex) for main memory address (E201F)16?(A) E, 201(B) F, 201(C) E, E20(D) 2, 01FAnswer: (A)Explanation:
Block Size = 16 bytes
Block Offset = 4
No. of sets or cache lines = 212
Number of index bits = 12
Size of main memory = 220
Number of tag bits = 20 - 12 - 4 = 4
Let us consider the hex address E201F
Tag lines = First 4 bits = E (in hex)
Cache lines = Next 12 bits = 201 (In Hex)
Refer http://virtual-labs.ac.in/labs/cse10/dmc.html
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersQuestions on Cache Mapping Techniques with Ashish Verma | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0037:09 / 58:01β’Liveβ’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=lz3J33WzNOo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
|
[
{
"code": null,
"e": 24101,
"s": 24073,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 24476,
"s": 24101,
"text": "Consider a machine with a byte addressable main memory of 220 bytes, block size of 16 bytes and a direct mapped cache having 212 cache lines. Let the addresses of two consecutive bytes in main memory be (E201F)16 and (E2020)16. What are the tag and cache line address (in hex) for main memory address (E201F)16?(A) E, 201(B) F, 201(C) E, E20(D) 2, 01FAnswer: (A)Explanation:"
},
{
"code": null,
"e": 24762,
"s": 24476,
"text": "Block Size = 16 bytes\nBlock Offset = 4 \n\nNo. of sets or cache lines = 212\nNumber of index bits = 12\n\nSize of main memory = 220\nNumber of tag bits = 20 - 12 - 4 = 4 \n\nLet us consider the hex address E201F\nTag lines = First 4 bits = E (in hex)\nCache lines = Next 12 bits = 201 (In Hex) "
},
{
"code": null,
"e": 24814,
"s": 24762,
"text": "Refer http://virtual-labs.ac.in/labs/cse10/dmc.html"
},
{
"code": null,
"e": 25719,
"s": 24814,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersQuestions on Cache Mapping Techniques with Ashish Verma | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0037:09 / 58:01β’Liveβ’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=lz3J33WzNOo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25740,
"s": 25719,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25766,
"s": 25740,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 25771,
"s": 25766,
"text": "GATE"
},
{
"code": null,
"e": 25869,
"s": 25771,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25878,
"s": 25869,
"text": "Comments"
},
{
"code": null,
"e": 25891,
"s": 25878,
"text": "Old Comments"
},
{
"code": null,
"e": 25933,
"s": 25891,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25975,
"s": 25933,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 26009,
"s": 25975,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 26051,
"s": 26009,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26105,
"s": 26051,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 26138,
"s": 26105,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26180,
"s": 26138,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 42"
},
{
"code": null,
"e": 26222,
"s": 26180,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26256,
"s": 26222,
"text": "GATE | GATE CS 2011 | Question 65"
}
] |
Plotting Correlation Matrix using Python
|
26 Nov, 2020
Correlation means an association, It is a measure of the extent to which two variables are related.
1. Positive Correlation: When two variables increase together and decrease together. They are positively correlated. β1β is a perfect positive correlation. For example β demand and profit are positively correlated the more the demand for the product, the more profit hence positive correlation.
2. Negative Correlation: When one variable increases and the other variable decreases together and vice-versa. They are negatively correlated. For example, If the distance between magnet increases their attraction decreases, and vice-versa. Hence, a negative correlation. β-1β is no correlation
3. Zero Correlation( No Correlation): When two variables donβt seem to be linked at all. β0β is a perfect negative correlation. For Example, the amount of tea you take and level of intelligence.
Step 1: Importing the libraries.
Python3
import sklearnimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd
Step 2: Finding the Correlation between two variables.
Python3
y = pd.Series([1, 2, 3, 4, 3, 5, 4])x = pd.Series([1, 2, 3, 4, 5, 6, 7])correlation = y.corr(x)correlation
Output:
Step 3: Plotting the graph. Here we are using scatter plots. A scatter plot is a diagram where each value in the data set is represented by a dot. Also, it shows a relationship between two variables.
Python3
# plotting the dataplt.scatter(x, y) # This will fit the best line into the graphplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1)) (np.unique(x)), color='red')
Output:
Remember the points that were explained above. Observe both the images you will find similarity Also, observe the value of the correlation is near to 1, hence the positive correlation is reflected.
Python3
# adds the titleplt.title('Correlation') # plot the dataplt.scatter(x, y) # fits the best fitting line to the dataplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1)) (np.unique(x)), color='red') # Labelling axesplt.xlabel('x axis')plt.ylabel('y axis')
Output:
There are many ways you can plot correlation matrices one efficient way is using the heatmap. It is very easy to understand the correlation using heatmaps it tells the correlation of one feature(variable) to every other feature(variable). In other words, A correlation matrix is a tabular data representing the βcorrelationsβ between pairs of variables in a given data.
Python3
import seaborn as sns # checking correlation using heatmap#Loading datasetflights = sns.load_dataset("flights") #ploting the heatmap for correlationax = sns.heatmap(flights.corr(), annot=True)
Output:
Python-matplotlib
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "Correlation means an association, It is a measure of the extent to which two variables are related. "
},
{
"code": null,
"e": 424,
"s": 129,
"text": "1. Positive Correlation: When two variables increase together and decrease together. They are positively correlated. β1β is a perfect positive correlation. For example β demand and profit are positively correlated the more the demand for the product, the more profit hence positive correlation."
},
{
"code": null,
"e": 720,
"s": 424,
"text": "2. Negative Correlation: When one variable increases and the other variable decreases together and vice-versa. They are negatively correlated. For example, If the distance between magnet increases their attraction decreases, and vice-versa. Hence, a negative correlation. β-1β is no correlation"
},
{
"code": null,
"e": 915,
"s": 720,
"text": "3. Zero Correlation( No Correlation): When two variables donβt seem to be linked at all. β0β is a perfect negative correlation. For Example, the amount of tea you take and level of intelligence."
},
{
"code": null,
"e": 948,
"s": 915,
"text": "Step 1: Importing the libraries."
},
{
"code": null,
"e": 956,
"s": 948,
"text": "Python3"
},
{
"code": "import sklearnimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd",
"e": 1039,
"s": 956,
"text": null
},
{
"code": null,
"e": 1094,
"s": 1039,
"text": "Step 2: Finding the Correlation between two variables."
},
{
"code": null,
"e": 1102,
"s": 1094,
"text": "Python3"
},
{
"code": "y = pd.Series([1, 2, 3, 4, 3, 5, 4])x = pd.Series([1, 2, 3, 4, 5, 6, 7])correlation = y.corr(x)correlation ",
"e": 1210,
"s": 1102,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Output:"
},
{
"code": null,
"e": 1418,
"s": 1218,
"text": "Step 3: Plotting the graph. Here we are using scatter plots. A scatter plot is a diagram where each value in the data set is represented by a dot. Also, it shows a relationship between two variables."
},
{
"code": null,
"e": 1426,
"s": 1418,
"text": "Python3"
},
{
"code": "# plotting the dataplt.scatter(x, y) # This will fit the best line into the graphplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1)) (np.unique(x)), color='red')",
"e": 1599,
"s": 1426,
"text": null
},
{
"code": null,
"e": 1607,
"s": 1599,
"text": "Output:"
},
{
"code": null,
"e": 1805,
"s": 1607,
"text": "Remember the points that were explained above. Observe both the images you will find similarity Also, observe the value of the correlation is near to 1, hence the positive correlation is reflected."
},
{
"code": null,
"e": 1813,
"s": 1805,
"text": "Python3"
},
{
"code": "# adds the titleplt.title('Correlation') # plot the dataplt.scatter(x, y) # fits the best fitting line to the dataplt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1)) (np.unique(x)), color='red') # Labelling axesplt.xlabel('x axis')plt.ylabel('y axis')",
"e": 2087,
"s": 1813,
"text": null
},
{
"code": null,
"e": 2095,
"s": 2087,
"text": "Output:"
},
{
"code": null,
"e": 2465,
"s": 2095,
"text": "There are many ways you can plot correlation matrices one efficient way is using the heatmap. It is very easy to understand the correlation using heatmaps it tells the correlation of one feature(variable) to every other feature(variable). In other words, A correlation matrix is a tabular data representing the βcorrelationsβ between pairs of variables in a given data."
},
{
"code": null,
"e": 2473,
"s": 2465,
"text": "Python3"
},
{
"code": "import seaborn as sns # checking correlation using heatmap#Loading datasetflights = sns.load_dataset(\"flights\") #ploting the heatmap for correlationax = sns.heatmap(flights.corr(), annot=True)",
"e": 2668,
"s": 2473,
"text": null
},
{
"code": null,
"e": 2676,
"s": 2668,
"text": "Output:"
},
{
"code": null,
"e": 2694,
"s": 2676,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2709,
"s": 2694,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 2716,
"s": 2709,
"text": "Python"
}
] |
Python PIL | ImageDraw.Draw.rectangle()
|
02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.rectangle() Draws an rectangle.
Syntax: PIL.ImageDraw.Draw.rectangle(xy, fill=None, outline=None)Parameters:
xy β Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.outline β Color to use for the outline.fill β Color to use for the fill.
Returns: An Image object in rectangle shape.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.rectangle(shape, fill ="# ffff33", outline ="red")img.show()
Output:
Another Example: Here we use different colour for filling.
# importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new("RGB", (w, h)) # create rectangleimageimg1 = ImageDraw.Draw(img) img1.rectangle(shape, fill ="# 800080", outline ="green")img.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 332,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use."
},
{
"code": null,
"e": 379,
"s": 332,
"text": "ImageDraw.Draw.rectangle() Draws an rectangle."
},
{
"code": null,
"e": 456,
"s": 379,
"text": "Syntax: PIL.ImageDraw.Draw.rectangle(xy, fill=None, outline=None)Parameters:"
},
{
"code": null,
"e": 688,
"s": 456,
"text": "xy β Four points to define the bounding box. Sequence of either [(x0, y0), (x1, y1)] or [x0, y0, x1, y1]. The second point is just outside the drawn rectangle.outline β Color to use for the outline.fill β Color to use for the fill."
},
{
"code": null,
"e": 733,
"s": 688,
"text": "Returns: An Image object in rectangle shape."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create rectangle imageimg1 = ImageDraw.Draw(img) img1.rectangle(shape, fill =\"# ffff33\", outline =\"red\")img.show()",
"e": 1046,
"s": 733,
"text": null
},
{
"code": null,
"e": 1054,
"s": 1046,
"text": "Output:"
},
{
"code": null,
"e": 1113,
"s": 1054,
"text": "Another Example: Here we use different colour for filling."
},
{
"code": " # importing image object from PILimport mathfrom PIL import Image, ImageDraw w, h = 220, 190shape = [(40, 40), (w - 10, h - 10)] # creating new Image objectimg = Image.new(\"RGB\", (w, h)) # create rectangleimageimg1 = ImageDraw.Draw(img) img1.rectangle(shape, fill =\"# 800080\", outline =\"green\")img.show()",
"e": 1428,
"s": 1113,
"text": null
},
{
"code": null,
"e": 1436,
"s": 1428,
"text": "Output:"
},
{
"code": null,
"e": 1447,
"s": 1436,
"text": "Python-pil"
},
{
"code": null,
"e": 1454,
"s": 1447,
"text": "Python"
}
] |
Python statistics | pvariance()
|
20 Oct, 2021
Prerequisite : Python statistics | variance()pvariance() function helps to calculate the variance of an entire, rather than that of a sample. The only difference between variance() and pvariance() is that while using variance(), only the sample mean is taken into consideration, while during pvariance(), the mean of entire population is taken into consideration.Population variance is just similar to sample variance, it tells how data points in a specific population are spread out. It is the average of the distance from the data-points to the mean of the data-set, squared. The population variance is a parameter of the population and is not dependent on research methods or sampling practices.
Syntax : pvariance( [data], mu)Parameters : [data] : An iterable with real valued numbers. mu (optional): Takes actual mean of data-set/ population as value.Returnype : Returns the actual population variance of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2-values passed as parameter. Impossible values when the value provided as mu doesnβt match actual mean of the data-set.
Code #1 :
Python3
# Python code to demonstrate the# use of pvariance() # importing statistics moduleimport statistics # creating a random population listpopulation = (1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.9, 2.2, 2.3, 2.4, 2.6, 2.9, 3.0, 3.4, 3.3, 3.2) # Prints the population varianceprint("Population variance is %s" %(statistics.pvariance(population)))
Output :
Population variance is 0.6658984375
Code #2 : Demonstrates pvariance() on a different range of population trees.
Python3
# Python code to demonstrate pvariance()# on various range of population sets # importing statistics modulefrom statistics import pvariance # importing fractions module as Ffrom fractions import Fraction as F # Population tree for a set of positive integerspop1 = (1, 2, 3, 5, 4, 6, 1, 2, 2, 3, 1, 3, 7, 8, 9, 1, 1, 1, 2, 6, 7, 8, 9, ) # Creating a population tree for# a set of negative integerspop2 = (-36, -35, -34, -32, -30, -31, -33, -33, -33, -38, -36, -35, -34, -38, -40, -31, -32) # Creating a population tree for# a set of fractional numberspop3 = (F(1, 3), F(2, 4), F(2, 3), F(3, 2), F(2, 5), F(2, 2), F(1, 1), F(1, 4), F(1, 2), F(2, 1)) # Creating a population tree for# a set of decimal valuespop4 = (3.45, 3.2, 2.5, 4.6, 5.66, 6.43, 4.32, 4.23, 6.65, 7.87, 9.87, 1.23, 1.00, 1.45, 10.12, 12.22, 19.88) # Print the population variance for# the created population treesprint("Population variance of set 1 is % s" %(pvariance(pop1))) print("Population variance of set 2 is % s" %(pvariance(pop2))) print("Population variance of set 3 is % s" %(pvariance(pop3))) print("Population variance of set 4 is % s" %(pvariance(pop4)))
Output :
Population variance of set 1 is 7.913043478260869
Population variance of set 2 is 7.204152249134948
Population variance of set 3 is 103889/360000
Population variance of set 4 is 21.767923875432526
Code #3 : Demonstrates the use of mu parameter.
Python3
# Python code to demonstrate the use# of 'mu' parameter on pvariance() # importing statistics moduleimport statistics # Apparently, the Python interpreter doesn't# even check whether the value entered for mu# is the actual mean of data-set or not.# Thus providing incorrect value would# lead to impossible answers # Creating a population tree of the# age of kids in a localitytree = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 12, 12, 13, 1, 2, 12, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6) # Finding the mean of population treem = statistics.mean(tree) # Using the mu parameter# while using pvariance()print("Population Variance is % s" %(statistics.pvariance(tree, mu = m)))
Output :
Population Variance is 14.30385015608741
Code #4 : Demonstrate the difference between pvariance() and variance()
Python3
# Python code to demonstrate the# difference between pvariance()# and variance() # importing statistocs moduleimport statistics # Population tree and extract# a sample from ittree = (1.1, 1.22, .23, .55, .67, 2.33, 2.81, 1.54, 1.2, 0.2, 0.1, 1.22, 1.61) # Sample extract from population treesample = (1.22, .23, .55, .67, 2.33, 2.81, 1.54, 1.2, 0.2) # Print sample variance and as# well as population varianceprint ("Variance of whole popuation is %s" %(statistics.pvariance(tree))) print ("Variance of sample from population is %s " % (statistics.variance(sample))) # Print the difference in both population# variance and sample varianceprint("\n") print("Difference in Population variance" "and Sample variance is % s" %(abs(statistics.pvariance(tree) - statistics.variance(sample))))
Output :
Variance of the whole popuation is 0.6127751479289941
Variance of the sample from population is 0.8286277777777779
Difference in Population variance and Sample variance is 0.21585262984878373
Note : We can see from the above sample example that Population Variance and Sample Variance doesnβt differ by a huge value. Code #5 : Demonstrates StatisticsError
Python3
# Python code to demonstrate StatisticsError # importing statistics moduleimport statistics # creating an empty population setpop = () # will raise StatisticsErrorprint(statistics.pvariance(pop))
Output :
Traceback (most recent call last):
File "/home/fa112e1405f09970eeddd48214318a3c.py", line 10, in
print(statistics.pvariance(pop))
File "/usr/lib/python3.5/statistics.py", line 603, in pvariance
raise StatisticsError('pvariance requires at least one data point')
statistics.StatisticsError: pvariance requires at least one data point
Applications : The applications of Population Variance is much similar to Sample Variance, although the range of population variance is much larger than sample variance. Population variance is only to be used when the variance of an entire population is to be calculated, otherwise for calculating the variance of a sample, variance() is preferred. Population Variance is a very important tool in Statistics and handling huge amounts of data. Like, when the omniscient mean is unknown (sample mean) then variance is used as biased estimator.
nidhi_biet
prachisoda1234
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 729,
"s": 28,
"text": "Prerequisite : Python statistics | variance()pvariance() function helps to calculate the variance of an entire, rather than that of a sample. The only difference between variance() and pvariance() is that while using variance(), only the sample mean is taken into consideration, while during pvariance(), the mean of entire population is taken into consideration.Population variance is just similar to sample variance, it tells how data points in a specific population are spread out. It is the average of the distance from the data-points to the mean of the data-set, squared. The population variance is a parameter of the population and is not dependent on research methods or sampling practices. "
},
{
"code": null,
"e": 1156,
"s": 729,
"text": "Syntax : pvariance( [data], mu)Parameters : [data] : An iterable with real valued numbers. mu (optional): Takes actual mean of data-set/ population as value.Returnype : Returns the actual population variance of the values passed as parameter.Exceptions : StatisticsError is raised for data-set less than 2-values passed as parameter. Impossible values when the value provided as mu doesnβt match actual mean of the data-set. "
},
{
"code": null,
"e": 1167,
"s": 1156,
"text": "Code #1 : "
},
{
"code": null,
"e": 1175,
"s": 1167,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the# use of pvariance() # importing statistics moduleimport statistics # creating a random population listpopulation = (1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.9, 2.2, 2.3, 2.4, 2.6, 2.9, 3.0, 3.4, 3.3, 3.2) # Prints the population varianceprint(\"Population variance is %s\" %(statistics.pvariance(population)))",
"e": 1524,
"s": 1175,
"text": null
},
{
"code": null,
"e": 1535,
"s": 1524,
"text": "Output : "
},
{
"code": null,
"e": 1571,
"s": 1535,
"text": "Population variance is 0.6658984375"
},
{
"code": null,
"e": 1652,
"s": 1571,
"text": " Code #2 : Demonstrates pvariance() on a different range of population trees. "
},
{
"code": null,
"e": 1660,
"s": 1652,
"text": "Python3"
},
{
"code": "# Python code to demonstrate pvariance()# on various range of population sets # importing statistics modulefrom statistics import pvariance # importing fractions module as Ffrom fractions import Fraction as F # Population tree for a set of positive integerspop1 = (1, 2, 3, 5, 4, 6, 1, 2, 2, 3, 1, 3, 7, 8, 9, 1, 1, 1, 2, 6, 7, 8, 9, ) # Creating a population tree for# a set of negative integerspop2 = (-36, -35, -34, -32, -30, -31, -33, -33, -33, -38, -36, -35, -34, -38, -40, -31, -32) # Creating a population tree for# a set of fractional numberspop3 = (F(1, 3), F(2, 4), F(2, 3), F(3, 2), F(2, 5), F(2, 2), F(1, 1), F(1, 4), F(1, 2), F(2, 1)) # Creating a population tree for# a set of decimal valuespop4 = (3.45, 3.2, 2.5, 4.6, 5.66, 6.43, 4.32, 4.23, 6.65, 7.87, 9.87, 1.23, 1.00, 1.45, 10.12, 12.22, 19.88) # Print the population variance for# the created population treesprint(\"Population variance of set 1 is % s\" %(pvariance(pop1))) print(\"Population variance of set 2 is % s\" %(pvariance(pop2))) print(\"Population variance of set 3 is % s\" %(pvariance(pop3))) print(\"Population variance of set 4 is % s\" %(pvariance(pop4)))",
"e": 3013,
"s": 1660,
"text": null
},
{
"code": null,
"e": 3024,
"s": 3013,
"text": "Output : "
},
{
"code": null,
"e": 3221,
"s": 3024,
"text": "Population variance of set 1 is 7.913043478260869\nPopulation variance of set 2 is 7.204152249134948\nPopulation variance of set 3 is 103889/360000\nPopulation variance of set 4 is 21.767923875432526"
},
{
"code": null,
"e": 3273,
"s": 3221,
"text": " Code #3 : Demonstrates the use of mu parameter. "
},
{
"code": null,
"e": 3281,
"s": 3273,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the use# of 'mu' parameter on pvariance() # importing statistics moduleimport statistics # Apparently, the Python interpreter doesn't# even check whether the value entered for mu# is the actual mean of data-set or not.# Thus providing incorrect value would# lead to impossible answers # Creating a population tree of the# age of kids in a localitytree = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 12, 12, 13, 1, 2, 12, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6) # Finding the mean of population treem = statistics.mean(tree) # Using the mu parameter# while using pvariance()print(\"Population Variance is % s\" %(statistics.pvariance(tree, mu = m)))",
"e": 3978,
"s": 3281,
"text": null
},
{
"code": null,
"e": 3989,
"s": 3978,
"text": "Output : "
},
{
"code": null,
"e": 4030,
"s": 3989,
"text": "Population Variance is 14.30385015608741"
},
{
"code": null,
"e": 4106,
"s": 4030,
"text": " Code #4 : Demonstrate the difference between pvariance() and variance() "
},
{
"code": null,
"e": 4114,
"s": 4106,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the# difference between pvariance()# and variance() # importing statistocs moduleimport statistics # Population tree and extract# a sample from ittree = (1.1, 1.22, .23, .55, .67, 2.33, 2.81, 1.54, 1.2, 0.2, 0.1, 1.22, 1.61) # Sample extract from population treesample = (1.22, .23, .55, .67, 2.33, 2.81, 1.54, 1.2, 0.2) # Print sample variance and as# well as population varianceprint (\"Variance of whole popuation is %s\" %(statistics.pvariance(tree))) print (\"Variance of sample from population is %s \" % (statistics.variance(sample))) # Print the difference in both population# variance and sample varianceprint(\"\\n\") print(\"Difference in Population variance\" \"and Sample variance is % s\" %(abs(statistics.pvariance(tree) - statistics.variance(sample))))",
"e": 4992,
"s": 4114,
"text": null
},
{
"code": null,
"e": 5003,
"s": 4992,
"text": "Output : "
},
{
"code": null,
"e": 5197,
"s": 5003,
"text": "Variance of the whole popuation is 0.6127751479289941\nVariance of the sample from population is 0.8286277777777779 \n\nDifference in Population variance and Sample variance is 0.21585262984878373"
},
{
"code": null,
"e": 5365,
"s": 5197,
"text": "Note : We can see from the above sample example that Population Variance and Sample Variance doesnβt differ by a huge value. Code #5 : Demonstrates StatisticsError "
},
{
"code": null,
"e": 5373,
"s": 5365,
"text": "Python3"
},
{
"code": "# Python code to demonstrate StatisticsError # importing statistics moduleimport statistics # creating an empty population setpop = () # will raise StatisticsErrorprint(statistics.pvariance(pop))",
"e": 5569,
"s": 5373,
"text": null
},
{
"code": null,
"e": 5580,
"s": 5569,
"text": "Output : "
},
{
"code": null,
"e": 5926,
"s": 5580,
"text": "Traceback (most recent call last):\n File \"/home/fa112e1405f09970eeddd48214318a3c.py\", line 10, in \n print(statistics.pvariance(pop))\n File \"/usr/lib/python3.5/statistics.py\", line 603, in pvariance\n raise StatisticsError('pvariance requires at least one data point')\nstatistics.StatisticsError: pvariance requires at least one data point"
},
{
"code": null,
"e": 6471,
"s": 5926,
"text": " Applications : The applications of Population Variance is much similar to Sample Variance, although the range of population variance is much larger than sample variance. Population variance is only to be used when the variance of an entire population is to be calculated, otherwise for calculating the variance of a sample, variance() is preferred. Population Variance is a very important tool in Statistics and handling huge amounts of data. Like, when the omniscient mean is unknown (sample mean) then variance is used as biased estimator. "
},
{
"code": null,
"e": 6482,
"s": 6471,
"text": "nidhi_biet"
},
{
"code": null,
"e": 6497,
"s": 6482,
"text": "prachisoda1234"
},
{
"code": null,
"e": 6523,
"s": 6497,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 6530,
"s": 6523,
"text": "Python"
},
{
"code": null,
"e": 6628,
"s": 6530,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6660,
"s": 6628,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6687,
"s": 6660,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6708,
"s": 6687,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6731,
"s": 6708,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6762,
"s": 6731,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6818,
"s": 6762,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6860,
"s": 6818,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6902,
"s": 6860,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6941,
"s": 6902,
"text": "Python | Get unique values from a list"
}
] |
Node.js process.argv Property
|
12 Oct, 2021
The process.argv property is an inbuilt application programming interface of the process module which is used to get the arguments passed to the node.js process when run in the command line.
Syntax:
process.argv
Return Value: This property returns an array containing the arguments passed to the process when run it in the command line. The first element is the process execution path and the second element is the path for the js file.
Below examples illustrate the use of process.argv property in Node.js:
Example 1:
// Node.js program to demonstrate the// process.argv Property // Include process moduleconst process = require('process'); // Printing process.argv property valueconsole.log(process.argv);
Command to run the code:
node index.js extra_argument1 extra_argument2 3
Output:
[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\nodejs\\g\\process\\argv_1.js',
'extra_argument1',
'extra_argument2',
'3'
]
Example 2:
// Node.js program to demonstrate the// process.argv Property // Include process moduleconst process = require('process'); // Printing process.argv property valuevar args = process.argv; console.log("number of arguments is "+args.length); args.forEach((val, index) => { console.log(`${index}: ${val}`);});
Command to run the code:
node index.js extra_argument1 extra_argument2 3
Output:
number of arguments is 5
0: C:\Program Files\nodejs\node.exe
1: C:\nodejs\g\process\argv_2.js
2: extra_argument1
3: extra_argument2
4: 3
Note: The above program will compile and run by using the node filename.js command followed by arguments.
Reference: https://nodejs.org/api/process.html#process_process_argv
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 219,
"s": 28,
"text": "The process.argv property is an inbuilt application programming interface of the process module which is used to get the arguments passed to the node.js process when run in the command line."
},
{
"code": null,
"e": 227,
"s": 219,
"text": "Syntax:"
},
{
"code": null,
"e": 240,
"s": 227,
"text": "process.argv"
},
{
"code": null,
"e": 465,
"s": 240,
"text": "Return Value: This property returns an array containing the arguments passed to the process when run it in the command line. The first element is the process execution path and the second element is the path for the js file."
},
{
"code": null,
"e": 536,
"s": 465,
"text": "Below examples illustrate the use of process.argv property in Node.js:"
},
{
"code": null,
"e": 547,
"s": 536,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// process.argv Property // Include process moduleconst process = require('process'); // Printing process.argv property valueconsole.log(process.argv);",
"e": 739,
"s": 547,
"text": null
},
{
"code": null,
"e": 764,
"s": 739,
"text": "Command to run the code:"
},
{
"code": null,
"e": 812,
"s": 764,
"text": "node index.js extra_argument1 extra_argument2 3"
},
{
"code": null,
"e": 820,
"s": 812,
"text": "Output:"
},
{
"code": null,
"e": 952,
"s": 820,
"text": "[ 'C:\\\\Program Files\\\\nodejs\\\\node.exe',\n 'C:\\\\nodejs\\\\g\\\\process\\\\argv_1.js',\n 'extra_argument1',\n 'extra_argument2',\n '3' \n]\n"
},
{
"code": null,
"e": 963,
"s": 952,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// process.argv Property // Include process moduleconst process = require('process'); // Printing process.argv property valuevar args = process.argv; console.log(\"number of arguments is \"+args.length); args.forEach((val, index) => { console.log(`${index}: ${val}`);});",
"e": 1277,
"s": 963,
"text": null
},
{
"code": null,
"e": 1302,
"s": 1277,
"text": "Command to run the code:"
},
{
"code": null,
"e": 1350,
"s": 1302,
"text": "node index.js extra_argument1 extra_argument2 3"
},
{
"code": null,
"e": 1358,
"s": 1350,
"text": "Output:"
},
{
"code": null,
"e": 1496,
"s": 1358,
"text": "number of arguments is 5\n0: C:\\Program Files\\nodejs\\node.exe\n1: C:\\nodejs\\g\\process\\argv_2.js\n2: extra_argument1\n3: extra_argument2\n4: 3\n"
},
{
"code": null,
"e": 1602,
"s": 1496,
"text": "Note: The above program will compile and run by using the node filename.js command followed by arguments."
},
{
"code": null,
"e": 1670,
"s": 1602,
"text": "Reference: https://nodejs.org/api/process.html#process_process_argv"
},
{
"code": null,
"e": 1693,
"s": 1670,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 1701,
"s": 1693,
"text": "Node.js"
},
{
"code": null,
"e": 1718,
"s": 1701,
"text": "Web Technologies"
}
] |
Pull to Refresh with ListView in Android with Example
|
17 Nov, 2020
The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. It uses a vertical swipe gesture to refresh the content of the views. SwipeRefreshLayout widget detects the vertical swipe and display distinct progress bars and triggers the callback methods in the app. To use this behavior SwipeRefreshLayout widget must be the parent of ListView or GridView. This behavior of the SwipeRefreshLayout widget gives the user to refresh the layout manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs.
Swipe-to-Refresh ListView is very much similar to Swipe-to-Refresh RecyclerView. In place of ListView, we use RecyclerView. Please refer to Pull to Refresh with RecyclerView in Android with Example.
In this example, we would store data of string type into the ArrayList which is used for populating the ListView. Whenever OnRefresh() method is called ArrayList data gets shuffled. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependencies
We are using SwipeRefreshLayout. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency you need to click on Sync Now.
dependencies {
implementation βandroidx.swiperefreshlayout:swiperefreshlayout:1.1.0β
}
Before moving further letβs add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.
XML
<resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources>
Step 3: Working with the activity_main.xml file
In this step, we will create SwipeRefreshLayout and add ListView to it. Go to app > res > layout > activity_main.xml and add the following code snippet.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/swipeRefreshLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--ListView to store list items--> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Step 4: Working with the MainActivity.java file
In this step, we get the reference of SwipeRefreshLayout and ListView which we define in our activiy_main.xml layout file. We will create an ArrayList of string elements and implement ArrayAdapter in order to set data to the list. And then, we implement setOnRefreshListener event on SwipeRefreshLayout and call OnRefresh() method to shuffle the list elements.
Java
import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.appcompat.app.AppCompatActivity;import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Random; public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; ListView listView; ArrayList<String> arrayList = new ArrayList<>(Arrays.asList("C-Language", "Java", "Data Structure", "Networking", "Operating System", "Compiler Design", "Theory Of Computation", "Software Engineering", "Web Engineering")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting the reference of SwipeRefreshLayout and ListView swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); listView = (ListView) findViewById(R.id.listView); // simple_list_item_1 is a built in layout. It is part of Android OS, instead of creating our own // xml layout we are using built-in layout ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList); listView.setAdapter(arrayAdapter); // Implementing setOnRefreshListener on SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(false); // User defined method to shuffle the array list items shuffleListItems(); } }); } public void shuffleListItems() { // Shuffling the arraylist items on the basis of system time Collections.shuffle(arrayList, new Random(System.currentTimeMillis())); ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList); listView.setAdapter(arrayAdapter); }}
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 866,
"s": 53,
"text": "The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. It uses a vertical swipe gesture to refresh the content of the views. SwipeRefreshLayout widget detects the vertical swipe and display distinct progress bars and triggers the callback methods in the app. To use this behavior SwipeRefreshLayout widget must be the parent of ListView or GridView. This behavior of the SwipeRefreshLayout widget gives the user to refresh the layout manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs. "
},
{
"code": null,
"e": 1065,
"s": 866,
"text": "Swipe-to-Refresh ListView is very much similar to Swipe-to-Refresh RecyclerView. In place of ListView, we use RecyclerView. Please refer to Pull to Refresh with RecyclerView in Android with Example."
},
{
"code": null,
"e": 1412,
"s": 1065,
"text": "In this example, we would store data of string type into the ArrayList which is used for populating the ListView. Whenever OnRefresh() method is called ArrayList data gets shuffled. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 1441,
"s": 1412,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1603,
"s": 1441,
"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": 1631,
"s": 1603,
"text": "Step 2: Adding dependencies"
},
{
"code": null,
"e": 1874,
"s": 1631,
"text": "We are using SwipeRefreshLayout. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency you need to click on Sync Now."
},
{
"code": null,
"e": 1890,
"s": 1874,
"text": "dependencies { "
},
{
"code": null,
"e": 1961,
"s": 1890,
"text": "implementation βandroidx.swiperefreshlayout:swiperefreshlayout:1.1.0β "
},
{
"code": null,
"e": 1963,
"s": 1961,
"text": "}"
},
{
"code": null,
"e": 2128,
"s": 1963,
"text": "Before moving further letβs add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes."
},
{
"code": null,
"e": 2132,
"s": 2128,
"text": "XML"
},
{
"code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ",
"e": 2302,
"s": 2132,
"text": null
},
{
"code": null,
"e": 2350,
"s": 2302,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2503,
"s": 2350,
"text": "In this step, we will create SwipeRefreshLayout and add ListView to it. Go to app > res > layout > activity_main.xml and add the following code snippet."
},
{
"code": null,
"e": 2507,
"s": 2503,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/swipeRefreshLayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--ListView to store list items--> <ListView android:id=\"@+id/listView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>",
"e": 3102,
"s": 2507,
"text": null
},
{
"code": null,
"e": 3150,
"s": 3102,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 3511,
"s": 3150,
"text": "In this step, we get the reference of SwipeRefreshLayout and ListView which we define in our activiy_main.xml layout file. We will create an ArrayList of string elements and implement ArrayAdapter in order to set data to the list. And then, we implement setOnRefreshListener event on SwipeRefreshLayout and call OnRefresh() method to shuffle the list elements."
},
{
"code": null,
"e": 3516,
"s": 3511,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.ListView;import androidx.appcompat.app.AppCompatActivity;import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Random; public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; ListView listView; ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(\"C-Language\", \"Java\", \"Data Structure\", \"Networking\", \"Operating System\", \"Compiler Design\", \"Theory Of Computation\", \"Software Engineering\", \"Web Engineering\")); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Getting the reference of SwipeRefreshLayout and ListView swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); listView = (ListView) findViewById(R.id.listView); // simple_list_item_1 is a built in layout. It is part of Android OS, instead of creating our own // xml layout we are using built-in layout ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList); listView.setAdapter(arrayAdapter); // Implementing setOnRefreshListener on SwipeRefreshLayout swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(false); // User defined method to shuffle the array list items shuffleListItems(); } }); } public void shuffleListItems() { // Shuffling the arraylist items on the basis of system time Collections.shuffle(arrayList, new Random(System.currentTimeMillis())); ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList); listView.setAdapter(arrayAdapter); }}",
"e": 5620,
"s": 3516,
"text": null
},
{
"code": null,
"e": 5628,
"s": 5620,
"text": "android"
},
{
"code": null,
"e": 5635,
"s": 5628,
"text": "Picked"
},
{
"code": null,
"e": 5659,
"s": 5635,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5667,
"s": 5659,
"text": "Android"
},
{
"code": null,
"e": 5672,
"s": 5667,
"text": "Java"
},
{
"code": null,
"e": 5691,
"s": 5672,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5696,
"s": 5691,
"text": "Java"
},
{
"code": null,
"e": 5704,
"s": 5696,
"text": "Android"
}
] |
Securing Django Admin login with OTP (2 Factor Authentication)
|
01 Nov, 2020
Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here β Building Blog CMS (Content Management System) with Django
We will install TOTP package for our blog CMS which will add OTP security for our admin login. First install django-otp package
pip install django-otp
and add βdjango_otp, django_otp.plugins.otp_totpβ in our installed apps and django_otp.middleware.OTPMiddleware in middleware section of our settings file.
Python3
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_otp', 'django_otp.plugins.otp_totp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_otp.middleware.OTPMiddleware']
Now run,
# migrate our app
python3 manage.py migrate
Now log into django admin to create an TOTP device. You can see it after logging in
login page
Click add and fill the details to create a new TOTP qrcode
add TOTP devices
Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps.
scan the qrcode
Now go into django urls.py file in gfgblog, not in blog urls.py and add the lines
Python3
from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite
Now logout and login into django admin you have enter OTP everytime you need to login into django admin.
django admin with OTP
Keep Debug = False in Production
Limit Allowed hosted to our Server IP, localhost, and hostnames
Keep Secret key strong and safe
All ways use HTTPS in Production
Keep a check on user uploads if being managed by multiple users
Keep your database secure and donβt use SQLite in Production
Try to use Security and content headers in production, a few headers are given below add these in Settings.py
Python3
SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = TrueSESSION_COOKIE_SECURE = TrueSECURE_BROWSER_XSS_FILTER = TrueSECURE_HSTS_SECONDS = 31536000SECURE_HSTS_INCLUDE_SUBDOMAINS = TrueSECURE_HSTS_PRELOAD = TrueSECURE_CONTENT_TYPE_NOSNIFF = TrueCSRF_COOKIE_SECURE = True
Python Django
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Nov, 2020"
},
{
"code": null,
"e": 359,
"s": 28,
"text": "Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here β Building Blog CMS (Content Management System) with Django"
},
{
"code": null,
"e": 487,
"s": 359,
"text": "We will install TOTP package for our blog CMS which will add OTP security for our admin login. First install django-otp package"
},
{
"code": null,
"e": 510,
"s": 487,
"text": "pip install django-otp"
},
{
"code": null,
"e": 668,
"s": 510,
"text": " and add βdjango_otp, django_otp.plugins.otp_totpβ in our installed apps and django_otp.middleware.OTPMiddleware in middleware section of our settings file. "
},
{
"code": null,
"e": 676,
"s": 668,
"text": "Python3"
},
{
"code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_otp', 'django_otp.plugins.otp_totp' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_otp.middleware.OTPMiddleware']",
"e": 1375,
"s": 676,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1375,
"text": "Now run,"
},
{
"code": null,
"e": 1428,
"s": 1384,
"text": "# migrate our app\npython3 manage.py migrate"
},
{
"code": null,
"e": 1512,
"s": 1428,
"text": "Now log into django admin to create an TOTP device. You can see it after logging in"
},
{
"code": null,
"e": 1523,
"s": 1512,
"text": "login page"
},
{
"code": null,
"e": 1582,
"s": 1523,
"text": "Click add and fill the details to create a new TOTP qrcode"
},
{
"code": null,
"e": 1599,
"s": 1582,
"text": "add TOTP devices"
},
{
"code": null,
"e": 1729,
"s": 1599,
"text": " Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps."
},
{
"code": null,
"e": 1745,
"s": 1729,
"text": "scan the qrcode"
},
{
"code": null,
"e": 1827,
"s": 1745,
"text": "Now go into django urls.py file in gfgblog, not in blog urls.py and add the lines"
},
{
"code": null,
"e": 1835,
"s": 1827,
"text": "Python3"
},
{
"code": "from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite",
"e": 1914,
"s": 1835,
"text": null
},
{
"code": null,
"e": 2019,
"s": 1914,
"text": "Now logout and login into django admin you have enter OTP everytime you need to login into django admin."
},
{
"code": null,
"e": 2041,
"s": 2019,
"text": "django admin with OTP"
},
{
"code": null,
"e": 2074,
"s": 2041,
"text": "Keep Debug = False in Production"
},
{
"code": null,
"e": 2138,
"s": 2074,
"text": "Limit Allowed hosted to our Server IP, localhost, and hostnames"
},
{
"code": null,
"e": 2170,
"s": 2138,
"text": "Keep Secret key strong and safe"
},
{
"code": null,
"e": 2204,
"s": 2170,
"text": "All ways use HTTPS in Production"
},
{
"code": null,
"e": 2268,
"s": 2204,
"text": "Keep a check on user uploads if being managed by multiple users"
},
{
"code": null,
"e": 2329,
"s": 2268,
"text": "Keep your database secure and donβt use SQLite in Production"
},
{
"code": null,
"e": 2439,
"s": 2329,
"text": "Try to use Security and content headers in production, a few headers are given below add these in Settings.py"
},
{
"code": null,
"e": 2447,
"s": 2439,
"text": "Python3"
},
{
"code": "SECURE_SSL_REDIRECT = TrueSESSION_COOKIE_SECURE = TrueSESSION_COOKIE_SECURE = TrueSECURE_BROWSER_XSS_FILTER = TrueSECURE_HSTS_SECONDS = 31536000SECURE_HSTS_INCLUDE_SUBDOMAINS = TrueSECURE_HSTS_PRELOAD = TrueSECURE_CONTENT_TYPE_NOSNIFF = TrueCSRF_COOKIE_SECURE = True",
"e": 2714,
"s": 2447,
"text": null
},
{
"code": null,
"e": 2728,
"s": 2714,
"text": "Python Django"
},
{
"code": null,
"e": 2752,
"s": 2728,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2759,
"s": 2752,
"text": "Python"
},
{
"code": null,
"e": 2778,
"s": 2759,
"text": "Technical Scripter"
}
] |
Ruby | Enumerable group_by() function
|
05 Dec, 2019
The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned.
Syntax: enu.group_by { |obj| block }
Parameters: The function takes an optional block according to which grouping is done.
Return Value: It returns a hash.
Example #1:
# Ruby program for group_by method in Enumerable # Initialize enu = (1..10) # Printsenu.group_by { |obj| obj % 4 == 1 }
Output:
{true=>[1, 5, 9], false=>[2, 3, 4, 6, 7, 8, 10]}
Example #2:
# Ruby program for group_by method in Enumerable # Initialize enu = [2, 8, 9, 10, 23] # Printsenu.group_by { |obj| obj % 6 }
Output:
{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 273,
"s": 53,
"text": "The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned."
},
{
"code": null,
"e": 310,
"s": 273,
"text": "Syntax: enu.group_by { |obj| block }"
},
{
"code": null,
"e": 396,
"s": 310,
"text": "Parameters: The function takes an optional block according to which grouping is done."
},
{
"code": null,
"e": 429,
"s": 396,
"text": "Return Value: It returns a hash."
},
{
"code": null,
"e": 441,
"s": 429,
"text": "Example #1:"
},
{
"code": "# Ruby program for group_by method in Enumerable # Initialize enu = (1..10) # Printsenu.group_by { |obj| obj % 4 == 1 }",
"e": 563,
"s": 441,
"text": null
},
{
"code": null,
"e": 571,
"s": 563,
"text": "Output:"
},
{
"code": null,
"e": 621,
"s": 571,
"text": "{true=>[1, 5, 9], false=>[2, 3, 4, 6, 7, 8, 10]}\n"
},
{
"code": null,
"e": 633,
"s": 621,
"text": "Example #2:"
},
{
"code": "# Ruby program for group_by method in Enumerable # Initialize enu = [2, 8, 9, 10, 23] # Printsenu.group_by { |obj| obj % 6 }",
"e": 760,
"s": 633,
"text": null
},
{
"code": null,
"e": 768,
"s": 760,
"text": "Output:"
},
{
"code": null,
"e": 807,
"s": 768,
"text": "{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}\n"
},
{
"code": null,
"e": 829,
"s": 807,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 842,
"s": 829,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 847,
"s": 842,
"text": "Ruby"
}
] |
HTML <hr> color Attribute
|
05 May, 2021
The HTML <hr> color Attribute is used to specify the color of a Horizontal rule. It is not supported by HTML 5.Syntax:
<Hr color= "color_name | hex_number | rgb_number">
Attribute Values:
color_name: It sets the Text color by using the color name. For example βredβ.
hex_number: It sets the text color by using the color hex code. For example β#0000ffβ.
rgb_number: It sets the text color by using the rgb code. For example: βRGB(0, 153, 0)β.
Example:
html
<!DOCTYPE html><html> <head> <title> HTML hr color Attribute </title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <h2> Hr color attribute</h2> <hr width="500px;" color="red" size="10"> <p>Computer science portal</p> <hr width="70%" size="20" color="blue" noshade></body> </html>
Output
hritikbhatnagar2182
HTML-Attributes
HTML-Basics
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": "\n05 May, 2021"
},
{
"code": null,
"e": 149,
"s": 28,
"text": "The HTML <hr> color Attribute is used to specify the color of a Horizontal rule. It is not supported by HTML 5.Syntax: "
},
{
"code": null,
"e": 201,
"s": 149,
"text": "<Hr color= \"color_name | hex_number | rgb_number\"> "
},
{
"code": null,
"e": 221,
"s": 201,
"text": "Attribute Values: "
},
{
"code": null,
"e": 300,
"s": 221,
"text": "color_name: It sets the Text color by using the color name. For example βredβ."
},
{
"code": null,
"e": 387,
"s": 300,
"text": "hex_number: It sets the text color by using the color hex code. For example β#0000ffβ."
},
{
"code": null,
"e": 476,
"s": 387,
"text": "rgb_number: It sets the text color by using the rgb code. For example: βRGB(0, 153, 0)β."
},
{
"code": null,
"e": 487,
"s": 476,
"text": "Example: "
},
{
"code": null,
"e": 492,
"s": 487,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML hr color Attribute </title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <h2> Hr color attribute</h2> <hr width=\"500px;\" color=\"red\" size=\"10\"> <p>Computer science portal</p> <hr width=\"70%\" size=\"20\" color=\"blue\" noshade></body> </html>",
"e": 844,
"s": 492,
"text": null
},
{
"code": null,
"e": 852,
"s": 844,
"text": "Output "
},
{
"code": null,
"e": 876,
"s": 856,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 892,
"s": 876,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 904,
"s": 892,
"text": "HTML-Basics"
},
{
"code": null,
"e": 921,
"s": 904,
"text": "Web Technologies"
}
] |
How to access a collection in MongoDB using Python?
|
30 May, 2022
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability.
1) Getting a list of collection: For getting a list of a MongoDB databaseβs collections list_collection_names() method is used. This method returns a list of collections.Syntax:
list_collection_names()
Example:
Sample Database:
Python3
from pymongo import MongoClient # create an client instance of the# MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # get a list of a MongoDB database's# collectionscollections = db.list_collection_names()print ("collections:", collections, "\n")
Output:
collections: ['Geeks']
2) Check if the collection exist or not: To check if the collection attribute exists for the database use hasattr() method. It returns true if the collection is in database otherwise returns false.
Syntax: hasattr(db, βcollectionnameβ)
Parameters:db: It is database object. collectionname: It is the name of the collection.
Example:
Python3
from pymongo import MongoClient # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # check collection is exists or notprint(hasattr(db, 'Geeks'))
Output:
True
3) Accessing a Collection: To access a MongoDB collection name use the below syntax.
Syntax:
database_object.Collectionname
or
database_object["Collectionname"]
Note: Database_object[βCollectionameβ] can be useful in the case where the name of the collection contains a space in between them i.e. in cases like database_object[βCollection nameβ].Example:
Python3
from pymongo import MongoClient # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG col1 = db["gfg"] print ("Collection:", col1)
Output:
Collection: Collection(Database(MongoClient(host=[βlocalhost:27017β], document_class=dict, tz_aware=False, connect=True), βGFGβ), βgfgβ)
Code_r
Python-mongoDB
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability."
},
{
"code": null,
"e": 386,
"s": 208,
"text": "1) Getting a list of collection: For getting a list of a MongoDB databaseβs collections list_collection_names() method is used. This method returns a list of collections.Syntax:"
},
{
"code": null,
"e": 410,
"s": 386,
"text": "list_collection_names()"
},
{
"code": null,
"e": 421,
"s": 410,
"text": " Example: "
},
{
"code": null,
"e": 438,
"s": 421,
"text": "Sample Database:"
},
{
"code": null,
"e": 446,
"s": 438,
"text": "Python3"
},
{
"code": "from pymongo import MongoClient # create an client instance of the# MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # get a list of a MongoDB database's# collectionscollections = db.list_collection_names()print (\"collections:\", collections, \"\\n\")",
"e": 733,
"s": 446,
"text": null
},
{
"code": null,
"e": 741,
"s": 733,
"text": "Output:"
},
{
"code": null,
"e": 765,
"s": 741,
"text": "collections: ['Geeks'] "
},
{
"code": null,
"e": 964,
"s": 765,
"text": "2) Check if the collection exist or not: To check if the collection attribute exists for the database use hasattr() method. It returns true if the collection is in database otherwise returns false. "
},
{
"code": null,
"e": 1002,
"s": 964,
"text": "Syntax: hasattr(db, βcollectionnameβ)"
},
{
"code": null,
"e": 1091,
"s": 1002,
"text": "Parameters:db: It is database object. collectionname: It is the name of the collection. "
},
{
"code": null,
"e": 1100,
"s": 1091,
"text": "Example:"
},
{
"code": null,
"e": 1108,
"s": 1100,
"text": "Python3"
},
{
"code": "from pymongo import MongoClient # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG # check collection is exists or notprint(hasattr(db, 'Geeks'))",
"e": 1327,
"s": 1108,
"text": null
},
{
"code": null,
"e": 1335,
"s": 1327,
"text": "Output:"
},
{
"code": null,
"e": 1340,
"s": 1335,
"text": "True"
},
{
"code": null,
"e": 1427,
"s": 1340,
"text": "3) Accessing a Collection: To access a MongoDB collection name use the below syntax. "
},
{
"code": null,
"e": 1435,
"s": 1427,
"text": "Syntax:"
},
{
"code": null,
"e": 1503,
"s": 1435,
"text": "database_object.Collectionname\nor\ndatabase_object[\"Collectionname\"]"
},
{
"code": null,
"e": 1697,
"s": 1503,
"text": "Note: Database_object[βCollectionameβ] can be useful in the case where the name of the collection contains a space in between them i.e. in cases like database_object[βCollection nameβ].Example:"
},
{
"code": null,
"e": 1705,
"s": 1697,
"text": "Python3"
},
{
"code": "from pymongo import MongoClient # create an client instance of# the MongoDB classmo_c = MongoClient() # create an instance of 'some_database'db = mo_c.GFG col1 = db[\"gfg\"] print (\"Collection:\", col1)",
"e": 1906,
"s": 1705,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1906,
"text": " Output: "
},
{
"code": null,
"e": 2053,
"s": 1916,
"text": "Collection: Collection(Database(MongoClient(host=[βlocalhost:27017β], document_class=dict, tz_aware=False, connect=True), βGFGβ), βgfgβ)"
},
{
"code": null,
"e": 2060,
"s": 2053,
"text": "Code_r"
},
{
"code": null,
"e": 2075,
"s": 2060,
"text": "Python-mongoDB"
},
{
"code": null,
"e": 2082,
"s": 2075,
"text": "Python"
},
{
"code": null,
"e": 2180,
"s": 2082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2212,
"s": 2180,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2239,
"s": 2212,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2270,
"s": 2239,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2291,
"s": 2270,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2314,
"s": 2291,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2370,
"s": 2314,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2412,
"s": 2370,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2454,
"s": 2412,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2493,
"s": 2454,
"text": "Python | Get unique values from a list"
}
] |
Kotlin generics
|
01 Jun, 2020
Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety.
Creating parameterized classes βA generic type is a class or method that is parameterized over types. We always use angle brackets () to specify the type parameter in the program.
Generic class is defined as follows:
class MyClass<T>(text: T) {
var name = text
}
To create an instance of such a class, we need to provide the type arguments:
val my : MyClass<String> = Myclass<String>("GeeksforGeeks")
If the parameters can be inferred from the arguments of constructor , one is allowed to omit the type arguments:
val my = MyClass("GeeksforGeeks")
Here, GeeksforGeeks has type String, so the compiler figures out that we are talking about Myclass<String>
Advantages of generic β
Type casting is evitable- No need to typecast the object.Type safety- Generic allows only single type of object at a time.Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error.
Type casting is evitable- No need to typecast the object.
Type safety- Generic allows only single type of object at a time.
Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error.
In below example, we create an Company class with primary constructor having single parameter. Now, we try to pass the different type of data in object of Company class as String and Integer. The primary constructor of Company class accept string type (βGeeskforGeeksβ) but gives compile time error when passes Integer type (12).
Kotlin program without generic class-
class Company (text: String) { var x = text init{ println(x) }}fun main(args: Array<String>){ var name: Company = Company("GeeksforGeeks") var rank: Company = Company(12)// compile time error}
Output:
Error:(10, 33) Kotlin: The integer literal does not conform to the expected type String
In order to solve above problem, we can create a generic type class which is user defined that accepts different type of parameters in single class. The class Company of type is a general type class that accepts both Int and String types of parameters.
Kotlin program using generic class-
class Company<T> (text : T){ var x = text init{ println(x) }}fun main(args: Array<String>){ var name: Company<String> = Company<String>("GeeksforGeeks") var rank: Company<Int> = Company<Int>(12)}
Output:
GeeksforGeeks
1234
Unlike Java, Kotlin makes arrays invariant by default. By extension, generic types are invariant in Kotlin. This can be managed by the out and in keywords. Invariance is the property by which a standard generic function/class already defined for a particular data type, cannot accept or return another datatype. Any is the supertype of all other datatypes.Variance is of two types-
Declaration-site variance(using in and out)Use-site variance: Type projection
Declaration-site variance(using in and out)
Use-site variance: Type projection
The out Keyword β
In Kotlin, we can use the out keyword on the generic type which means we can assign this reference to any of its supertypes. The out value can only produced by the given class but can not consumed:
class OutClass<out T>(val value: T) {
fun get(): T {
return value
}
}
Above, we have defined an OutClass class that can produce a value of type T. Then, we can assign an instance of the OutClass to the reference that is a supertype of it:
val out = OutClass("string")
val ref: OutClass<Any> = out
Note: If we have not used the out type in the above class, then given statement will produce a compiler error.
The in Keyword β
If we want to assign it to the reference of its subtype then we can use the in keyword on the generic type. The in keyword can be used only on the parameter type that is consumed, not produced:
class InClass<in T> {
fun toString(value: T): String {
return value.toString()
}
}
Here, we have declared a toString() method that only be consuming a value of type T. Then, we can assign a reference of type Number to the reference of its subtype β Int:
val inClassObject: InClass<Number> = InClass()
val ref<Int> = inClassObject
Note: If we have not used the in type in the above class, then given statement will produce a compiler error.
Covariance implies substituting subtypes is acceptable, but supertypes is not, i.e. the generic function/class may accept subtypes of the datatype it is already defined for, e.g. a generic class defined for Number can accept Int, but a generic class defined for Int cannot accept Number. This can be implemented in Kotlin using the out keyword as follows-
fun main(args: Array<String>) { val x: MyClass<Any> = MyClass<Int>() // Error: Type mismatch val y: MyClass<out Any> = MyClass<String>() // Works since String is a subtype of Any val z: MyClass<out String> = MyClass<Any>() // Error since Any is a supertype of String}class MyClass<T>
We can directly allow covariance by appending out keyword to the declaration site. The following code works just fine.
fun main(args: Array<String>) { val y: MyClass<Any> = MyClass<String>() // Compiles without error}class MyClass<out T>
It is used to substitute a supertype value in the subtypes, i.e. the generic function/class may accept supertypes of the datatype it is already defined for, e.g. a generic class defined for Number cannot accept Int, but a generic class defined for Int can accept Number. It is implemented in Kotlin using the in keyword as follows-
fun main(args: Array<String>) { var a: Container<Dog> = Container<Animal>() //compiles without error var b: Container<Animal> = Container<Dog>() //gives compilation error}open class Animalclass Dog : Animal()class Container<in T>
If we want to copy all the elements of an array of some type into the array of Any type then it can be possible, but to allow the compiler to compile our code we need to annotate the input parameter with the out keyword. This makes the compiler to infer that input argument can be of any type that is a subtype of the Any:
Kotlin program of copying elements of one array into another β
fun copy(from: Array<out Any>, to: Array<Any>) { assert(from.size == to.size) // copying (from) array to (to) array for (i in from.indices) to[i] = from[i] // printing elements of array in which copied for (i in to.indices) { println(to[i]) }}fun main(args :Array<String>) { val ints: Array<Int> = arrayOf(1, 2, 3) val any :Array<Any> = Array<Any>(3) { "" } copy(ints, any) }
Output:
1
2
3
When we do not know about the specific type of the value and we just want to print all the elements of an array then we use star(*) projection.
Kotlin program of using star projections β
// star projection in arrayfun printArray(array: Array<*>) { array.forEach { print(it) }}fun main(args :Array<String>) { val name = arrayOf("Geeks","for","Geeks") printArray(name)}
Output:
GeeksforGeeks
kevilpy
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jun, 2020"
},
{
"code": null,
"e": 246,
"s": 52,
"text": "Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety."
},
{
"code": null,
"e": 426,
"s": 246,
"text": "Creating parameterized classes βA generic type is a class or method that is parameterized over types. We always use angle brackets () to specify the type parameter in the program."
},
{
"code": null,
"e": 463,
"s": 426,
"text": "Generic class is defined as follows:"
},
{
"code": null,
"e": 514,
"s": 463,
"text": "class MyClass<T>(text: T) {\n var name = text\n}\n"
},
{
"code": null,
"e": 592,
"s": 514,
"text": "To create an instance of such a class, we need to provide the type arguments:"
},
{
"code": null,
"e": 652,
"s": 592,
"text": "val my : MyClass<String> = Myclass<String>(\"GeeksforGeeks\")"
},
{
"code": null,
"e": 765,
"s": 652,
"text": "If the parameters can be inferred from the arguments of constructor , one is allowed to omit the type arguments:"
},
{
"code": null,
"e": 801,
"s": 765,
"text": "val my = MyClass(\"GeeksforGeeks\") \n"
},
{
"code": null,
"e": 908,
"s": 801,
"text": "Here, GeeksforGeeks has type String, so the compiler figures out that we are talking about Myclass<String>"
},
{
"code": null,
"e": 932,
"s": 908,
"text": "Advantages of generic β"
},
{
"code": null,
"e": 1177,
"s": 932,
"text": "Type casting is evitable- No need to typecast the object.Type safety- Generic allows only single type of object at a time.Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error."
},
{
"code": null,
"e": 1235,
"s": 1177,
"text": "Type casting is evitable- No need to typecast the object."
},
{
"code": null,
"e": 1301,
"s": 1235,
"text": "Type safety- Generic allows only single type of object at a time."
},
{
"code": null,
"e": 1424,
"s": 1301,
"text": "Compile time safety- Generics code is checked at compile time for the parameterized type so that it avoids run time error."
},
{
"code": null,
"e": 1754,
"s": 1424,
"text": "In below example, we create an Company class with primary constructor having single parameter. Now, we try to pass the different type of data in object of Company class as String and Integer. The primary constructor of Company class accept string type (βGeeskforGeeksβ) but gives compile time error when passes Integer type (12)."
},
{
"code": null,
"e": 1792,
"s": 1754,
"text": "Kotlin program without generic class-"
},
{
"code": "class Company (text: String) { var x = text init{ println(x) }}fun main(args: Array<String>){ var name: Company = Company(\"GeeksforGeeks\") var rank: Company = Company(12)// compile time error}",
"e": 2007,
"s": 1792,
"text": null
},
{
"code": null,
"e": 2015,
"s": 2007,
"text": "Output:"
},
{
"code": null,
"e": 2104,
"s": 2015,
"text": "Error:(10, 33) Kotlin: The integer literal does not conform to the expected type String\n"
},
{
"code": null,
"e": 2357,
"s": 2104,
"text": "In order to solve above problem, we can create a generic type class which is user defined that accepts different type of parameters in single class. The class Company of type is a general type class that accepts both Int and String types of parameters."
},
{
"code": null,
"e": 2393,
"s": 2357,
"text": "Kotlin program using generic class-"
},
{
"code": "class Company<T> (text : T){ var x = text init{ println(x) }}fun main(args: Array<String>){ var name: Company<String> = Company<String>(\"GeeksforGeeks\") var rank: Company<Int> = Company<Int>(12)} ",
"e": 2612,
"s": 2393,
"text": null
},
{
"code": null,
"e": 2620,
"s": 2612,
"text": "Output:"
},
{
"code": null,
"e": 2640,
"s": 2620,
"text": "GeeksforGeeks\n1234\n"
},
{
"code": null,
"e": 3022,
"s": 2640,
"text": "Unlike Java, Kotlin makes arrays invariant by default. By extension, generic types are invariant in Kotlin. This can be managed by the out and in keywords. Invariance is the property by which a standard generic function/class already defined for a particular data type, cannot accept or return another datatype. Any is the supertype of all other datatypes.Variance is of two types-"
},
{
"code": null,
"e": 3100,
"s": 3022,
"text": "Declaration-site variance(using in and out)Use-site variance: Type projection"
},
{
"code": null,
"e": 3144,
"s": 3100,
"text": "Declaration-site variance(using in and out)"
},
{
"code": null,
"e": 3179,
"s": 3144,
"text": "Use-site variance: Type projection"
},
{
"code": null,
"e": 3197,
"s": 3179,
"text": "The out Keyword β"
},
{
"code": null,
"e": 3395,
"s": 3197,
"text": "In Kotlin, we can use the out keyword on the generic type which means we can assign this reference to any of its supertypes. The out value can only produced by the given class but can not consumed:"
},
{
"code": null,
"e": 3482,
"s": 3395,
"text": "class OutClass<out T>(val value: T) {\n fun get(): T {\n return value\n }\n}\n"
},
{
"code": null,
"e": 3651,
"s": 3482,
"text": "Above, we have defined an OutClass class that can produce a value of type T. Then, we can assign an instance of the OutClass to the reference that is a supertype of it:"
},
{
"code": null,
"e": 3714,
"s": 3651,
"text": "val out = OutClass(\"string\")\nval ref: OutClass<Any> = out \n"
},
{
"code": null,
"e": 3825,
"s": 3714,
"text": "Note: If we have not used the out type in the above class, then given statement will produce a compiler error."
},
{
"code": null,
"e": 3842,
"s": 3825,
"text": "The in Keyword β"
},
{
"code": null,
"e": 4036,
"s": 3842,
"text": "If we want to assign it to the reference of its subtype then we can use the in keyword on the generic type. The in keyword can be used only on the parameter type that is consumed, not produced:"
},
{
"code": null,
"e": 4136,
"s": 4036,
"text": "class InClass<in T> {\n fun toString(value: T): String {\n return value.toString()\n }\n}\n"
},
{
"code": null,
"e": 4307,
"s": 4136,
"text": "Here, we have declared a toString() method that only be consuming a value of type T. Then, we can assign a reference of type Number to the reference of its subtype β Int:"
},
{
"code": null,
"e": 4384,
"s": 4307,
"text": "val inClassObject: InClass<Number> = InClass()\nval ref<Int> = inClassObject\n"
},
{
"code": null,
"e": 4494,
"s": 4384,
"text": "Note: If we have not used the in type in the above class, then given statement will produce a compiler error."
},
{
"code": null,
"e": 4850,
"s": 4494,
"text": "Covariance implies substituting subtypes is acceptable, but supertypes is not, i.e. the generic function/class may accept subtypes of the datatype it is already defined for, e.g. a generic class defined for Number can accept Int, but a generic class defined for Int cannot accept Number. This can be implemented in Kotlin using the out keyword as follows-"
},
{
"code": "fun main(args: Array<String>) { val x: MyClass<Any> = MyClass<Int>() // Error: Type mismatch val y: MyClass<out Any> = MyClass<String>() // Works since String is a subtype of Any val z: MyClass<out String> = MyClass<Any>() // Error since Any is a supertype of String}class MyClass<T>",
"e": 5150,
"s": 4850,
"text": null
},
{
"code": null,
"e": 5269,
"s": 5150,
"text": "We can directly allow covariance by appending out keyword to the declaration site. The following code works just fine."
},
{
"code": "fun main(args: Array<String>) { val y: MyClass<Any> = MyClass<String>() // Compiles without error}class MyClass<out T>",
"e": 5395,
"s": 5269,
"text": null
},
{
"code": null,
"e": 5727,
"s": 5395,
"text": "It is used to substitute a supertype value in the subtypes, i.e. the generic function/class may accept supertypes of the datatype it is already defined for, e.g. a generic class defined for Number cannot accept Int, but a generic class defined for Int can accept Number. It is implemented in Kotlin using the in keyword as follows-"
},
{
"code": "fun main(args: Array<String>) { var a: Container<Dog> = Container<Animal>() //compiles without error var b: Container<Animal> = Container<Dog>() //gives compilation error}open class Animalclass Dog : Animal()class Container<in T>",
"e": 5973,
"s": 5727,
"text": null
},
{
"code": null,
"e": 6296,
"s": 5973,
"text": "If we want to copy all the elements of an array of some type into the array of Any type then it can be possible, but to allow the compiler to compile our code we need to annotate the input parameter with the out keyword. This makes the compiler to infer that input argument can be of any type that is a subtype of the Any:"
},
{
"code": null,
"e": 6359,
"s": 6296,
"text": "Kotlin program of copying elements of one array into another β"
},
{
"code": "fun copy(from: Array<out Any>, to: Array<Any>) { assert(from.size == to.size) // copying (from) array to (to) array for (i in from.indices) to[i] = from[i] // printing elements of array in which copied for (i in to.indices) { println(to[i]) }}fun main(args :Array<String>) { val ints: Array<Int> = arrayOf(1, 2, 3) val any :Array<Any> = Array<Any>(3) { \"\" } copy(ints, any) }",
"e": 6773,
"s": 6359,
"text": null
},
{
"code": null,
"e": 6781,
"s": 6773,
"text": "Output:"
},
{
"code": null,
"e": 6788,
"s": 6781,
"text": "1\n2\n3\n"
},
{
"code": null,
"e": 6932,
"s": 6788,
"text": "When we do not know about the specific type of the value and we just want to print all the elements of an array then we use star(*) projection."
},
{
"code": null,
"e": 6975,
"s": 6932,
"text": "Kotlin program of using star projections β"
},
{
"code": "// star projection in arrayfun printArray(array: Array<*>) { array.forEach { print(it) }}fun main(args :Array<String>) { val name = arrayOf(\"Geeks\",\"for\",\"Geeks\") printArray(name)}",
"e": 7166,
"s": 6975,
"text": null
},
{
"code": null,
"e": 7174,
"s": 7166,
"text": "Output:"
},
{
"code": null,
"e": 7188,
"s": 7174,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 7196,
"s": 7188,
"text": "kevilpy"
},
{
"code": null,
"e": 7203,
"s": 7196,
"text": "Picked"
},
{
"code": null,
"e": 7210,
"s": 7203,
"text": "Kotlin"
}
] |
Count number of trees in a forest
|
28 Jul, 2021
Given n nodes of a forest (collection of trees), find the number of trees in the forest.Examples :
Input : edges[] = {0, 1}, {0, 2}, {3, 4}
Output : 2
Explanation : There are 2 trees
0 3
/ \ \
1 2 4
Approach : 1. Apply DFS on every node. 2. Increment count by one if every connected node is visited from one source. 3. Again perform DFS traversal if some nodes yet not visited. 4. Count will give the number of trees in forest.
C++
Java
Python3
C#
Javascript
// CPP program to count number of trees in// a forest.#include<bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to do DFS of graph// recursively from a given vertex u.void DFSUtil(int u, vector<int> adj[], vector<bool> &visited){ visited[u] = true; for (int i=0; i<adj[u].size(); i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited);} // Returns count of tree is the forest// given as adjacency list.int countTrees(vector<int> adj[], int V){ vector<bool> visited(V, false); int res = 0; for (int u=0; u<V; u++) { if (visited[u] == false) { DFSUtil(u, adj, visited); res++; } } return res;} // Driver codeint main(){ int V = 5; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 3, 4); cout << countTrees(adj, V); return 0;}
// Java program to count number of trees in a forest.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { DFSUtil(n,visited); } } } // The function to do DFS traversal. It uses recursive DFSUtil() int countTrees() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; int res = 0; // Call the recursive helper function to print DFS traversal // starting from all vertices one by one for (int i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res; } // Driver code public static void main(String args[]) { Graph g = new Graph(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(3, 4); System.out.println(g.countTrees()); }} // This code is contributed by mayankbansal2
# Python3 program to count number # of trees in a forest. # A utility function to add an# edge in an undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # A utility function to do DFS of graph# recursively from a given vertex u.def DFSUtil(u, adj, visited): visited[u] = True for i in range(len(adj[u])): if (visited[adj[u][i]] == False): DFSUtil(adj[u][i], adj, visited) # Returns count of tree is the# forest given as adjacency list.def countTrees(adj, V): visited = [False] * V res = 0 for u in range(V): if (visited[u] == False): DFSUtil(u, adj, visited) res += 1 return res # Driver codeif __name__ == '__main__': V = 5 adj = [[] for i in range(V)] addEdge(adj, 0, 1) addEdge(adj, 0, 2) addEdge(adj, 3, 4) print(countTrees(adj, V)) # This code is contributed by PranchalK
// C# program to count number of trees in a forest.using System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int> []adj; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool []visited) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) { DFSUtil(n, visited); } } } // The function to do DFS traversal. // It uses recursive DFSUtil() int countTrees() { // Mark all the vertices as not visited // (set as false by default in java) bool []visited = new bool[V]; int res = 0; // Call the recursive helper function // to print DFS traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res; } // Driver code public static void Main(String []args) { Graph g = new Graph(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(3, 4); Console.WriteLine(g.countTrees()); }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to count number of trees in a forest. // This class represents a directed graph// using adjacency list representationvar V; // No. of vertices // Array of lists for// Adjacency List Representationvar adj;// Constructorfunction Graph( v){ V = v; adj = Array.from(Array(v), ()=>Array());}// Function to add an edge into the graphfunction addEdge(v, w){ adj[v].push(w); // Add w to v's list.}// A function used by DFSfunction DFSUtil(v, visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(var i of adj[v]) { var n = i; if (!visited[n]) { DFSUtil(n, visited); } }}// The function to do DFS traversal.// It uses recursive DFSUtil()function countTrees(){ // Mark all the vertices as not visited // (set as false by default in java) var visited = Array(V).fill(false); var res = 0; // Call the recursive helper function // to print DFS traversal starting from // all vertices one by one for(var i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res;} // Driver codeGraph(5);addEdge(0, 1);addEdge(0, 2);addEdge(3, 4);document.write(countTrees()); // This code is contributed by rutvik_56.</script>
2
Time Complexity : O(V + E)
Rajesh Raj 2
PranchalKatiyar
mayankbansal2
princiraj1992
rutvik_56
DFS
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 153,
"s": 52,
"text": "Given n nodes of a forest (collection of trees), find the number of trees in the forest.Examples : "
},
{
"code": null,
"e": 328,
"s": 153,
"text": "Input : edges[] = {0, 1}, {0, 2}, {3, 4}\nOutput : 2\nExplanation : There are 2 trees\n 0 3\n / \\ \\\n 1 2 4"
},
{
"code": null,
"e": 560,
"s": 330,
"text": "Approach : 1. Apply DFS on every node. 2. Increment count by one if every connected node is visited from one source. 3. Again perform DFS traversal if some nodes yet not visited. 4. Count will give the number of trees in forest. "
},
{
"code": null,
"e": 564,
"s": 560,
"text": "C++"
},
{
"code": null,
"e": 569,
"s": 564,
"text": "Java"
},
{
"code": null,
"e": 577,
"s": 569,
"text": "Python3"
},
{
"code": null,
"e": 580,
"s": 577,
"text": "C#"
},
{
"code": null,
"e": 591,
"s": 580,
"text": "Javascript"
},
{
"code": "// CPP program to count number of trees in// a forest.#include<bits/stdc++.h>using namespace std; // A utility function to add an edge in an// undirected graph.void addEdge(vector<int> adj[], int u, int v){ adj[u].push_back(v); adj[v].push_back(u);} // A utility function to do DFS of graph// recursively from a given vertex u.void DFSUtil(int u, vector<int> adj[], vector<bool> &visited){ visited[u] = true; for (int i=0; i<adj[u].size(); i++) if (visited[adj[u][i]] == false) DFSUtil(adj[u][i], adj, visited);} // Returns count of tree is the forest// given as adjacency list.int countTrees(vector<int> adj[], int V){ vector<bool> visited(V, false); int res = 0; for (int u=0; u<V; u++) { if (visited[u] == false) { DFSUtil(u, adj, visited); res++; } } return res;} // Driver codeint main(){ int V = 5; vector<int> adj[V]; addEdge(adj, 0, 1); addEdge(adj, 0, 2); addEdge(adj, 3, 4); cout << countTrees(adj, V); return 0;}",
"e": 1646,
"s": 591,
"text": null
},
{
"code": "// Java program to count number of trees in a forest.import java.io.*;import java.util.*; // This class represents a directed graph using adjacency list// representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { DFSUtil(n,visited); } } } // The function to do DFS traversal. It uses recursive DFSUtil() int countTrees() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; int res = 0; // Call the recursive helper function to print DFS traversal // starting from all vertices one by one for (int i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res; } // Driver code public static void main(String args[]) { Graph g = new Graph(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(3, 4); System.out.println(g.countTrees()); }} // This code is contributed by mayankbansal2",
"e": 3536,
"s": 1646,
"text": null
},
{
"code": "# Python3 program to count number # of trees in a forest. # A utility function to add an# edge in an undirected graph.def addEdge(adj, u, v): adj[u].append(v) adj[v].append(u) # A utility function to do DFS of graph# recursively from a given vertex u.def DFSUtil(u, adj, visited): visited[u] = True for i in range(len(adj[u])): if (visited[adj[u][i]] == False): DFSUtil(adj[u][i], adj, visited) # Returns count of tree is the# forest given as adjacency list.def countTrees(adj, V): visited = [False] * V res = 0 for u in range(V): if (visited[u] == False): DFSUtil(u, adj, visited) res += 1 return res # Driver codeif __name__ == '__main__': V = 5 adj = [[] for i in range(V)] addEdge(adj, 0, 1) addEdge(adj, 0, 2) addEdge(adj, 3, 4) print(countTrees(adj, V)) # This code is contributed by PranchalK",
"e": 4426,
"s": 3536,
"text": null
},
{
"code": "// C# program to count number of trees in a forest.using System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ private int V; // No. of vertices // Array of lists for // Adjacency List Representation private List<int> []adj; // Constructor Graph(int v) { V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); // Add w to v's list. } // A function used by DFS void DFSUtil(int v, bool []visited) { // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex foreach(int i in adj[v]) { int n = i; if (!visited[n]) { DFSUtil(n, visited); } } } // The function to do DFS traversal. // It uses recursive DFSUtil() int countTrees() { // Mark all the vertices as not visited // (set as false by default in java) bool []visited = new bool[V]; int res = 0; // Call the recursive helper function // to print DFS traversal starting from // all vertices one by one for (int i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res; } // Driver code public static void Main(String []args) { Graph g = new Graph(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(3, 4); Console.WriteLine(g.countTrees()); }} // This code is contributed by PrinciRaj1992",
"e": 6293,
"s": 4426,
"text": null
},
{
"code": "<script>// Javascript program to count number of trees in a forest. // This class represents a directed graph// using adjacency list representationvar V; // No. of vertices // Array of lists for// Adjacency List Representationvar adj;// Constructorfunction Graph( v){ V = v; adj = Array.from(Array(v), ()=>Array());}// Function to add an edge into the graphfunction addEdge(v, w){ adj[v].push(w); // Add w to v's list.}// A function used by DFSfunction DFSUtil(v, visited){ // Mark the current node as // visited and print it visited[v] = true; // Recur for all the vertices // adjacent to this vertex for(var i of adj[v]) { var n = i; if (!visited[n]) { DFSUtil(n, visited); } }}// The function to do DFS traversal.// It uses recursive DFSUtil()function countTrees(){ // Mark all the vertices as not visited // (set as false by default in java) var visited = Array(V).fill(false); var res = 0; // Call the recursive helper function // to print DFS traversal starting from // all vertices one by one for(var i = 0; i < V; ++i) { if (visited[i] == false) { DFSUtil(i, visited); res ++; } } return res;} // Driver codeGraph(5);addEdge(0, 1);addEdge(0, 2);addEdge(3, 4);document.write(countTrees()); // This code is contributed by rutvik_56.</script>",
"e": 7699,
"s": 6293,
"text": null
},
{
"code": null,
"e": 7701,
"s": 7699,
"text": "2"
},
{
"code": null,
"e": 7731,
"s": 7703,
"text": "Time Complexity : O(V + E) "
},
{
"code": null,
"e": 7744,
"s": 7731,
"text": "Rajesh Raj 2"
},
{
"code": null,
"e": 7760,
"s": 7744,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 7774,
"s": 7760,
"text": "mayankbansal2"
},
{
"code": null,
"e": 7788,
"s": 7774,
"text": "princiraj1992"
},
{
"code": null,
"e": 7798,
"s": 7788,
"text": "rutvik_56"
},
{
"code": null,
"e": 7802,
"s": 7798,
"text": "DFS"
},
{
"code": null,
"e": 7808,
"s": 7802,
"text": "Graph"
},
{
"code": null,
"e": 7812,
"s": 7808,
"text": "DFS"
},
{
"code": null,
"e": 7818,
"s": 7812,
"text": "Graph"
}
] |
Count triplets such that sum of any two number is equal to third | Set 2
|
13 Aug, 2021
Given an array of distinct positive integers arr[] of length N, the task is to count all the triplets such that sum of two elements equals the third element.
Examples:
Input: arr[] = {1, 5, 3, 2} Output: 2 Explanation: In the given array, there are two such triplets such that sum of the two numbers is equal to the third number, those are β (1, 2, 3), (3, 2, 5)Input: arr[] = {3, 2, 7} Output: 0 Explanation: In the given array there are no such triplets such that sum of two numbers is equal to the third number.
Approach: The idea is to create a frequency array of the numbers which are present in the array and then check for each pair of the element that the sum of the pair elements is present in the array or not with the help of frequency array in O(1) time.Algorithm:
Declare a frequency array to store the frequency of the numbers.
Iterate over the elements of the array and increment the count of that number in the frequency array.
Run two loops to choose two different indexes of the matrix and check if the sum of the elements at those indices has a frequency more than 0 in the frequency array.
If frequency of the sum is greater than 0:
Increment the count of the triplets.
Note: We have assumed in the program that the value of array elements lies in the range [1, 100].Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation to count the// triplets such that the sum of the// two numbers is equal to third number #include <bits/stdc++.h>using namespace std; // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberint countTriplets(int arr[], int n){ int freq[100] = {0}; // Loop to count the frequency for (int i=0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0;i < n; i++){ for(int j = i+1; j < n; j++){ if(freq[arr[i] + arr[j]]){ count++; } } } return count;} // Driver Codeint main(){ int n = 4; int arr[] = {1, 5, 3, 2}; // Function Call cout << countTriplets(arr, n); return 0;}
// Java implementation to count the// triplets such that the sum of the// two numbers is equal to third numberclass GFG{ // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberstatic int countTriplets(int arr[], int n){ int []freq = new int[100]; // Loop to count the frequency for (int i = 0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(freq[arr[i] + arr[j]] > 0){ count++; } } } return count;} // Driver Codepublic static void main(String[] args){ int n = 4; int arr[] = {1, 5, 3, 2}; // Function Call System.out.print(countTriplets(arr, n));}} // This code is contributed by Rajput-Ji
# Python 3 implementation to count the# triplets such that the sum of the# two numbers is equal to third number # Function to find the count of the# triplets such that sum of two# numbers is equal to the third numberdef countTriplets(arr, n): freq = [0 for i in range(100)] # Loop to count the frequency for i in range(n): freq[arr[i]] += 1 count = 0 # Loop to count for triplets for i in range(n): for j in range(i + 1, n, 1): if(freq[arr[i] + arr[j]]): count += 1 return count # Driver Codeif __name__ == '__main__': n = 4 arr = [1, 5, 3, 2] # Function Call print(countTriplets(arr, n)) # This code is contributed by Surendra_Gangwar
// C# implementation to count the// triplets such that the sum of the// two numbers is equal to third numberusing System; class GFG{ // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberstatic int countTriplets(int []arr, int n){ int []freq = new int[100]; // Loop to count the frequency for (int i = 0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(freq[arr[i] + arr[j]] > 0){ count++; } } } return count;} // Driver Codepublic static void Main(string[] args){ int n = 4; int []arr = {1, 5, 3, 2}; // Function Call Console.WriteLine(countTriplets(arr, n));}} // This code is contributed by Yahs_R
<script> // Javascript implementation to count the// triplets such that the sum of the// two numbers is equal to third number // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberfunction countTriplets(arr, n){ let freq = new Uint8Array(100); // Loop to count the frequency for (let i=0; i < n; i++){ freq[arr[i]]++; } let count = 0; // Loop to count for triplets for(let i = 0;i < n; i++){ for(let j = i+1; j < n; j++){ if(freq[arr[i] + arr[j]]){ count++; } } } return count;} // Driver Code let n = 4; let arr = [1, 5, 3, 2]; // Function Call document.write(countTriplets(arr, n)); //This code is contributed by Mayank Tyagi</script>
2
Performance Analysis:
Time Complexity: O(N2).
Auxiliary Space: O(N).
SURENDRA_GANGWAR
Rajput-Ji
Yash_R
nidhi_biet
mayanktyagi1709
pankajsharmagfg
Arrays
Data Structures
Hash
Data Structures
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 212,
"s": 54,
"text": "Given an array of distinct positive integers arr[] of length N, the task is to count all the triplets such that sum of two elements equals the third element."
},
{
"code": null,
"e": 224,
"s": 212,
"text": "Examples: "
},
{
"code": null,
"e": 573,
"s": 224,
"text": "Input: arr[] = {1, 5, 3, 2} Output: 2 Explanation: In the given array, there are two such triplets such that sum of the two numbers is equal to the third number, those are β (1, 2, 3), (3, 2, 5)Input: arr[] = {3, 2, 7} Output: 0 Explanation: In the given array there are no such triplets such that sum of two numbers is equal to the third number. "
},
{
"code": null,
"e": 837,
"s": 573,
"text": "Approach: The idea is to create a frequency array of the numbers which are present in the array and then check for each pair of the element that the sum of the pair elements is present in the array or not with the help of frequency array in O(1) time.Algorithm: "
},
{
"code": null,
"e": 902,
"s": 837,
"text": "Declare a frequency array to store the frequency of the numbers."
},
{
"code": null,
"e": 1004,
"s": 902,
"text": "Iterate over the elements of the array and increment the count of that number in the frequency array."
},
{
"code": null,
"e": 1170,
"s": 1004,
"text": "Run two loops to choose two different indexes of the matrix and check if the sum of the elements at those indices has a frequency more than 0 in the frequency array."
},
{
"code": null,
"e": 1254,
"s": 1170,
"text": "If frequency of the sum is greater than 0:\n Increment the count of the triplets."
},
{
"code": null,
"e": 1403,
"s": 1254,
"text": "Note: We have assumed in the program that the value of array elements lies in the range [1, 100].Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1407,
"s": 1403,
"text": "C++"
},
{
"code": null,
"e": 1412,
"s": 1407,
"text": "Java"
},
{
"code": null,
"e": 1421,
"s": 1412,
"text": "Python 3"
},
{
"code": null,
"e": 1424,
"s": 1421,
"text": "C#"
},
{
"code": null,
"e": 1435,
"s": 1424,
"text": "Javascript"
},
{
"code": "// C++ implementation to count the// triplets such that the sum of the// two numbers is equal to third number #include <bits/stdc++.h>using namespace std; // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberint countTriplets(int arr[], int n){ int freq[100] = {0}; // Loop to count the frequency for (int i=0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0;i < n; i++){ for(int j = i+1; j < n; j++){ if(freq[arr[i] + arr[j]]){ count++; } } } return count;} // Driver Codeint main(){ int n = 4; int arr[] = {1, 5, 3, 2}; // Function Call cout << countTriplets(arr, n); return 0;}",
"e": 2227,
"s": 1435,
"text": null
},
{
"code": "// Java implementation to count the// triplets such that the sum of the// two numbers is equal to third numberclass GFG{ // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberstatic int countTriplets(int arr[], int n){ int []freq = new int[100]; // Loop to count the frequency for (int i = 0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(freq[arr[i] + arr[j]] > 0){ count++; } } } return count;} // Driver Codepublic static void main(String[] args){ int n = 4; int arr[] = {1, 5, 3, 2}; // Function Call System.out.print(countTriplets(arr, n));}} // This code is contributed by Rajput-Ji",
"e": 3074,
"s": 2227,
"text": null
},
{
"code": "# Python 3 implementation to count the# triplets such that the sum of the# two numbers is equal to third number # Function to find the count of the# triplets such that sum of two# numbers is equal to the third numberdef countTriplets(arr, n): freq = [0 for i in range(100)] # Loop to count the frequency for i in range(n): freq[arr[i]] += 1 count = 0 # Loop to count for triplets for i in range(n): for j in range(i + 1, n, 1): if(freq[arr[i] + arr[j]]): count += 1 return count # Driver Codeif __name__ == '__main__': n = 4 arr = [1, 5, 3, 2] # Function Call print(countTriplets(arr, n)) # This code is contributed by Surendra_Gangwar",
"e": 3798,
"s": 3074,
"text": null
},
{
"code": "// C# implementation to count the// triplets such that the sum of the// two numbers is equal to third numberusing System; class GFG{ // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberstatic int countTriplets(int []arr, int n){ int []freq = new int[100]; // Loop to count the frequency for (int i = 0; i < n; i++){ freq[arr[i]]++; } int count = 0; // Loop to count for triplets for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(freq[arr[i] + arr[j]] > 0){ count++; } } } return count;} // Driver Codepublic static void Main(string[] args){ int n = 4; int []arr = {1, 5, 3, 2}; // Function Call Console.WriteLine(countTriplets(arr, n));}} // This code is contributed by Yahs_R",
"e": 4655,
"s": 3798,
"text": null
},
{
"code": "<script> // Javascript implementation to count the// triplets such that the sum of the// two numbers is equal to third number // Function to find the count of the// triplets such that sum of two// numbers is equal to the third numberfunction countTriplets(arr, n){ let freq = new Uint8Array(100); // Loop to count the frequency for (let i=0; i < n; i++){ freq[arr[i]]++; } let count = 0; // Loop to count for triplets for(let i = 0;i < n; i++){ for(let j = i+1; j < n; j++){ if(freq[arr[i] + arr[j]]){ count++; } } } return count;} // Driver Code let n = 4; let arr = [1, 5, 3, 2]; // Function Call document.write(countTriplets(arr, n)); //This code is contributed by Mayank Tyagi</script>",
"e": 5462,
"s": 4655,
"text": null
},
{
"code": null,
"e": 5464,
"s": 5462,
"text": "2"
},
{
"code": null,
"e": 5490,
"s": 5466,
"text": "Performance Analysis: "
},
{
"code": null,
"e": 5514,
"s": 5490,
"text": "Time Complexity: O(N2)."
},
{
"code": null,
"e": 5537,
"s": 5514,
"text": "Auxiliary Space: O(N)."
},
{
"code": null,
"e": 5554,
"s": 5537,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 5564,
"s": 5554,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5571,
"s": 5564,
"text": "Yash_R"
},
{
"code": null,
"e": 5582,
"s": 5571,
"text": "nidhi_biet"
},
{
"code": null,
"e": 5598,
"s": 5582,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 5614,
"s": 5598,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 5621,
"s": 5614,
"text": "Arrays"
},
{
"code": null,
"e": 5637,
"s": 5621,
"text": "Data Structures"
},
{
"code": null,
"e": 5642,
"s": 5637,
"text": "Hash"
},
{
"code": null,
"e": 5658,
"s": 5642,
"text": "Data Structures"
},
{
"code": null,
"e": 5665,
"s": 5658,
"text": "Arrays"
},
{
"code": null,
"e": 5670,
"s": 5665,
"text": "Hash"
},
{
"code": null,
"e": 5768,
"s": 5670,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5836,
"s": 5768,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5880,
"s": 5836,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5912,
"s": 5880,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5960,
"s": 5912,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5974,
"s": 5960,
"text": "Linear Search"
},
{
"code": null,
"e": 5999,
"s": 5974,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 6048,
"s": 5999,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6092,
"s": 6048,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6130,
"s": 6092,
"text": "What is Hashing | A Complete Tutorial"
}
] |
C++ Queue Library - push() Function
|
The C++ function std::queue::push() inserts new element at the end of queue and assigns val to newly inserted element. This member function increases size of queue by one.
This member function effectively calls the push_back() member function of the underlying container.
Following is the declaration for std::queue::push() function form std::queue header.
void push (const value_type& val);
void push (const value_type& val);
val β Value to be assigned to newly inserted element.
None
Constant i.e. O(1)
The following example shows the usage of std::queue::push() function.
#include <iostream>
#include <queue>
using namespace std;
int main(void) {
queue<int> q;
for (int i = 0; i < 5; ++i)
q.push(i + 1);
cout << "Contents of queue" << endl;
while (!q.empty()) {
cout << q.front() << endl;
q.pop();
}
return 0;
}
Let us compile and run the above program, this will produce the following result β
Contents of queue
1
2
3
4
5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2775,
"s": 2603,
"text": "The C++ function std::queue::push() inserts new element at the end of queue and assigns val to newly inserted element. This member function increases size of queue by one."
},
{
"code": null,
"e": 2875,
"s": 2775,
"text": "This member function effectively calls the push_back() member function of the underlying container."
},
{
"code": null,
"e": 2960,
"s": 2875,
"text": "Following is the declaration for std::queue::push() function form std::queue header."
},
{
"code": null,
"e": 2996,
"s": 2960,
"text": "void push (const value_type& val);\n"
},
{
"code": null,
"e": 3032,
"s": 2996,
"text": "void push (const value_type& val);\n"
},
{
"code": null,
"e": 3086,
"s": 3032,
"text": "val β Value to be assigned to newly inserted element."
},
{
"code": null,
"e": 3091,
"s": 3086,
"text": "None"
},
{
"code": null,
"e": 3110,
"s": 3091,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3180,
"s": 3110,
"text": "The following example shows the usage of std::queue::push() function."
},
{
"code": null,
"e": 3461,
"s": 3180,
"text": "#include <iostream>\n#include <queue>\n\nusing namespace std;\n\nint main(void) {\n queue<int> q;\n\n for (int i = 0; i < 5; ++i)\n q.push(i + 1);\n\n cout << \"Contents of queue\" << endl;\n while (!q.empty()) {\n cout << q.front() << endl;\n q.pop();\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 3544,
"s": 3461,
"text": "Let us compile and run the above program, this will produce the following result β"
},
{
"code": null,
"e": 3573,
"s": 3544,
"text": "Contents of queue\n1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 3580,
"s": 3573,
"text": " Print"
},
{
"code": null,
"e": 3591,
"s": 3580,
"text": " Add Notes"
}
] |
Anonymous Method in C# - GeeksforGeeks
|
11 Feb, 2019
An anonymous method is a method which doesnβt contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the user can assign this method to a variable of the delegate type.
Syntax:
delegate(parameter_list){
// Code..
};
Example :
// C# program to illustrate how to // create an anonymous functionusing System; class GFG { public delegate void petanim(string pet); // Main method static public void Main() { // An anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine("My favorite pet is: {0}", mypet); }; p("Dog"); }}
My favorite pet is: Dog
Important Points:
This method is also known as inline delegate.
Using this method you can create a delegate object without writing separate methods.
This method can access variable present in the outer method. Such type of variables is known as Outer variables. As shown in the below example fav is the outer variable.Example:// C# program to illustrate how an // anonymous function access variable// defined in outer methodusing System; class GFG { // Create a delegate public delegate void petanim(string pet); // Main method static public void Main() { string fav = "Rabbit"; // Anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine("My favorite pet is {0}.", mypet); // Accessing variable defined // outside the anonymous function Console.WriteLine("And I like {0} also.", fav); }; p("Dog"); }}Output:My favorite pet is Dog.
And I like Rabbit also.
Example:
// C# program to illustrate how an // anonymous function access variable// defined in outer methodusing System; class GFG { // Create a delegate public delegate void petanim(string pet); // Main method static public void Main() { string fav = "Rabbit"; // Anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine("My favorite pet is {0}.", mypet); // Accessing variable defined // outside the anonymous function Console.WriteLine("And I like {0} also.", fav); }; p("Dog"); }}
My favorite pet is Dog.
And I like Rabbit also.
You can pass this method to another method which accepts delegate as a parameter. As shown in the below example:Example :// C# program to illustrate how an // anonymous method passed as a parameterusing System; public delegate void Show(string x); class GFG { // identity method with two parameters public static void identity(Show mypet, string color) { color = " Black" + color; mypet(color); } // Main method static public void Main() { // Here anonymous method pass as // a parameter in identity method identity(delegate(string color) { Console.WriteLine("The color"+ " of my dog is {0}", color); }, "White"); }}Output:The color of my dog is BlackWhite
Example :
// C# program to illustrate how an // anonymous method passed as a parameterusing System; public delegate void Show(string x); class GFG { // identity method with two parameters public static void identity(Show mypet, string color) { color = " Black" + color; mypet(color); } // Main method static public void Main() { // Here anonymous method pass as // a parameter in identity method identity(delegate(string color) { Console.WriteLine("The color"+ " of my dog is {0}", color); }, "White"); }}
The color of my dog is BlackWhite
In anonymous methods, you are allowed to remove parameter-list, which means you can convert an anonymous method into a delegate.
The anonymous-method-block means the scope of the parameters in the anonymous method.
An anonymous method does not contain jump statements like goto, break, or continue.
An anonymous method does not access unsafe code.
An anonymous method does not access in, ref, and out parameter of the outer scope.
You can not use an anonymous method to the left side of the is operator.
You can also use an anonymous method as an event handler.Example:// C# program to illustrate how an // anonymous method use as a // event handlerMyButton.Click += delegate(Object obj, EventArgs ev){ System.Windows.Forms.MessageBox.Show("Complete without error...!!");}
Example:
// C# program to illustrate how an // anonymous method use as a // event handlerMyButton.Click += delegate(Object obj, EventArgs ev){ System.Windows.Forms.MessageBox.Show("Complete without error...!!");}
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | IsNullOrEmpty() Method
Main Method in C#
C# | Dictionary.Add() Method
Lambda Expressions in C#
Different ways to sort an array in descending order in C#
C# | Arrays of Strings
C# | How to use strings in switch statement
C# | List Class
C# | How to check whether a List contains a specified element
How to find the length of an Array in C#
|
[
{
"code": null,
"e": 24913,
"s": 24885,
"text": "\n11 Feb, 2019"
},
{
"code": null,
"e": 25274,
"s": 24913,
"text": "An anonymous method is a method which doesnβt contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the user can assign this method to a variable of the delegate type."
},
{
"code": null,
"e": 25282,
"s": 25274,
"text": "Syntax:"
},
{
"code": null,
"e": 25326,
"s": 25282,
"text": "delegate(parameter_list){\n // Code..\n};\n"
},
{
"code": null,
"e": 25336,
"s": 25326,
"text": "Example :"
},
{
"code": "// C# program to illustrate how to // create an anonymous functionusing System; class GFG { public delegate void petanim(string pet); // Main method static public void Main() { // An anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine(\"My favorite pet is: {0}\", mypet); }; p(\"Dog\"); }}",
"e": 25777,
"s": 25336,
"text": null
},
{
"code": null,
"e": 25802,
"s": 25777,
"text": "My favorite pet is: Dog\n"
},
{
"code": null,
"e": 25820,
"s": 25802,
"text": "Important Points:"
},
{
"code": null,
"e": 25866,
"s": 25820,
"text": "This method is also known as inline delegate."
},
{
"code": null,
"e": 25951,
"s": 25866,
"text": "Using this method you can create a delegate object without writing separate methods."
},
{
"code": null,
"e": 26856,
"s": 25951,
"text": "This method can access variable present in the outer method. Such type of variables is known as Outer variables. As shown in the below example fav is the outer variable.Example:// C# program to illustrate how an // anonymous function access variable// defined in outer methodusing System; class GFG { // Create a delegate public delegate void petanim(string pet); // Main method static public void Main() { string fav = \"Rabbit\"; // Anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine(\"My favorite pet is {0}.\", mypet); // Accessing variable defined // outside the anonymous function Console.WriteLine(\"And I like {0} also.\", fav); }; p(\"Dog\"); }}Output:My favorite pet is Dog.\nAnd I like Rabbit also.\n"
},
{
"code": null,
"e": 26865,
"s": 26856,
"text": "Example:"
},
{
"code": "// C# program to illustrate how an // anonymous function access variable// defined in outer methodusing System; class GFG { // Create a delegate public delegate void petanim(string pet); // Main method static public void Main() { string fav = \"Rabbit\"; // Anonymous method with one parameter petanim p = delegate(string mypet) { Console.WriteLine(\"My favorite pet is {0}.\", mypet); // Accessing variable defined // outside the anonymous function Console.WriteLine(\"And I like {0} also.\", fav); }; p(\"Dog\"); }}",
"e": 27538,
"s": 26865,
"text": null
},
{
"code": null,
"e": 27587,
"s": 27538,
"text": "My favorite pet is Dog.\nAnd I like Rabbit also.\n"
},
{
"code": null,
"e": 28397,
"s": 27587,
"text": "You can pass this method to another method which accepts delegate as a parameter. As shown in the below example:Example :// C# program to illustrate how an // anonymous method passed as a parameterusing System; public delegate void Show(string x); class GFG { // identity method with two parameters public static void identity(Show mypet, string color) { color = \" Black\" + color; mypet(color); } // Main method static public void Main() { // Here anonymous method pass as // a parameter in identity method identity(delegate(string color) { Console.WriteLine(\"The color\"+ \" of my dog is {0}\", color); }, \"White\"); }}Output:The color of my dog is BlackWhite\n"
},
{
"code": null,
"e": 28407,
"s": 28397,
"text": "Example :"
},
{
"code": "// C# program to illustrate how an // anonymous method passed as a parameterusing System; public delegate void Show(string x); class GFG { // identity method with two parameters public static void identity(Show mypet, string color) { color = \" Black\" + color; mypet(color); } // Main method static public void Main() { // Here anonymous method pass as // a parameter in identity method identity(delegate(string color) { Console.WriteLine(\"The color\"+ \" of my dog is {0}\", color); }, \"White\"); }}",
"e": 29054,
"s": 28407,
"text": null
},
{
"code": null,
"e": 29090,
"s": 29054,
"text": "The color of my dog is BlackWhite\n"
},
{
"code": null,
"e": 29219,
"s": 29090,
"text": "In anonymous methods, you are allowed to remove parameter-list, which means you can convert an anonymous method into a delegate."
},
{
"code": null,
"e": 29305,
"s": 29219,
"text": "The anonymous-method-block means the scope of the parameters in the anonymous method."
},
{
"code": null,
"e": 29389,
"s": 29305,
"text": "An anonymous method does not contain jump statements like goto, break, or continue."
},
{
"code": null,
"e": 29438,
"s": 29389,
"text": "An anonymous method does not access unsafe code."
},
{
"code": null,
"e": 29521,
"s": 29438,
"text": "An anonymous method does not access in, ref, and out parameter of the outer scope."
},
{
"code": null,
"e": 29594,
"s": 29521,
"text": "You can not use an anonymous method to the left side of the is operator."
},
{
"code": null,
"e": 29866,
"s": 29594,
"text": "You can also use an anonymous method as an event handler.Example:// C# program to illustrate how an // anonymous method use as a // event handlerMyButton.Click += delegate(Object obj, EventArgs ev){ System.Windows.Forms.MessageBox.Show(\"Complete without error...!!\");}"
},
{
"code": null,
"e": 29875,
"s": 29866,
"text": "Example:"
},
{
"code": "// C# program to illustrate how an // anonymous method use as a // event handlerMyButton.Click += delegate(Object obj, EventArgs ev){ System.Windows.Forms.MessageBox.Show(\"Complete without error...!!\");}",
"e": 30082,
"s": 29875,
"text": null
},
{
"code": null,
"e": 30093,
"s": 30082,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 30096,
"s": 30093,
"text": "C#"
},
{
"code": null,
"e": 30194,
"s": 30096,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30203,
"s": 30194,
"text": "Comments"
},
{
"code": null,
"e": 30216,
"s": 30203,
"text": "Old Comments"
},
{
"code": null,
"e": 30244,
"s": 30216,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 30262,
"s": 30244,
"text": "Main Method in C#"
},
{
"code": null,
"e": 30291,
"s": 30262,
"text": "C# | Dictionary.Add() Method"
},
{
"code": null,
"e": 30316,
"s": 30291,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 30374,
"s": 30316,
"text": "Different ways to sort an array in descending order in C#"
},
{
"code": null,
"e": 30397,
"s": 30374,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 30441,
"s": 30397,
"text": "C# | How to use strings in switch statement"
},
{
"code": null,
"e": 30457,
"s": 30441,
"text": "C# | List Class"
},
{
"code": null,
"e": 30519,
"s": 30457,
"text": "C# | How to check whether a List contains a specified element"
}
] |
Calendar Functions in Java
|
The java.util.calendar class provides the calendar functions in Java. Is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
Following are the calendar functions in Java β
Let us now see an example of the equals() method.
The java.util.Calendar.equals() method compares this Calendar to the specified Object β
import java.util.*;
public class Demo {
public static void main(String[] args) {
// create two calendars
Calendar cal = Calendar.getInstance();
// specify a date for one of them
Calendar cal2 = new GregorianCalendar(2011, 04, 29);
// compare the two calendars.
boolean b = cal.equals(cal2);
// print result
System.out.println("Calendars are equal :" + b);
}
}
Calendars are equal :false
Let us see another example wherein we are getting the first day of week. The java.util.Calendar.getFirstDayOfWeek() method returns the first day of the week.
import java.util.*;
public class Demo {
public static void main(String[] args) {
// create a new calendar
Calendar cal = Calendar.getInstance();
// print the first day of the week
System.out.println("First day is :" + cal.getFirstDayOfWeek());
int day = cal.getFirstDayOfWeek();
switch (day) {
case (1):
System.out.println("Sunday");
break;
case (2):
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thrusday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
}
}
}
First day is :1
Sunday
|
[
{
"code": null,
"e": 1391,
"s": 1062,
"text": "The java.util.calendar class provides the calendar functions in Java. Is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week."
},
{
"code": null,
"e": 1438,
"s": 1391,
"text": "Following are the calendar functions in Java β"
},
{
"code": null,
"e": 1488,
"s": 1438,
"text": "Let us now see an example of the equals() method."
},
{
"code": null,
"e": 1576,
"s": 1488,
"text": "The java.util.Calendar.equals() method compares this Calendar to the specified Object β"
},
{
"code": null,
"e": 1990,
"s": 1576,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n // create two calendars\n Calendar cal = Calendar.getInstance();\n // specify a date for one of them\n Calendar cal2 = new GregorianCalendar(2011, 04, 29);\n // compare the two calendars.\n boolean b = cal.equals(cal2);\n // print result\n System.out.println(\"Calendars are equal :\" + b);\n }\n}"
},
{
"code": null,
"e": 2017,
"s": 1990,
"text": "Calendars are equal :false"
},
{
"code": null,
"e": 2175,
"s": 2017,
"text": "Let us see another example wherein we are getting the first day of week. The java.util.Calendar.getFirstDayOfWeek() method returns the first day of the week."
},
{
"code": null,
"e": 3081,
"s": 2175,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String[] args) {\n // create a new calendar\n Calendar cal = Calendar.getInstance();\n // print the first day of the week\n System.out.println(\"First day is :\" + cal.getFirstDayOfWeek());\n int day = cal.getFirstDayOfWeek();\n switch (day) {\n case (1):\n System.out.println(\"Sunday\");\n break;\n case (2):\n System.out.println(\"Monday\");\n break;\n case 3:\n System.out.println(\"Tuesday\");\n break;\n case 4:\n System.out.println(\"Wednesday\");\n break;\n case 5:\n System.out.println(\"Thrusday\");\n break;\n case 6:\n System.out.println(\"Friday\");\n break;\n case 7:\n System.out.println(\"Saturday\");\n break;\n }\n }\n}"
},
{
"code": null,
"e": 3104,
"s": 3081,
"text": "First day is :1\nSunday"
}
] |
Running Deep Learning Algorithms as a Service | by Nir Orman | Towards Data Science
|
So, You want to serve Deep Learning Algorithms as a service.
You have a really cool algorithmic library written in Python and TensorFlow/Keras/Some other platform that requires running workloads on a GPU and you want to be able to serve it at scale and have it up and running fast.
Celery is an open-source asynchronous task queue which is based on distributed message passing. After reading all possible blog posts and seeing all the Youtube videos about Celery, I decided itβs the right solution for the task at hand.
Please welcome our main characters of the plot:
The API: Gets a request, creates a Celery async task, and puts it in a queue. (I recommend flask for this task, itβs light but extendable)The message queue: AKA Celeryβs Broker. Stores the tasks created by the API in queues. The best practice is to choose RabbitMQ.Workers: a python/celery process which we will run on a GPU and will take tasks from the queues. This is where all the heavy lifting gets done.The resultβs backend: Will store the tasks return values. The best practice is to use redis which enables complicated workflows (one task that is dependant on another) without polling.
The API: Gets a request, creates a Celery async task, and puts it in a queue. (I recommend flask for this task, itβs light but extendable)
The message queue: AKA Celeryβs Broker. Stores the tasks created by the API in queues. The best practice is to choose RabbitMQ.
Workers: a python/celery process which we will run on a GPU and will take tasks from the queues. This is where all the heavy lifting gets done.
The resultβs backend: Will store the tasks return values. The best practice is to use redis which enables complicated workflows (one task that is dependant on another) without polling.
The best practice is to use Celery with RabbitMQ as the broker of the messages and with redis as the resultβs backend, in order to use all the unique features that Celery can provide. We know software requirements often change faster than we expect, this should provide us with maximum flexibility so we can use even the most complicated features of Celery. When choosing RabbitMQ and redis, each new task is transformed into a message which Celery then posts to a queue in RabbitMQ, and each return value of a task performed by a worker will automatically be written back to redis (you can easily host RabbitMQ on GCP using βclick to deployβ, and redis using AWS Elastic Cache).
Once the message representing the task is in the queue, we need a GPU worker to compute it. The GPU worker will read a message from the queue and perform the task. For example, if itβs a computer vision algorithm, a worker will download the original image from AWS S3, manipulate it, and upload the new image back to S3. The URL of the image will be passed as part of the task.
But wait, thereβs a catch.
GPUs, are very expensive machines. One instance of P2.Xlarge in AWS costs over 2,000$ a month (3.06$ an hour while writing these lines) or ~600$ if itβs a spot instance. This obviously means we do NOT want them to be constantly up if thereβs no need. They have to be turned on, on-demand, and then turned off. The thing is, Elastic Beanstalk has no feature of auto-scaling according to RabbitMQ queue metrics.
We have to write our own custom Auto Scaler. Itβs a big name for a small Python script that runs and polls RabbitMQ for the number of tasks in the queue every 30 seconds. If thereβre messages in the queue, it calls the AWS API and makes it start GPU workers accordingly.
Each worker is booted with the docker container of the algorithmic repository (stored in ECR, Elastic Container Registry). Once the container is up and running, it connects to RabbitMQ and redis. It then takes a task from the queue and calculates it. The output is written by the worker to S3. If the task was completed successfully then the return value of the Celery task, is a json containing a URL to the output saved to S3 and its metadata. That return value is automatically saved to redis by Celery and also saved to Postgres DB. If the task failed to finish, an exception is saved to redis.
Check out the diagram below to understand the architecture explained above:
Sounds breezy so far? One of the main challenges using Celery is to configure it the right way.
Hereβs a good configuration thatβll save you time and tears when you try to perform Deep Learning tasks at scale. Check it out below and then weβll dive into every detail of it:
from celery import Celeryfrom api.celery_jobs_app.celery_config import BROKER_URI, BACKEND_URIAPP = Celery( 'celery_app', broker=BROKER_URI, backend=BACKEND_URI, include=['api.celery_jobs_app.tasks'])APP.conf.update({ 'imports': ( 'api.celery_jobs_app.tasks.tasks' ), 'task_routes': { 'calculate-image-task': {'queue': 'images-queue'} } }, 'task_serializer': 'json', 'result_serializer': 'json', 'accept_content': ['json'], 'worker_prefetch_multiplier': 1, 'task_acks_late': True, 'task_track_started': True, 'result_expires': 604800, # one week 'task_reject_on_worker_lost': True, 'task_queue_max_priority': 10})
Note: The configuration has been simplified in order to make it easier to understand.
Letβs break it down.
The first paragraph in the snippet is just some imports, trivial.
The second paragraph defines the celery app itself, which has a broker and backend (As stated before, the best practice is to use RabbitMQ and redis).
The third paragraph updates the configuration of Celery, This is the interesting part.
The βimportsβ section says in which of our python packages Celery should look for tasks.
The βtasks_routesβ part maps between the taskβs name and the queue in which it should be stored. In the code snippet above, all tasks that are of type βcalculate-image-taskβ will be pushed into a queue named βimages-queueβ. If you do not write which queue your task should be routed to, it will by default go to the default queue named βceleryβ. BTW, you can change the name of the default queue if you want by defining βtask_default_queueβ property.
FYI: The queue itself is automatically created on RabbitMQ once the first task is routed to it. Cool :)
βtask_serializerβ: This is how tasks will be serialized once they are put in the queue and deserialized once they reach the worker. In the image processing case, we do not want the image itself to be serialized and deserialized, The best practice is to store it and only pass its location or URL. Weβll use json as the serializer.
βresult_serializerβ: Keep in mind, if you declare the serialization type as json and return a result that is an object or an exception (which is the return type in case there was an exception which wasnβt caught) then your result serialization will throw an exception since any object thatβs not a json would throw an exception of failing to serialize. You can always read more about serializers here.
βaccept_contentβ: A white-list of content-types/serializers to allow.
Tip: Itβs not recommended to use βpickleβ serializer since it is known to have security issues. Since Celery version 4.0, json is actually the default option of serialization, but βExplicit is better than implicitβ (The Zen of Python).
βworker_prefetch_multiplierβ: The default of Celery is that each worker takes 4 tasks and computes all of them before it comes back for the next tasks. Their idea was to optimize network roundtrips. In our case, Deep Learning tasks tend to be long ones (way longer than the network time). This means we do not want a worker to take a bunch of tasks and perform them one after the other. We want each worker to take a single task at a time, and then come back to take the next task when itβs done with the previous one. That way, if one task requires a very long computation, other workers could work on the next tasks simultaneously, since as long as the first worker is not working on them, they are kept in the queue.
βtask_acks_lateβ: By default, when a worker takes a task, the task will be βackedβ just before its execution. In the case of Deep Learning tasks, which take a long time to compute, we would want them to be βackedβ only after they are computed. This is especially useful when we use spot instances, which lower our average task price but may also be lost if thereβs a shortage of GPU instances and our bidding price wasnβt competitive enough.
βtask_track_startedβ: Good for tracking that a task has started, cause when your task is long-running, you want to know itβs no longer in the queue (which would be marked as βpendingβ.) I recommend using Flower as the monitor solution for Celery, which allows you to see exactly whatβs the status of every task.
βresult_expiresβ: by default, Celery keeps your results on redis only for 1 day. If you want it to be kept longer, define`result_expires` differently in the configuration file. I would recommend keeping it for at most 1 week and writing the results to a more organized DB that has a schema, such as PostgreSQL.
βtask_reject_on_worker_lostβ: Weβll set this to True. When we use spot instances, thereβs a chance a worker will be lost when a spot instance is taken away from us. We want the task to be put back into the queue and be computed by another worker. Be careful, if a worker was lost due to hardware errors like βout of memoryβ etc., then the task will get partially calculated again and again in a loop since the worker will be lost every time it tries to compute it. If you see a task in an endless loop, this is the configuration you should be suspicious about.
βtask_queue_max_priorityβ: This is where you can make sure that important tasks get done first. You can set a priority for every Celery task (by assigning it with some int representing its priority). If you set this property, you must also set it to your RabbitMQ queue, it does not get set automatically. If a task with priority enters a queue that doesnβt have the priority property, an exception will be thrown and the task will not enter the queue. This property is useful if you have a premium customer whose tasks should be computed first.
If youβre thinking about using this property in order to prioritize fast running tasks over slow ones (such as long GPU computing tasks) then consider adding another group of workers, that are CPU workers and not expensive GPU workers. It would be cheaper and faster.
As you can see in the architecture diagram at the top, You can also have workers running on a totally different cloud.
For example, you could run your workers on Azure AKS which is the Kubernetes of Azure. But thatβs a totally different blog post.
Good luck serving your Deep Learning Algorithms with Celery, if you have any questions, feel free to contact me on LinkedIn.
|
[
{
"code": null,
"e": 233,
"s": 172,
"text": "So, You want to serve Deep Learning Algorithms as a service."
},
{
"code": null,
"e": 454,
"s": 233,
"text": "You have a really cool algorithmic library written in Python and TensorFlow/Keras/Some other platform that requires running workloads on a GPU and you want to be able to serve it at scale and have it up and running fast."
},
{
"code": null,
"e": 692,
"s": 454,
"text": "Celery is an open-source asynchronous task queue which is based on distributed message passing. After reading all possible blog posts and seeing all the Youtube videos about Celery, I decided itβs the right solution for the task at hand."
},
{
"code": null,
"e": 740,
"s": 692,
"text": "Please welcome our main characters of the plot:"
},
{
"code": null,
"e": 1333,
"s": 740,
"text": "The API: Gets a request, creates a Celery async task, and puts it in a queue. (I recommend flask for this task, itβs light but extendable)The message queue: AKA Celeryβs Broker. Stores the tasks created by the API in queues. The best practice is to choose RabbitMQ.Workers: a python/celery process which we will run on a GPU and will take tasks from the queues. This is where all the heavy lifting gets done.The resultβs backend: Will store the tasks return values. The best practice is to use redis which enables complicated workflows (one task that is dependant on another) without polling."
},
{
"code": null,
"e": 1472,
"s": 1333,
"text": "The API: Gets a request, creates a Celery async task, and puts it in a queue. (I recommend flask for this task, itβs light but extendable)"
},
{
"code": null,
"e": 1600,
"s": 1472,
"text": "The message queue: AKA Celeryβs Broker. Stores the tasks created by the API in queues. The best practice is to choose RabbitMQ."
},
{
"code": null,
"e": 1744,
"s": 1600,
"text": "Workers: a python/celery process which we will run on a GPU and will take tasks from the queues. This is where all the heavy lifting gets done."
},
{
"code": null,
"e": 1929,
"s": 1744,
"text": "The resultβs backend: Will store the tasks return values. The best practice is to use redis which enables complicated workflows (one task that is dependant on another) without polling."
},
{
"code": null,
"e": 2609,
"s": 1929,
"text": "The best practice is to use Celery with RabbitMQ as the broker of the messages and with redis as the resultβs backend, in order to use all the unique features that Celery can provide. We know software requirements often change faster than we expect, this should provide us with maximum flexibility so we can use even the most complicated features of Celery. When choosing RabbitMQ and redis, each new task is transformed into a message which Celery then posts to a queue in RabbitMQ, and each return value of a task performed by a worker will automatically be written back to redis (you can easily host RabbitMQ on GCP using βclick to deployβ, and redis using AWS Elastic Cache)."
},
{
"code": null,
"e": 2987,
"s": 2609,
"text": "Once the message representing the task is in the queue, we need a GPU worker to compute it. The GPU worker will read a message from the queue and perform the task. For example, if itβs a computer vision algorithm, a worker will download the original image from AWS S3, manipulate it, and upload the new image back to S3. The URL of the image will be passed as part of the task."
},
{
"code": null,
"e": 3014,
"s": 2987,
"text": "But wait, thereβs a catch."
},
{
"code": null,
"e": 3424,
"s": 3014,
"text": "GPUs, are very expensive machines. One instance of P2.Xlarge in AWS costs over 2,000$ a month (3.06$ an hour while writing these lines) or ~600$ if itβs a spot instance. This obviously means we do NOT want them to be constantly up if thereβs no need. They have to be turned on, on-demand, and then turned off. The thing is, Elastic Beanstalk has no feature of auto-scaling according to RabbitMQ queue metrics."
},
{
"code": null,
"e": 3695,
"s": 3424,
"text": "We have to write our own custom Auto Scaler. Itβs a big name for a small Python script that runs and polls RabbitMQ for the number of tasks in the queue every 30 seconds. If thereβre messages in the queue, it calls the AWS API and makes it start GPU workers accordingly."
},
{
"code": null,
"e": 4294,
"s": 3695,
"text": "Each worker is booted with the docker container of the algorithmic repository (stored in ECR, Elastic Container Registry). Once the container is up and running, it connects to RabbitMQ and redis. It then takes a task from the queue and calculates it. The output is written by the worker to S3. If the task was completed successfully then the return value of the Celery task, is a json containing a URL to the output saved to S3 and its metadata. That return value is automatically saved to redis by Celery and also saved to Postgres DB. If the task failed to finish, an exception is saved to redis."
},
{
"code": null,
"e": 4370,
"s": 4294,
"text": "Check out the diagram below to understand the architecture explained above:"
},
{
"code": null,
"e": 4466,
"s": 4370,
"text": "Sounds breezy so far? One of the main challenges using Celery is to configure it the right way."
},
{
"code": null,
"e": 4644,
"s": 4466,
"text": "Hereβs a good configuration thatβll save you time and tears when you try to perform Deep Learning tasks at scale. Check it out below and then weβll dive into every detail of it:"
},
{
"code": null,
"e": 5331,
"s": 4644,
"text": "from celery import Celeryfrom api.celery_jobs_app.celery_config import BROKER_URI, BACKEND_URIAPP = Celery( 'celery_app', broker=BROKER_URI, backend=BACKEND_URI, include=['api.celery_jobs_app.tasks'])APP.conf.update({ 'imports': ( 'api.celery_jobs_app.tasks.tasks' ), 'task_routes': { 'calculate-image-task': {'queue': 'images-queue'} } }, 'task_serializer': 'json', 'result_serializer': 'json', 'accept_content': ['json'], 'worker_prefetch_multiplier': 1, 'task_acks_late': True, 'task_track_started': True, 'result_expires': 604800, # one week 'task_reject_on_worker_lost': True, 'task_queue_max_priority': 10})"
},
{
"code": null,
"e": 5417,
"s": 5331,
"text": "Note: The configuration has been simplified in order to make it easier to understand."
},
{
"code": null,
"e": 5438,
"s": 5417,
"text": "Letβs break it down."
},
{
"code": null,
"e": 5504,
"s": 5438,
"text": "The first paragraph in the snippet is just some imports, trivial."
},
{
"code": null,
"e": 5655,
"s": 5504,
"text": "The second paragraph defines the celery app itself, which has a broker and backend (As stated before, the best practice is to use RabbitMQ and redis)."
},
{
"code": null,
"e": 5742,
"s": 5655,
"text": "The third paragraph updates the configuration of Celery, This is the interesting part."
},
{
"code": null,
"e": 5831,
"s": 5742,
"text": "The βimportsβ section says in which of our python packages Celery should look for tasks."
},
{
"code": null,
"e": 6282,
"s": 5831,
"text": "The βtasks_routesβ part maps between the taskβs name and the queue in which it should be stored. In the code snippet above, all tasks that are of type βcalculate-image-taskβ will be pushed into a queue named βimages-queueβ. If you do not write which queue your task should be routed to, it will by default go to the default queue named βceleryβ. BTW, you can change the name of the default queue if you want by defining βtask_default_queueβ property."
},
{
"code": null,
"e": 6386,
"s": 6282,
"text": "FYI: The queue itself is automatically created on RabbitMQ once the first task is routed to it. Cool :)"
},
{
"code": null,
"e": 6717,
"s": 6386,
"text": "βtask_serializerβ: This is how tasks will be serialized once they are put in the queue and deserialized once they reach the worker. In the image processing case, we do not want the image itself to be serialized and deserialized, The best practice is to store it and only pass its location or URL. Weβll use json as the serializer."
},
{
"code": null,
"e": 7119,
"s": 6717,
"text": "βresult_serializerβ: Keep in mind, if you declare the serialization type as json and return a result that is an object or an exception (which is the return type in case there was an exception which wasnβt caught) then your result serialization will throw an exception since any object thatβs not a json would throw an exception of failing to serialize. You can always read more about serializers here."
},
{
"code": null,
"e": 7189,
"s": 7119,
"text": "βaccept_contentβ: A white-list of content-types/serializers to allow."
},
{
"code": null,
"e": 7425,
"s": 7189,
"text": "Tip: Itβs not recommended to use βpickleβ serializer since it is known to have security issues. Since Celery version 4.0, json is actually the default option of serialization, but βExplicit is better than implicitβ (The Zen of Python)."
},
{
"code": null,
"e": 8145,
"s": 7425,
"text": "βworker_prefetch_multiplierβ: The default of Celery is that each worker takes 4 tasks and computes all of them before it comes back for the next tasks. Their idea was to optimize network roundtrips. In our case, Deep Learning tasks tend to be long ones (way longer than the network time). This means we do not want a worker to take a bunch of tasks and perform them one after the other. We want each worker to take a single task at a time, and then come back to take the next task when itβs done with the previous one. That way, if one task requires a very long computation, other workers could work on the next tasks simultaneously, since as long as the first worker is not working on them, they are kept in the queue."
},
{
"code": null,
"e": 8587,
"s": 8145,
"text": "βtask_acks_lateβ: By default, when a worker takes a task, the task will be βackedβ just before its execution. In the case of Deep Learning tasks, which take a long time to compute, we would want them to be βackedβ only after they are computed. This is especially useful when we use spot instances, which lower our average task price but may also be lost if thereβs a shortage of GPU instances and our bidding price wasnβt competitive enough."
},
{
"code": null,
"e": 8899,
"s": 8587,
"text": "βtask_track_startedβ: Good for tracking that a task has started, cause when your task is long-running, you want to know itβs no longer in the queue (which would be marked as βpendingβ.) I recommend using Flower as the monitor solution for Celery, which allows you to see exactly whatβs the status of every task."
},
{
"code": null,
"e": 9210,
"s": 8899,
"text": "βresult_expiresβ: by default, Celery keeps your results on redis only for 1 day. If you want it to be kept longer, define`result_expires` differently in the configuration file. I would recommend keeping it for at most 1 week and writing the results to a more organized DB that has a schema, such as PostgreSQL."
},
{
"code": null,
"e": 9771,
"s": 9210,
"text": "βtask_reject_on_worker_lostβ: Weβll set this to True. When we use spot instances, thereβs a chance a worker will be lost when a spot instance is taken away from us. We want the task to be put back into the queue and be computed by another worker. Be careful, if a worker was lost due to hardware errors like βout of memoryβ etc., then the task will get partially calculated again and again in a loop since the worker will be lost every time it tries to compute it. If you see a task in an endless loop, this is the configuration you should be suspicious about."
},
{
"code": null,
"e": 10317,
"s": 9771,
"text": "βtask_queue_max_priorityβ: This is where you can make sure that important tasks get done first. You can set a priority for every Celery task (by assigning it with some int representing its priority). If you set this property, you must also set it to your RabbitMQ queue, it does not get set automatically. If a task with priority enters a queue that doesnβt have the priority property, an exception will be thrown and the task will not enter the queue. This property is useful if you have a premium customer whose tasks should be computed first."
},
{
"code": null,
"e": 10585,
"s": 10317,
"text": "If youβre thinking about using this property in order to prioritize fast running tasks over slow ones (such as long GPU computing tasks) then consider adding another group of workers, that are CPU workers and not expensive GPU workers. It would be cheaper and faster."
},
{
"code": null,
"e": 10704,
"s": 10585,
"text": "As you can see in the architecture diagram at the top, You can also have workers running on a totally different cloud."
},
{
"code": null,
"e": 10833,
"s": 10704,
"text": "For example, you could run your workers on Azure AKS which is the Kubernetes of Azure. But thatβs a totally different blog post."
}
] |
BabylonJS - Video Texture
|
To display video in the scene, babylonjs has the video texture feature. videotexture takes an array of videos as input.
For video texture, we are going to use mp4 file. Please download an mp4 of your choice and use it in the demo below.
video.material.diffuseTexture = new BABYLON.VideoTexture("video",
["mp4 file", "webm file"], scene, true);
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>BabylonJs - Basic Element-Creating Scene</title>
<script src = "babylon.js"></script>
<style>
canvas {width: 100%; height: 100%;}
</style>
</head>
<body>
<canvas id = "renderCanvas"></canvas>
<script type = "text/javascript">
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var createScene = function() {
var scene = new BABYLON.Scene(engine);
//Adding an Arc Rotate Camera
var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas, false);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
var light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 1, 0), scene);
// Default intensity is 1. Let's dim the light a small amount
light.intensity = 0.7;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
var ground = BABYLON.Mesh.CreateGround("ground1", 100, 50, 2, scene);
// Move the sphere upward 1/2 its height
ground.position.y = 1;
var mat = new BABYLON.StandardMaterial("mat", scene);
var videoTexture = new BABYLON.VideoTexture("video", ["sounds/video.mp4"], scene, true, true);
mat.diffuseTexture = videoTexture;
ground.material = mat;
scene.onPointerUp = function () {
videoTexture.video.play();
}
return scene;
};
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
</script>
</body>
</html>
The above line of code will generate the following output β
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2303,
"s": 2183,
"text": "To display video in the scene, babylonjs has the video texture feature. videotexture takes an array of videos as input."
},
{
"code": null,
"e": 2420,
"s": 2303,
"text": "For video texture, we are going to use mp4 file. Please download an mp4 of your choice and use it in the demo below."
},
{
"code": null,
"e": 2528,
"s": 2420,
"text": "video.material.diffuseTexture = new BABYLON.VideoTexture(\"video\",\n[\"mp4 file\", \"webm file\"], scene, true);\n"
},
{
"code": null,
"e": 4392,
"s": 2528,
"text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Basic Element-Creating Scene</title>\n <script src = \"babylon.js\"></script>\n <style>\n canvas {width: 100%; height: 100%;}\n </style>\n </head>\n \n <body>\n <canvas id = \"renderCanvas\"></canvas>\n <script type = \"text/javascript\">\n var canvas = document.getElementById(\"renderCanvas\");\n var engine = new BABYLON.Engine(canvas, true);\n \n var createScene = function() {\n var scene = new BABYLON.Scene(engine);\n\n //Adding an Arc Rotate Camera\n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene);\n camera.attachControl(canvas, false);\n\n // This creates a light, aiming 0,1,0 - to the sky (non-mesh)\n var light = new BABYLON.HemisphericLight(\"light1\", new BABYLON.Vector3(0, 1, 0), scene);\n\n // Default intensity is 1. Let's dim the light a small amount\n light.intensity = 0.7;\n\n // Our built-in 'sphere' shape. Params: name, subdivs, size, scene\n var ground = BABYLON.Mesh.CreateGround(\"ground1\", 100, 50, 2, scene);\n\n // Move the sphere upward 1/2 its height\n ground.position.y = 1;\n\n var mat = new BABYLON.StandardMaterial(\"mat\", scene);\n\n var videoTexture = new BABYLON.VideoTexture(\"video\", [\"sounds/video.mp4\"], scene, true, true);\n\n mat.diffuseTexture = videoTexture;\n ground.material = mat;\n\n scene.onPointerUp = function () {\n videoTexture.video.play();\n }\n return scene;\n };\n var scene = createScene();\n engine.runRenderLoop(function() {\n scene.render();\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 4452,
"s": 4392,
"text": "The above line of code will generate the following output β"
},
{
"code": null,
"e": 4459,
"s": 4452,
"text": " Print"
},
{
"code": null,
"e": 4470,
"s": 4459,
"text": " Add Notes"
}
] |
How do I hide an element when printing a web page?
|
To hide the element, add βdisplay:noneβ to the element with CSS.
<style>
@media print {
.noprint {
visibility: hidden;
}
}
</style>
In addition, add the element, which you want to hide inside the <div>β
<div id="noprint">
Add here the element, which you want to hide.
</div>
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "To hide the element, add βdisplay:noneβ to the element with CSS."
},
{
"code": null,
"e": 1206,
"s": 1127,
"text": "<style>\n@media print {\n .noprint {\n visibility: hidden;\n }\n}\n</style>"
},
{
"code": null,
"e": 1277,
"s": 1206,
"text": "In addition, add the element, which you want to hide inside the <div>β"
},
{
"code": null,
"e": 1352,
"s": 1277,
"text": "<div id=\"noprint\">\n Add here the element, which you want to hide.\n</div>"
}
] |
When should I use a semicolon after curly braces in JavaScript?
|
In JavaScript, Semicolons are optional. Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements is placed on a separate line. It is a good programming practice to use semicolons.
In JavaScript, use a semi-colon after a statement. Letβs see an example of a variable assignment:
var s = function() {
alert("Hello World!");
};
However, semicolons arenβt necessary for the following function declarations:
function() {
alert("Hello World!");
};
|
[
{
"code": null,
"e": 1386,
"s": 1062,
"text": "In JavaScript, Semicolons are optional. Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements is placed on a separate line. It is a good programming practice to use semicolons."
},
{
"code": null,
"e": 1484,
"s": 1386,
"text": "In JavaScript, use a semi-colon after a statement. Letβs see an example of a variable assignment:"
},
{
"code": null,
"e": 1534,
"s": 1484,
"text": "var s = function() {\n alert(\"Hello World!\");\n};"
},
{
"code": null,
"e": 1612,
"s": 1534,
"text": "However, semicolons arenβt necessary for the following function declarations:"
},
{
"code": null,
"e": 1654,
"s": 1612,
"text": "function() {\n alert(\"Hello World!\");\n};"
}
] |
Slice Composite Literal in Go - GeeksforGeeks
|
22 Jul, 2019
There are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array.Composite literals are used to construct the values for arrays, structs, slices, and maps. Each time they are evaluated, it will create new value. They consist of the type of the literal followed by a brace-bound list of elements. (Did you get this point!) Well, after this read you will get to know what is a composite literal and you will be shocked that you know it already !!!!
Letβs see how to create a slice and make the use of composite literal:
// Go program to show the slice // - composite literalpackage main import "fmt" func main() { // Slice with composite literal // Slice allows you to group together // the values of the same type // here type of values is int s1 := []int{23, 56, 89, 34} // displaying the values fmt.Println(s1)}
Output:
[23 56 89 34]
Hope you understand the term what exactly a composite literal. So basically assigning the values or initialization of arrays, slice, etc. are done using composite literals. These are generally used to compose a bunch of values of similar types.
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
Time Formatting in Golang
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
How to convert a string in lower case in Golang?
How to compare times in Golang?
Different Ways to Find the Type of Variable in Golang
|
[
{
"code": null,
"e": 24826,
"s": 24798,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 25475,
"s": 24826,
"text": "There are two terms i.e. Slice and Composite Literal. Slice is a composite data type similar to an array which is used to hold the elements of the same data type. The main difference between array and slice is that slice can vary in size dynamically but not an array.Composite literals are used to construct the values for arrays, structs, slices, and maps. Each time they are evaluated, it will create new value. They consist of the type of the literal followed by a brace-bound list of elements. (Did you get this point!) Well, after this read you will get to know what is a composite literal and you will be shocked that you know it already !!!!"
},
{
"code": null,
"e": 25546,
"s": 25475,
"text": "Letβs see how to create a slice and make the use of composite literal:"
},
{
"code": "// Go program to show the slice // - composite literalpackage main import \"fmt\" func main() { // Slice with composite literal // Slice allows you to group together // the values of the same type // here type of values is int s1 := []int{23, 56, 89, 34} // displaying the values fmt.Println(s1)}",
"e": 25873,
"s": 25546,
"text": null
},
{
"code": null,
"e": 25881,
"s": 25873,
"text": "Output:"
},
{
"code": null,
"e": 25896,
"s": 25881,
"text": "[23 56 89 34]\n"
},
{
"code": null,
"e": 26141,
"s": 25896,
"text": "Hope you understand the term what exactly a composite literal. So basically assigning the values or initialization of arrays, slice, etc. are done using composite literals. These are generally used to compose a bunch of values of similar types."
},
{
"code": null,
"e": 26148,
"s": 26141,
"text": "Golang"
},
{
"code": null,
"e": 26162,
"s": 26148,
"text": "Golang-Slices"
},
{
"code": null,
"e": 26174,
"s": 26162,
"text": "Go Language"
},
{
"code": null,
"e": 26272,
"s": 26174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26281,
"s": 26272,
"text": "Comments"
},
{
"code": null,
"e": 26294,
"s": 26281,
"text": "Old Comments"
},
{
"code": null,
"e": 26346,
"s": 26294,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 26392,
"s": 26346,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 26418,
"s": 26392,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 26468,
"s": 26418,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 26519,
"s": 26468,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 26566,
"s": 26519,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 26578,
"s": 26566,
"text": "Golang Maps"
},
{
"code": null,
"e": 26627,
"s": 26578,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 26659,
"s": 26627,
"text": "How to compare times in Golang?"
}
] |
Calculate time of operation in Arduino
|
Often, you need to measure the time your microcontroller takes to perform a particular task. You can use the millis() function of Arduino to measure the time. This function returns the number of milliseconds passed since your board started running the current program. Therefore, to calculate the time taken by an operation, you can call millis() before and after your operation, and take the difference of the two values.
An example implementation is given below β
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
long int t1 = millis();
task_whose_time_is_to_be_measured();
long int t2 = millis();
Serial.print("Time taken by the task: "); Serial.print(t2-t1); Serial.println(" milliseconds");
}
void loop() {
// put your main code here, to run repeatedly:
}
As you can see, this will give the execution time of the task in milliseconds. But what if you want the execution time to be in microseconds? You guessed it! You can use micros() instead of millis().
|
[
{
"code": null,
"e": 1485,
"s": 1062,
"text": "Often, you need to measure the time your microcontroller takes to perform a particular task. You can use the millis() function of Arduino to measure the time. This function returns the number of milliseconds passed since your board started running the current program. Therefore, to calculate the time taken by an operation, you can call millis() before and after your operation, and take the difference of the two values."
},
{
"code": null,
"e": 1528,
"s": 1485,
"text": "An example implementation is given below β"
},
{
"code": null,
"e": 1872,
"s": 1528,
"text": "void setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n long int t1 = millis();\n task_whose_time_is_to_be_measured();\n long int t2 = millis();\n Serial.print(\"Time taken by the task: \"); Serial.print(t2-t1); Serial.println(\" milliseconds\");\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}"
},
{
"code": null,
"e": 2072,
"s": 1872,
"text": "As you can see, this will give the execution time of the task in milliseconds. But what if you want the execution time to be in microseconds? You guessed it! You can use micros() instead of millis()."
}
] |
C# Program to check if a number is prime or not
|
To calculate whether a number is prime or not, we have used a for a loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0, between the number itself.
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
a++;
}
}
A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime.
Let us see the complete example to check if a number is prime or not
Live Demo
using System;
namespace Demo {
class MyApplication {
public static void Main() {
int n = 5, a = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
a++;
}
}
if (a == 2) {
Console.WriteLine("{0} is a Prime Number", n);
} else {
Console.WriteLine("Not a Prime Number");
}
Console.ReadLine();
}
}
}
5 is a Prime Number
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "To calculate whether a number is prime or not, we have used a for a loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0, between the number itself."
},
{
"code": null,
"e": 1330,
"s": 1260,
"text": "for (int i = 1; i <= n; i++) {\n if (n % i == 0) {\n a++;\n }\n}"
},
{
"code": null,
"e": 1516,
"s": 1330,
"text": "A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime. "
},
{
"code": null,
"e": 1585,
"s": 1516,
"text": "Let us see the complete example to check if a number is prime or not"
},
{
"code": null,
"e": 1595,
"s": 1585,
"text": "Live Demo"
},
{
"code": null,
"e": 2035,
"s": 1595,
"text": "using System;\nnamespace Demo {\n class MyApplication {\n public static void Main() {\n int n = 5, a = 0;\n for (int i = 1; i <= n; i++) {\n if (n % i == 0) {\n a++;\n }\n }\n if (a == 2) {\n Console.WriteLine(\"{0} is a Prime Number\", n);\n } else {\n Console.WriteLine(\"Not a Prime Number\");\n }\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2055,
"s": 2035,
"text": "5 is a Prime Number"
}
] |
TypeScript - Nested if statement
|
The else...if ladder is useful to test multiple conditions. Its syntax is given below β
if (boolean_expression1) {
//statements if the expression1 evaluates to true
} else if (boolean_expression2) {
//statements if the expression2 evaluates to true
} else {
//statements if both expression1 and expression2 result to false
}
When using if...else...if and else statements, there are a few points to keep in mind.
An if can have zero or one else's and it must come after any else..if's.
An if can have zero or one else's and it must come after any else..if's.
An if can have zero to many else..if's and they must come before the else.
An if can have zero to many else..if's and they must come before the else.
Once an else..if succeeds, none of the remaining else..if's or else's will be tested.
Once an else..if succeeds, none of the remaining else..if's or else's will be tested.
var num:number = 2
if(num > 0) {
console.log(num+" is positive")
} else if(num < 0) {
console.log(num+" is negative")
} else {
console.log(num+" is neither positive nor negative")
}
The snippet displays whether the value is positive, negative or zero.
On compiling, it will generate the following JavaScript code β
//Generated by typescript 1.8.10
var num = 2;
if (num > 0) {
console.log(num + " is positive");
} else if (num < 0) {
console.log(num + " is negative");
} else {
console.log(num + " is neither positive nor negative");
}
Here is the output of the above code β
2 is positive
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2136,
"s": 2048,
"text": "The else...if ladder is useful to test multiple conditions. Its syntax is given below β"
},
{
"code": null,
"e": 2389,
"s": 2136,
"text": "if (boolean_expression1) { \n //statements if the expression1 evaluates to true \n} else if (boolean_expression2) { \n //statements if the expression2 evaluates to true \n} else { \n //statements if both expression1 and expression2 result to false \n}\n"
},
{
"code": null,
"e": 2476,
"s": 2389,
"text": "When using if...else...if and else statements, there are a few points to keep in mind."
},
{
"code": null,
"e": 2549,
"s": 2476,
"text": "An if can have zero or one else's and it must come after any else..if's."
},
{
"code": null,
"e": 2622,
"s": 2549,
"text": "An if can have zero or one else's and it must come after any else..if's."
},
{
"code": null,
"e": 2697,
"s": 2622,
"text": "An if can have zero to many else..if's and they must come before the else."
},
{
"code": null,
"e": 2772,
"s": 2697,
"text": "An if can have zero to many else..if's and they must come before the else."
},
{
"code": null,
"e": 2858,
"s": 2772,
"text": "Once an else..if succeeds, none of the remaining else..if's or else's will be tested."
},
{
"code": null,
"e": 2944,
"s": 2858,
"text": "Once an else..if succeeds, none of the remaining else..if's or else's will be tested."
},
{
"code": null,
"e": 3143,
"s": 2944,
"text": "var num:number = 2 \nif(num > 0) { \n console.log(num+\" is positive\") \n} else if(num < 0) { \n console.log(num+\" is negative\") \n} else { \n console.log(num+\" is neither positive nor negative\") \n}\n"
},
{
"code": null,
"e": 3213,
"s": 3143,
"text": "The snippet displays whether the value is positive, negative or zero."
},
{
"code": null,
"e": 3276,
"s": 3213,
"text": "On compiling, it will generate the following JavaScript code β"
},
{
"code": null,
"e": 3506,
"s": 3276,
"text": "//Generated by typescript 1.8.10\nvar num = 2;\nif (num > 0) {\n console.log(num + \" is positive\");\n} else if (num < 0) {\n console.log(num + \" is negative\");\n} else {\n console.log(num + \" is neither positive nor negative\");\n}\n"
},
{
"code": null,
"e": 3545,
"s": 3506,
"text": "Here is the output of the above code β"
},
{
"code": null,
"e": 3560,
"s": 3545,
"text": "2 is positive\n"
},
{
"code": null,
"e": 3593,
"s": 3560,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3607,
"s": 3593,
"text": " Antonio Papa"
},
{
"code": null,
"e": 3640,
"s": 3607,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3654,
"s": 3640,
"text": " Haider Malik"
},
{
"code": null,
"e": 3689,
"s": 3654,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3709,
"s": 3689,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3742,
"s": 3709,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3756,
"s": 3742,
"text": " Sean Bradley"
},
{
"code": null,
"e": 3791,
"s": 3756,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3807,
"s": 3791,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3840,
"s": 3807,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3860,
"s": 3840,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 3867,
"s": 3860,
"text": " Print"
},
{
"code": null,
"e": 3878,
"s": 3867,
"text": " Add Notes"
}
] |
Modified version of summing an array with recursion in JavaScript
|
Letβs say, we are required to write a recursive function that sums all the elements of an array of
Numbers but with a twist and the twist is that the recursive function we write cannot initialize any
extra variable (memory).
Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all
has to be using what we already have.
Hereβs the solution β
We already have an array and can use its first element (i.e., the element at zeroth index to hold
the recursive sum).
The approach is that we repeatedly pop one element from the array and add it to the first
element of the array until we are left with only one element.
When we are left with only one element, it will be the cumulative sum of the array and we return
that. The code for this approach will be β
const recursiveSum = arr => {
if(arr.length > 1){
arr[0] += arr.pop();
return recursiveSum(arr);
};
return arr[0];
};
console.log(recursiveSum([1,2,3,4]));
console.log(recursiveSum([1,2,3,4,3,6,3,32,7,9,5]));
console.log(recursiveSum([]));
The output in the console will be β
10
75
undefined
|
[
{
"code": null,
"e": 1287,
"s": 1062,
"text": "Letβs say, we are required to write a recursive function that sums all the elements of an array of\nNumbers but with a twist and the twist is that the recursive function we write cannot initialize any\nextra variable (memory)."
},
{
"code": null,
"e": 1425,
"s": 1287,
"text": "Like we cannot use a variable to store the sum or to keep a count of the index of the array, it all\nhas to be using what we already have."
},
{
"code": null,
"e": 1447,
"s": 1425,
"text": "Hereβs the solution β"
},
{
"code": null,
"e": 1565,
"s": 1447,
"text": "We already have an array and can use its first element (i.e., the element at zeroth index to hold\nthe recursive sum)."
},
{
"code": null,
"e": 1717,
"s": 1565,
"text": "The approach is that we repeatedly pop one element from the array and add it to the first\nelement of the array until we are left with only one element."
},
{
"code": null,
"e": 1857,
"s": 1717,
"text": "When we are left with only one element, it will be the cumulative sum of the array and we return\nthat. The code for this approach will be β"
},
{
"code": null,
"e": 2118,
"s": 1857,
"text": "const recursiveSum = arr => {\n if(arr.length > 1){\n arr[0] += arr.pop();\n return recursiveSum(arr);\n };\n return arr[0];\n};\nconsole.log(recursiveSum([1,2,3,4]));\nconsole.log(recursiveSum([1,2,3,4,3,6,3,32,7,9,5]));\nconsole.log(recursiveSum([]));"
},
{
"code": null,
"e": 2154,
"s": 2118,
"text": "The output in the console will be β"
},
{
"code": null,
"e": 2170,
"s": 2154,
"text": "10\n75\nundefined"
}
] |
How to wrap the text in text flow layout in JavaFX?
|
To create rich text contents in our applications JavaFX provides a special layout called text flow represented by the javafx.scene.layout.TextFlow class. Using this you can layout multiple text nodes in a single text flow.
Since they are separate nodes, you can set different fonts to them. If you try to add nodes other than text to this layout, they will be treated as embedded objects and are simply inserted between the text.
Unlike Label and the Text nodes, TextFLow doesnβt provide any method to wrap the text. But it does have a property named prefWidth specifying the desired width of the TextFlow layout. You can set values to this property using the setPrefWidth() method.
In short, you can wrap the text at a desired width or height using the setPrefWidth() or, setPrefHeight() methods.
import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
public class TextFlow_Wrap extends Application {
public void start(Stage stage) throws FileNotFoundException {
//Creating a text object
Text text1 = new Text("Welcome To Tutorialspoint");
Font font1 = Font.font("Brush Script MT", FontWeight.BOLD, 50);
text1.setFont(font1);
//Setting the color of the text
text1.setFill(Color.BLUEVIOLET);
text1.setStrokeWidth(1);
text1.setStroke(Color.CORAL);
Text text2 = new Text(" We provide free tutorials for readers in various technologies ");
text2.setFont(new Font("Algerian", 30));
text2.setFill(Color.ORANGERED);
Text text3 = new Text("We believe in easy learning");
//Setting font to the text
Font font2 = Font.font("Ink Free", FontWeight.BOLD, 35);
text3.setFont(font2);
text3.setFill(Color.DIMGRAY);
//Creating the text flow
TextFlow textFlow = new TextFlow();
//Wrapping the content of the text flow
textFlow.setPrefWidth(595);
textFlow.getChildren().addAll(text1, text2, text3);
//Setting padding to the text flow
textFlow.setPadding(new Insets(15, 15, 15, 15));
//Setting the stage
Group root = new Group(textFlow);
Scene scene = new Scene(root, 595, 250, Color.BEIGE);
stage.setTitle("Text Flow");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "To create rich text contents in our applications JavaFX provides a special layout called text flow represented by the javafx.scene.layout.TextFlow class. Using this you can layout multiple text nodes in a single text flow."
},
{
"code": null,
"e": 1492,
"s": 1285,
"text": "Since they are separate nodes, you can set different fonts to them. If you try to add nodes other than text to this layout, they will be treated as embedded objects and are simply inserted between the text."
},
{
"code": null,
"e": 1745,
"s": 1492,
"text": "Unlike Label and the Text nodes, TextFLow doesnβt provide any method to wrap the text. But it does have a property named prefWidth specifying the desired width of the TextFlow layout. You can set values to this property using the setPrefWidth() method."
},
{
"code": null,
"e": 1860,
"s": 1745,
"text": "In short, you can wrap the text at a desired width or height using the setPrefWidth() or, setPrefHeight() methods."
},
{
"code": null,
"e": 3654,
"s": 1860,
"text": "import java.io.FileNotFoundException;\nimport javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontWeight;\nimport javafx.scene.text.Text;\nimport javafx.scene.text.TextFlow;\npublic class TextFlow_Wrap extends Application {\n public void start(Stage stage) throws FileNotFoundException {\n //Creating a text object\n Text text1 = new Text(\"Welcome To Tutorialspoint\");\n Font font1 = Font.font(\"Brush Script MT\", FontWeight.BOLD, 50);\n text1.setFont(font1);\n //Setting the color of the text\n text1.setFill(Color.BLUEVIOLET);\n text1.setStrokeWidth(1);\n text1.setStroke(Color.CORAL);\n Text text2 = new Text(\" We provide free tutorials for readers in various technologies \");\n text2.setFont(new Font(\"Algerian\", 30));\n text2.setFill(Color.ORANGERED);\n Text text3 = new Text(\"We believe in easy learning\");\n //Setting font to the text\n Font font2 = Font.font(\"Ink Free\", FontWeight.BOLD, 35);\n text3.setFont(font2);\n text3.setFill(Color.DIMGRAY);\n //Creating the text flow\n TextFlow textFlow = new TextFlow();\n //Wrapping the content of the text flow\n textFlow.setPrefWidth(595);\n textFlow.getChildren().addAll(text1, text2, text3);\n //Setting padding to the text flow\n textFlow.setPadding(new Insets(15, 15, 15, 15));\n //Setting the stage\n Group root = new Group(textFlow);\n Scene scene = new Scene(root, 595, 250, Color.BEIGE);\n stage.setTitle(\"Text Flow\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
What is the difference between compile time polymorphism and runtime polymorphism in java?
|
If we perform (achieve) method overriding and method overloading using instance methods, it is run time (dynamic) polymorphism.
In dynamic polymorphism the binding between the method call an the method body happens at the time of execution and, this binding is known as dynamic binding or late binding.
Live Demo
class SuperClass{
public static void sample(){
System.out.println("Method of the super class");
}
}
public class RuntimePolymorphism extends SuperClass {
public static void sample(){
System.out.println("Method of the sub class");
}
public static void main(String args[]){
SuperClass obj1 = new RuntimePolymorphism();
RuntimePolymorphism obj2 = new RuntimePolymorphism();
obj1.sample();
obj2.sample();
}
}
Method of the super class
Method of the sub class
If we perform (achieve) method overriding and method overloading using static, private, final methods, it is compile time (static) polymorphism.
In static polymorphism the binding between the method call an the method body happens at the time of compilation and, this binding is known as static binding or early binding.
class SuperClass{
public static void sample(){
System.out.println("Method of the super class");
}
}
public class SubClass extends SuperClas {
public static void sample(){
System.out.println("Method of the sub class");
}
public static void main(String args[]){
SuperClass.sample();
SubClass.sample();
}
}
Method of the super class
Method of the sub class
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "If we perform (achieve) method overriding and method overloading using instance methods, it is run time (dynamic) polymorphism."
},
{
"code": null,
"e": 1365,
"s": 1190,
"text": "In dynamic polymorphism the binding between the method call an the method body happens at the time of execution and, this binding is known as dynamic binding or late binding."
},
{
"code": null,
"e": 1376,
"s": 1365,
"text": " Live Demo"
},
{
"code": null,
"e": 1835,
"s": 1376,
"text": "class SuperClass{\n public static void sample(){\n System.out.println(\"Method of the super class\");\n }\n}\npublic class RuntimePolymorphism extends SuperClass {\n public static void sample(){\n System.out.println(\"Method of the sub class\");\n }\n public static void main(String args[]){\n SuperClass obj1 = new RuntimePolymorphism();\n RuntimePolymorphism obj2 = new RuntimePolymorphism();\n obj1.sample();\n obj2.sample();\n }\n}"
},
{
"code": null,
"e": 1886,
"s": 1835,
"text": "Method of the super class\nMethod of the sub class\n"
},
{
"code": null,
"e": 2031,
"s": 1886,
"text": "If we perform (achieve) method overriding and method overloading using static, private, final methods, it is compile time (static) polymorphism."
},
{
"code": null,
"e": 2207,
"s": 2031,
"text": "In static polymorphism the binding between the method call an the method body happens at the time of compilation and, this binding is known as static binding or early binding."
},
{
"code": null,
"e": 2553,
"s": 2207,
"text": "class SuperClass{\n public static void sample(){\n System.out.println(\"Method of the super class\");\n }\n}\npublic class SubClass extends SuperClas {\n public static void sample(){\n System.out.println(\"Method of the sub class\");\n }\n public static void main(String args[]){\n SuperClass.sample();\n SubClass.sample();\n }\n}"
},
{
"code": null,
"e": 2604,
"s": 2553,
"text": "Method of the super class\nMethod of the sub class\n"
}
] |
Sorting in C++
|
In this section we will see how to perform sorting algorithm in C++. A sorted array is
an array in which each of the elements are sorted in some order such as numerical,
alphabetical etc. There are many algorithms to sort a numerical array such as bubble
sort, insertion sort, selection sort, merge sort, quick sort, heap sort etc. More details
about sorting the array using selection sort are given below.
The selection sort is a sorting method that yields a sorted array. It does so by
repeatedly finding the smallest element in the array and interchanging it with the
element at the starting of the unsorted part.
A program that implements a sorted array using selection sort is given as follows.
Live Demo
#include<iostream>
using namespace std;
void selectionSort(int a[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
int main() {
int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };
int n = sizeof(a)/ sizeof(a[0]);
int i;
cout<<"Given array is:"<<endl;
for (i = 0; i < n; i++)
cout<< a[i] <<" ";
cout<<endl;
selectionSort(a, n);
printf("\nSorted array is: \n");
for (i = 0; i < n; i++)
cout<< a[i] <<" ";
return 0;
}
Given array is:
22 91 35 78 10 8 75 99 1 67
Sorted array is:
1 8 10 22 35 67 75 78 91 99
In the above program, selectionSort() is a function that sorts the array a[] using
selection sort. There are two for loops in selectionSort(). In each iteration of the
outer for loop, the minimum element in the remaining array after i is found and then
interchanged with the element currently at i. This is repeated until the array is
sorted. This is shown below.
void selectionSort(int a[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
In the main() function, the array a[] is defined. Then the function selectionSort() is
called with the array a[] and its size n. Finally, the sorted array is displayed. This is
shown below.
int main() {
int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };
int n = sizeof(a)/ sizeof(a[0]);
int i;
cout<<"Given array is:"<<endl;
for (i = 0; i < n; i++)
cout<< a[i] <<" ";
cout<<endl;
selectionSort(a, n);
printf("\nSorted array is: \n");
for (i = 0; i < n; i++)
cout<< a[i] <<" ";
return 0;
}
|
[
{
"code": null,
"e": 1469,
"s": 1062,
"text": "In this section we will see how to perform sorting algorithm in C++. A sorted array is\nan array in which each of the elements are sorted in some order such as numerical,\nalphabetical etc. There are many algorithms to sort a numerical array such as bubble\nsort, insertion sort, selection sort, merge sort, quick sort, heap sort etc. More details\nabout sorting the array using selection sort are given below."
},
{
"code": null,
"e": 1679,
"s": 1469,
"text": "The selection sort is a sorting method that yields a sorted array. It does so by\nrepeatedly finding the smallest element in the array and interchanging it with the\nelement at the starting of the unsorted part."
},
{
"code": null,
"e": 1762,
"s": 1679,
"text": "A program that implements a sorted array using selection sort is given as follows."
},
{
"code": null,
"e": 1773,
"s": 1762,
"text": " Live Demo"
},
{
"code": null,
"e": 2451,
"s": 1773,
"text": "#include<iostream>\nusing namespace std;\nvoid selectionSort(int a[], int n) {\n int i, j, min, temp;\n for (i = 0; i < n - 1; i++) {\n min = i;\n for (j = i + 1; j < n; j++)\n if (a[j] < a[min])\n min = j;\n temp = a[i];\n a[i] = a[min];\n a[min] = temp;\n }\n}\nint main() {\n int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };\n int n = sizeof(a)/ sizeof(a[0]);\n int i;\n cout<<\"Given array is:\"<<endl;\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n cout<<endl;\n selectionSort(a, n);\n printf(\"\\nSorted array is: \\n\");\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n return 0;\n}"
},
{
"code": null,
"e": 2540,
"s": 2451,
"text": "Given array is:\n22 91 35 78 10 8 75 99 1 67\nSorted array is:\n1 8 10 22 35 67 75 78 91 99"
},
{
"code": null,
"e": 2904,
"s": 2540,
"text": "In the above program, selectionSort() is a function that sorts the array a[] using\nselection sort. There are two for loops in selectionSort(). In each iteration of the\nouter for loop, the minimum element in the remaining array after i is found and then\ninterchanged with the element currently at i. This is repeated until the array is\nsorted. This is shown below."
},
{
"code": null,
"e": 3182,
"s": 2904,
"text": "void selectionSort(int a[], int n) {\n int i, j, min, temp;\n for (i = 0; i < n - 1; i++) {\n min = i;\n for (j = i + 1; j < n; j++)\n if (a[j] < a[min])\n min = j;\n temp = a[i];\n a[i] = a[min];\n a[min] = temp;\n }\n}"
},
{
"code": null,
"e": 3372,
"s": 3182,
"text": "In the main() function, the array a[] is defined. Then the function selectionSort() is\ncalled with the array a[] and its size n. Finally, the sorted array is displayed. This is\nshown below."
},
{
"code": null,
"e": 3723,
"s": 3372,
"text": "int main() {\n int a[] = { 22, 91, 35, 78, 10, 8, 75, 99, 1, 67 };\n int n = sizeof(a)/ sizeof(a[0]);\n int i;\n cout<<\"Given array is:\"<<endl;\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n cout<<endl;\n selectionSort(a, n);\n printf(\"\\nSorted array is: \\n\");\n for (i = 0; i < n; i++)\n cout<< a[i] <<\" \";\n return 0;\n}"
}
] |
Append Operation on Vectors in R Programming - GeeksforGeeks
|
11 Jun, 2021
Vectors in R programming is a basic object consisting sequence of homogeneous elements. It can be integer, logical, double, character, complex or raw. In this article, let us discuss different methods to concatenate/append values to a vector in R programming. Values can be appended/concatenated in a vector using 2 methods:
c() function
append() function
c() function is a generic function that combines data into a vector or a list.
Syntax: c(...)Parameters: ...: represents objects to be concatenated
To know about more optional parameters, use below command in console:
help("c")
Example 1:
r
# Create a vectorx <- 1:5n <- 6:10 # Append using c() functiony <- c(x, n) # Print resultant vectorprint(y)
Output:
[1] 1 2 3 4 5 6 7 8 9 10
Example 2:
r
# Create vectorx <- 1:5n <- letters[1:5] # Appendy <- c(x, n) # Print resultant vectorprint(y) # Print type of resultant vectortypeof(y) # Print type of other vectorstypeof(x)typeof(n)
Output:
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
[1] "character"
[1] "integer"
[1] "character"
append() function in R is used for merging vectors or adding more elements to a vector.
Syntax: append(x, values)Parameters: x: represents a vector to which values has to be appended to values: represents the values which has to be appended in the vector
Example 1:
r
# Create a vectorx <- 1:5 # Append using append() functionx <- append(x, 6:10) # Print resultant vectorprint(x)
Output:
[1] 1 2 3 4 5 6 7 8 9 10
Example 2:
r
# Create a vectorx <- 1:5y <- letters[1:5] # Append using append() functionx <- append(x, values = y) # Print resultant vectorprint(x)
Output:
[1] "1" "2" "3" "4" "5" "a" "b" "c" "d" "e"
ruhelaa48
Picked
R-Vectors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
R - if statement
Replace Specific Characters in String in R
How to change the order of bars in bar chart in R ?
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 25569,
"s": 25242,
"text": "Vectors in R programming is a basic object consisting sequence of homogeneous elements. It can be integer, logical, double, character, complex or raw. In this article, let us discuss different methods to concatenate/append values to a vector in R programming. Values can be appended/concatenated in a vector using 2 methods: "
},
{
"code": null,
"e": 25582,
"s": 25569,
"text": "c() function"
},
{
"code": null,
"e": 25600,
"s": 25582,
"text": "append() function"
},
{
"code": null,
"e": 25682,
"s": 25602,
"text": "c() function is a generic function that combines data into a vector or a list. "
},
{
"code": null,
"e": 25753,
"s": 25682,
"text": "Syntax: c(...)Parameters: ...: represents objects to be concatenated "
},
{
"code": null,
"e": 25825,
"s": 25753,
"text": "To know about more optional parameters, use below command in console: "
},
{
"code": null,
"e": 25835,
"s": 25825,
"text": "help(\"c\")"
},
{
"code": null,
"e": 25848,
"s": 25835,
"text": "Example 1: "
},
{
"code": null,
"e": 25850,
"s": 25848,
"text": "r"
},
{
"code": "# Create a vectorx <- 1:5n <- 6:10 # Append using c() functiony <- c(x, n) # Print resultant vectorprint(y)",
"e": 25958,
"s": 25850,
"text": null
},
{
"code": null,
"e": 25968,
"s": 25958,
"text": "Output: "
},
{
"code": null,
"e": 26003,
"s": 25968,
"text": " [1] 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 26016,
"s": 26003,
"text": "Example 2: "
},
{
"code": null,
"e": 26018,
"s": 26016,
"text": "r"
},
{
"code": "# Create vectorx <- 1:5n <- letters[1:5] # Appendy <- c(x, n) # Print resultant vectorprint(y) # Print type of resultant vectortypeof(y) # Print type of other vectorstypeof(x)typeof(n)",
"e": 26203,
"s": 26018,
"text": null
},
{
"code": null,
"e": 26213,
"s": 26203,
"text": "Output: "
},
{
"code": null,
"e": 26303,
"s": 26213,
"text": "[1] \"1\" \"2\" \"3\" \"4\" \"5\" \"a\" \"b\" \"c\" \"d\" \"e\"\n[1] \"character\"\n[1] \"integer\"\n[1] \"character\""
},
{
"code": null,
"e": 26394,
"s": 26305,
"text": "append() function in R is used for merging vectors or adding more elements to a vector. "
},
{
"code": null,
"e": 26563,
"s": 26394,
"text": "Syntax: append(x, values)Parameters: x: represents a vector to which values has to be appended to values: represents the values which has to be appended in the vector "
},
{
"code": null,
"e": 26576,
"s": 26563,
"text": "Example 1: "
},
{
"code": null,
"e": 26578,
"s": 26576,
"text": "r"
},
{
"code": "# Create a vectorx <- 1:5 # Append using append() functionx <- append(x, 6:10) # Print resultant vectorprint(x)",
"e": 26690,
"s": 26578,
"text": null
},
{
"code": null,
"e": 26700,
"s": 26690,
"text": "Output: "
},
{
"code": null,
"e": 26734,
"s": 26700,
"text": "[1] 1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 26747,
"s": 26734,
"text": "Example 2: "
},
{
"code": null,
"e": 26749,
"s": 26747,
"text": "r"
},
{
"code": "# Create a vectorx <- 1:5y <- letters[1:5] # Append using append() functionx <- append(x, values = y) # Print resultant vectorprint(x)",
"e": 26884,
"s": 26749,
"text": null
},
{
"code": null,
"e": 26894,
"s": 26884,
"text": "Output: "
},
{
"code": null,
"e": 26938,
"s": 26894,
"text": "[1] \"1\" \"2\" \"3\" \"4\" \"5\" \"a\" \"b\" \"c\" \"d\" \"e\""
},
{
"code": null,
"e": 26950,
"s": 26940,
"text": "ruhelaa48"
},
{
"code": null,
"e": 26957,
"s": 26950,
"text": "Picked"
},
{
"code": null,
"e": 26967,
"s": 26957,
"text": "R-Vectors"
},
{
"code": null,
"e": 26978,
"s": 26967,
"text": "R Language"
},
{
"code": null,
"e": 27076,
"s": 26978,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27085,
"s": 27076,
"text": "Comments"
},
{
"code": null,
"e": 27098,
"s": 27085,
"text": "Old Comments"
},
{
"code": null,
"e": 27150,
"s": 27098,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27188,
"s": 27150,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27223,
"s": 27188,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27281,
"s": 27223,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27330,
"s": 27281,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27367,
"s": 27330,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 27417,
"s": 27367,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27434,
"s": 27417,
"text": "R - if statement"
},
{
"code": null,
"e": 27477,
"s": 27434,
"text": "Replace Specific Characters in String in R"
}
] |
Google Interview Experience for Software Engineer 2021 New Grad - GeeksforGeeks
|
17 Dec, 2020
I was contacted by a Google recruiter a few months ago, that my resume has been shortlisted for the Software Engineer 2021 New Grad Role. I was provided with the next action steps of how to proceed with the next round of interviews β Technical Phone Interview which is generally 45 minutes.
I wasnβt able to grab the offer, but I really hope that my experience and feedback about this whole process would help you as much as it helped me.
Usually, the recruiter asks about your preferable date and time for the interview, also they furnish you with some beneficial extra tips and information that you should know.
Round 1(Technical Phone Interview): I was asked about my recent project mentioned in the CV , there was a good discussion about it, for say 5 minutes. After that I was given a coding question to solve :
Given an N-ary Tree, find out the average width of each of the nodes present in that tree.
Note: A node can have βNβ number of children
Explanation: Consider the above tree, for node 1 , the average width would be the total no. of nodes under that node ie. 7 (including the target node) divided by the total number of levels under the parent node (7/3) .
The format of the answer should be: [node number : average width of that node ] that is ,for the given tree the answer is :
[ 1 : 2.5 , 2 : 1.5 , 3 : 1.5 , 4 : 1 , 5 : 1 , 6 : 1 , 7 : 1 ]
I was able to come up with a brute-force approach ONLY within that remaining time.
The interviewer was quite polite, interactive, and helped me with my initial queries against the given problem statement. One thing to note over here is while your interviewer is helping you clear the doubts and landing on a meaningful solution, it also means that you are getting a penalty for not being selected. Itβs a fact !
Good luck to you, if you are appearing/preparing for interviews! Sometimes itβs your day, sometimes it isnβt.
Do not give up
Google
Marketing
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE-1 (On-Campus)
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1
Zoho Interview | Set 3 (Off-Campus)
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience (Off-Campus) 2022
Directi Interview | Set 7 (Programming Questions)
Amazon Interview Experience for SDE-1
Amazon Interview Experience for SDE-1(Off-Campus)
|
[
{
"code": null,
"e": 25054,
"s": 25026,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 25345,
"s": 25054,
"text": "I was contacted by a Google recruiter a few months ago, that my resume has been shortlisted for the Software Engineer 2021 New Grad Role. I was provided with the next action steps of how to proceed with the next round of interviews β Technical Phone Interview which is generally 45 minutes."
},
{
"code": null,
"e": 25493,
"s": 25345,
"text": "I wasnβt able to grab the offer, but I really hope that my experience and feedback about this whole process would help you as much as it helped me."
},
{
"code": null,
"e": 25668,
"s": 25493,
"text": "Usually, the recruiter asks about your preferable date and time for the interview, also they furnish you with some beneficial extra tips and information that you should know."
},
{
"code": null,
"e": 25872,
"s": 25668,
"text": "Round 1(Technical Phone Interview): I was asked about my recent project mentioned in the CV , there was a good discussion about it, for say 5 minutes. After that I was given a coding question to solve : "
},
{
"code": null,
"e": 25963,
"s": 25872,
"text": "Given an N-ary Tree, find out the average width of each of the nodes present in that tree."
},
{
"code": null,
"e": 26008,
"s": 25963,
"text": "Note: A node can have βNβ number of children"
},
{
"code": null,
"e": 26227,
"s": 26008,
"text": "Explanation: Consider the above tree, for node 1 , the average width would be the total no. of nodes under that node ie. 7 (including the target node) divided by the total number of levels under the parent node (7/3) ."
},
{
"code": null,
"e": 26351,
"s": 26227,
"text": "The format of the answer should be: [node number : average width of that node ] that is ,for the given tree the answer is :"
},
{
"code": null,
"e": 26415,
"s": 26351,
"text": "[ 1 : 2.5 , 2 : 1.5 , 3 : 1.5 , 4 : 1 , 5 : 1 , 6 : 1 , 7 : 1 ]"
},
{
"code": null,
"e": 26498,
"s": 26415,
"text": "I was able to come up with a brute-force approach ONLY within that remaining time."
},
{
"code": null,
"e": 26828,
"s": 26498,
"text": "The interviewer was quite polite, interactive, and helped me with my initial queries against the given problem statement. One thing to note over here is while your interviewer is helping you clear the doubts and landing on a meaningful solution, it also means that you are getting a penalty for not being selected. Itβs a fact ! "
},
{
"code": null,
"e": 26939,
"s": 26828,
"text": "Good luck to you, if you are appearing/preparing for interviews! Sometimes itβs your day, sometimes it isnβt. "
},
{
"code": null,
"e": 26954,
"s": 26939,
"text": "Do not give up"
},
{
"code": null,
"e": 26961,
"s": 26954,
"text": "Google"
},
{
"code": null,
"e": 26971,
"s": 26961,
"text": "Marketing"
},
{
"code": null,
"e": 26993,
"s": 26971,
"text": "Interview Experiences"
},
{
"code": null,
"e": 27000,
"s": 26993,
"text": "Google"
},
{
"code": null,
"e": 27098,
"s": 27000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27107,
"s": 27098,
"text": "Comments"
},
{
"code": null,
"e": 27120,
"s": 27107,
"text": "Old Comments"
},
{
"code": null,
"e": 27170,
"s": 27120,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
},
{
"code": null,
"e": 27229,
"s": 27170,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 27267,
"s": 27229,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 27303,
"s": 27267,
"text": "Zoho Interview | Set 3 (Off-Campus)"
},
{
"code": null,
"e": 27339,
"s": 27303,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 27404,
"s": 27339,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 27450,
"s": 27404,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 27500,
"s": 27450,
"text": "Directi Interview | Set 7 (Programming Questions)"
},
{
"code": null,
"e": 27538,
"s": 27500,
"text": "Amazon Interview Experience for SDE-1"
}
] |
Combinations of sum with tuples in tuple list in Python
|
If it is required to get the combinations of sum with respect to tuples in a list of tuples, the 'combinations' method and the list comprehension can be used.
The 'combinations' method returns 'r' length subsequence of elements from the iterable that is passed as input. The combinations are shown in lexicographic sort order. The combination tuples are displayed in a sorted order.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same β
Live Demo
from itertools import combinations
my_list = [( 67, 45), (34, 56), (99, 123), (10, 56)]
print ("The list of tuple is : " )
print(my_list)
my_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)]
print("The summation combination result is : ")
print(my_result)
The list of tuple is :
[(67, 45), (34, 56), (99, 123), (10, 56)]
The summation combination result is :
[(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]
A list of tuples is defined, and is displayed on the console.
The combinations method is used to return subsequence of length 2, as mentioned in the method.
The list of tuple is iterated, and the elements from every tuple in the list of tuple is added to the element from the next tuple.
This value is assigned a variable.
This variable is the output that is displayed on the console.
|
[
{
"code": null,
"e": 1221,
"s": 1062,
"text": "If it is required to get the combinations of sum with respect to tuples in a list of tuples, the 'combinations' method and the list comprehension can be used."
},
{
"code": null,
"e": 1445,
"s": 1221,
"text": "The 'combinations' method returns 'r' length subsequence of elements from the iterable that is passed as input. The combinations are shown in lexicographic sort order. The combination tuples are displayed in a sorted order."
},
{
"code": null,
"e": 1572,
"s": 1445,
"text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)."
},
{
"code": null,
"e": 1634,
"s": 1572,
"text": "A list of tuple basically contains tuples enclosed in a list."
},
{
"code": null,
"e": 1673,
"s": 1634,
"text": "Below is a demonstration of the same β"
},
{
"code": null,
"e": 1683,
"s": 1673,
"text": "Live Demo"
},
{
"code": null,
"e": 1973,
"s": 1683,
"text": "from itertools import combinations\nmy_list = [( 67, 45), (34, 56), (99, 123), (10, 56)]\n\nprint (\"The list of tuple is : \" )\nprint(my_list)\n\nmy_result = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(my_list, 2)]\n\nprint(\"The summation combination result is : \")\nprint(my_result)"
},
{
"code": null,
"e": 2147,
"s": 1973,
"text": "The list of tuple is :\n[(67, 45), (34, 56), (99, 123), (10, 56)]\nThe summation combination result is :\n[(101, 101), (166, 168), (77, 101), (133, 179), (44, 112), (109, 179)]"
},
{
"code": null,
"e": 2209,
"s": 2147,
"text": "A list of tuples is defined, and is displayed on the console."
},
{
"code": null,
"e": 2304,
"s": 2209,
"text": "The combinations method is used to return subsequence of length 2, as mentioned in the method."
},
{
"code": null,
"e": 2435,
"s": 2304,
"text": "The list of tuple is iterated, and the elements from every tuple in the list of tuple is added to the element from the next tuple."
},
{
"code": null,
"e": 2470,
"s": 2435,
"text": "This value is assigned a variable."
},
{
"code": null,
"e": 2532,
"s": 2470,
"text": "This variable is the output that is displayed on the console."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.