title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Clojure - Exception Handling
|
Exception handling is required in any programming language to handle the runtime errors so that the normal flow of the application can be maintained. Exception usually disrupts the normal flow of the application, which is the reason why we need to use exception handling in our application.
Exception is broadly classified into the following categories −
Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. E.g. IOException, SQLException, etc. Checked exceptions are checked at compile-time.
Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. E.g. IOException, SQLException, etc. Checked exceptions are checked at compile-time.
Let’s consider the following program which does an operation on a file called Example.txt. However, there can be always a case wherein the file Example.txt does not exist.
(ns clojure.examples.example
(:gen-class))
;; This program displays Hello World
(defn Example []
(def string1 (slurp "Example.txt"))
(println string1))
(Example)
If the file Example.txt does not exist, then the following exception will be generated by the program.
Caused by: java.io.FileNotFoundException: Example.txt (No such file or
directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at clojure.java.io$fn__9185.invoke(io.clj:229)
at clojure.java.io$fn__9098$G__9091__9105.invoke(io.clj:69)
at clojure.java.io$fn__9197.invoke(io.clj:258)
at clojure.java.io$fn__9098$G__9091__9105.invoke(io.clj:69)
From the above exception, we can clearly see that the program raised a FileNotFoundException.
Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake.
(ns clojure.examples.example
(:gen-class))
(defn Example []
(try
(aget (int-array [1 2 3]) 5)
(catch Exception e (println (str "caught exception: " (.toString e))))
(finally (println "This is our final block")))
(println "Let's move on"))
(Example)
When the above code is executed, the following exception will be raised.
caught exception: java.lang.ArrayIndexOutOfBoundsException: 5
This is our final block
Let's move on
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError, etc. These are errors which the program can never recover from and will cause the program to crash. We now need some mechanism to catch these exceptions so that the program can continue to run if these exceptions exist.
The following diagram shows how the hierarchy of exceptions in Clojure is organized. It’s all based on the hierarchy defined in Java.
Just like other programming languages, Clojure provides the normal ‘try-catch‘ block to catch exceptions as and when they occur.
Following is the general syntax of the try-catch block.
(try
(//Protected code)
catch Exception e1)
(//Catch block)
All of your code which could raise an exception is placed in the Protected code block.
In the catch block, you can write custom code to handle your exception so that the application can recover from the exception.
Let’s look at our earlier example which generated a file-not-found exception and see how we can use the try catch block to catch the exception raised by the program.
(ns clojure.examples.example
(:gen-class))
(defn Example []
(try
(def string1 (slurp "Example.txt"))
(println string1)
(catch Exception e (println (str "caught exception: " (.getMessage e))))))
(Example)
The above program produces the following output.
caught exception: Example.txt (No such file or directory)
From the above code, we wrap out faulty code in the try block. In the catch block, we are just catching our exception and outputting a message that an exception has occurred. So, we now have a meaningful way of capturing the exception, which is generated by the program.
One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly.
Let’s modify our earlier code to include two catch blocks, one which is specific for our file not found exception and the other is for a general exception block.
(ns clojure.examples.example
(:gen-class))
(defn Example []
(try
(def string1 (slurp "Example.txt"))
(println string1)
(catch java.io.FileNotFoundException e (println (str "caught file
exception: " (.getMessage e))))
(catch Exception e (println (str "caught exception: " (.getMessage e)))))
(println "Let's move on"))
(Example)
The above program produces the following output.
caught file exception: Example.txt (No such file or directory)
Let's move on
From the above output, we can clearly see that our exception was caught by the ‘FileNotFoundException’ catch block and not the general one.
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. Following is the syntax for this block.
(try
(//Protected code)
catch Exception e1)
(//Catch block)
(finally
//Cleanup code)
Let’s modify the above code and add the finally block of code. Following is the code snippet.
(ns clojure.examples.example
(:gen-class))
(defn Example []
(try
(def string1 (slurp "Example.txt"))
(println string1)
(catch java.io.FileNotFoundException e (println (str "caught file
exception: " (.getMessage e))))
(catch Exception e (println (str "caught exception: " (.getMessage e))))
(finally (println "This is our final block")))
(println "Let's move on"))
(Example)
The above program produces the following output.
caught file exception: Example.txt (No such file or directory)
This is our final block
Let's move on
From the above program, you can see that the final block is also implemented after the catch block catches the required exception.
Since Clojure derives its exception handling from Java, similar to Java, the following methods are available in Clojure for managing the exceptions.
public String getMessage() − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
public String getMessage() − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
public Throwable getCause() − Returns the cause of the exception as represented by a Throwable object.
public Throwable getCause() − Returns the cause of the exception as represented by a Throwable object.
public String toString() − Returns the name of the class concatenated with the result of getMessage().
public String toString() − Returns the name of the class concatenated with the result of getMessage().
public void printStackTrace() − Prints the result of toString() along with the stack trace to System.err, the error output stream.
public void printStackTrace() − Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace() − Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public StackTraceElement [] getStackTrace() − Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace() − Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
public Throwable fillInStackTrace() − Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
Following is the example code that uses some of the methods listed above.
(ns clojure.examples.example
(:gen-class))
(defn Example []
(try
(def string1 (slurp "Example.txt"))
(println string1)
(catch java.io.FileNotFoundException e (println (str "caught file
exception: " (.toString e))))
(catch Exception e (println (str "caught exception: " (.toString e))))
(finally (println "This is our final block")))
(println "Let's move on"))
(Example)
The above program produces the following output.
caught file exception: java.io.FileNotFoundException: Example.txt (No such file
or directory)
This is our final block
Let's move on
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2665,
"s": 2374,
"text": "Exception handling is required in any programming language to handle the runtime errors so that the normal flow of the application can be maintained. Exception usually disrupts the normal flow of the application, which is the reason why we need to use exception handling in our application."
},
{
"code": null,
"e": 2729,
"s": 2665,
"text": "Exception is broadly classified into the following categories −"
},
{
"code": null,
"e": 2941,
"s": 2729,
"text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. E.g. IOException, SQLException, etc. Checked exceptions are checked at compile-time."
},
{
"code": null,
"e": 3153,
"s": 2941,
"text": "Checked Exception − The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. E.g. IOException, SQLException, etc. Checked exceptions are checked at compile-time."
},
{
"code": null,
"e": 3325,
"s": 3153,
"text": "Let’s consider the following program which does an operation on a file called Example.txt. However, there can be always a case wherein the file Example.txt does not exist."
},
{
"code": null,
"e": 3497,
"s": 3325,
"text": "(ns clojure.examples.example\n (:gen-class))\n\n;; This program displays Hello World\n(defn Example []\n (def string1 (slurp \"Example.txt\"))\n (println string1))\n(Example)"
},
{
"code": null,
"e": 3600,
"s": 3497,
"text": "If the file Example.txt does not exist, then the following exception will be generated by the program."
},
{
"code": null,
"e": 4063,
"s": 3600,
"text": "Caused by: java.io.FileNotFoundException: Example.txt (No such file or\ndirectory)\nat java.io.FileInputStream.open0(Native Method)\nat java.io.FileInputStream.open(FileInputStream.java:195)\nat java.io.FileInputStream.<init>(FileInputStream.java:138)\nat clojure.java.io$fn__9185.invoke(io.clj:229)\nat clojure.java.io$fn__9098$G__9091__9105.invoke(io.clj:69)\nat clojure.java.io$fn__9197.invoke(io.clj:258)\nat clojure.java.io$fn__9098$G__9091__9105.invoke(io.clj:69)\n"
},
{
"code": null,
"e": 4157,
"s": 4063,
"text": "From the above exception, we can clearly see that the program raised a FileNotFoundException."
},
{
"code": null,
"e": 4437,
"s": 4157,
"text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime."
},
{
"code": null,
"e": 4717,
"s": 4437,
"text": "Unchecked Exception − The classes that extend RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime."
},
{
"code": null,
"e": 4935,
"s": 4717,
"text": "One classical case is the ArrayIndexOutOfBoundsException which happens when you try to access an index of an array which is greater than the length of the array. Following is a typical example of this sort of mistake."
},
{
"code": null,
"e": 5211,
"s": 4935,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn Example []\n (try\n (aget (int-array [1 2 3]) 5)\n (catch Exception e (println (str \"caught exception: \" (.toString e))))\n (finally (println \"This is our final block\")))\n (println \"Let's move on\"))\n(Example)"
},
{
"code": null,
"e": 5284,
"s": 5211,
"text": "When the above code is executed, the following exception will be raised."
},
{
"code": null,
"e": 5385,
"s": 5284,
"text": "caught exception: java.lang.ArrayIndexOutOfBoundsException: 5\nThis is our final block\nLet's move on\n"
},
{
"code": null,
"e": 5688,
"s": 5385,
"text": "Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError, etc. These are errors which the program can never recover from and will cause the program to crash. We now need some mechanism to catch these exceptions so that the program can continue to run if these exceptions exist."
},
{
"code": null,
"e": 5822,
"s": 5688,
"text": "The following diagram shows how the hierarchy of exceptions in Clojure is organized. It’s all based on the hierarchy defined in Java."
},
{
"code": null,
"e": 5951,
"s": 5822,
"text": "Just like other programming languages, Clojure provides the normal ‘try-catch‘ block to catch exceptions as and when they occur."
},
{
"code": null,
"e": 6007,
"s": 5951,
"text": "Following is the general syntax of the try-catch block."
},
{
"code": null,
"e": 6074,
"s": 6007,
"text": "(try\n (//Protected code)\n catch Exception e1)\n(//Catch block)\n"
},
{
"code": null,
"e": 6161,
"s": 6074,
"text": "All of your code which could raise an exception is placed in the Protected code block."
},
{
"code": null,
"e": 6288,
"s": 6161,
"text": "In the catch block, you can write custom code to handle your exception so that the application can recover from the exception."
},
{
"code": null,
"e": 6454,
"s": 6288,
"text": "Let’s look at our earlier example which generated a file-not-found exception and see how we can use the try catch block to catch the exception raised by the program."
},
{
"code": null,
"e": 6682,
"s": 6454,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn Example []\n (try\n (def string1 (slurp \"Example.txt\"))\n (println string1)\n (catch Exception e (println (str \"caught exception: \" (.getMessage e))))))\n(Example)"
},
{
"code": null,
"e": 6731,
"s": 6682,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 6790,
"s": 6731,
"text": "caught exception: Example.txt (No such file or directory)\n"
},
{
"code": null,
"e": 7061,
"s": 6790,
"text": "From the above code, we wrap out faulty code in the try block. In the catch block, we are just catching our exception and outputting a message that an exception has occurred. So, we now have a meaningful way of capturing the exception, which is generated by the program."
},
{
"code": null,
"e": 7247,
"s": 7061,
"text": "One can have multiple catch blocks to handle multiple types of exceptions. For each catch block, depending on the type of exception raised you would write code to handle it accordingly."
},
{
"code": null,
"e": 7409,
"s": 7247,
"text": "Let’s modify our earlier code to include two catch blocks, one which is specific for our file not found exception and the other is for a general exception block."
},
{
"code": null,
"e": 7793,
"s": 7409,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn Example []\n (try\n (def string1 (slurp \"Example.txt\"))\n (println string1)\n \n (catch java.io.FileNotFoundException e (println (str \"caught file\n exception: \" (.getMessage e))))\n \n (catch Exception e (println (str \"caught exception: \" (.getMessage e)))))\n (println \"Let's move on\"))\n(Example)"
},
{
"code": null,
"e": 7842,
"s": 7793,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 7920,
"s": 7842,
"text": "caught file exception: Example.txt (No such file or directory)\nLet's move on\n"
},
{
"code": null,
"e": 8060,
"s": 7920,
"text": "From the above output, we can clearly see that our exception was caught by the ‘FileNotFoundException’ catch block and not the general one."
},
{
"code": null,
"e": 8201,
"s": 8060,
"text": "The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception."
},
{
"code": null,
"e": 8381,
"s": 8201,
"text": "Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. Following is the syntax for this block."
},
{
"code": null,
"e": 8476,
"s": 8381,
"text": "(try\n (//Protected code)\n catch Exception e1)\n(//Catch block)\n(finally\n //Cleanup code)\n"
},
{
"code": null,
"e": 8570,
"s": 8476,
"text": "Let’s modify the above code and add the finally block of code. Following is the code snippet."
},
{
"code": null,
"e": 9006,
"s": 8570,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn Example []\n (try\n (def string1 (slurp \"Example.txt\"))\n (println string1)\n \n (catch java.io.FileNotFoundException e (println (str \"caught file\n exception: \" (.getMessage e))))\n \n (catch Exception e (println (str \"caught exception: \" (.getMessage e))))\n (finally (println \"This is our final block\")))\n (println \"Let's move on\"))\n(Example)"
},
{
"code": null,
"e": 9055,
"s": 9006,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 9157,
"s": 9055,
"text": "caught file exception: Example.txt (No such file or directory)\nThis is our final block\nLet's move on\n"
},
{
"code": null,
"e": 9288,
"s": 9157,
"text": "From the above program, you can see that the final block is also implemented after the catch block catches the required exception."
},
{
"code": null,
"e": 9437,
"s": 9288,
"text": "Since Clojure derives its exception handling from Java, similar to Java, the following methods are available in Clojure for managing the exceptions."
},
{
"code": null,
"e": 9590,
"s": 9437,
"text": "public String getMessage() − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor."
},
{
"code": null,
"e": 9743,
"s": 9590,
"text": "public String getMessage() − Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor."
},
{
"code": null,
"e": 9846,
"s": 9743,
"text": "public Throwable getCause() − Returns the cause of the exception as represented by a Throwable object."
},
{
"code": null,
"e": 9949,
"s": 9846,
"text": "public Throwable getCause() − Returns the cause of the exception as represented by a Throwable object."
},
{
"code": null,
"e": 10052,
"s": 9949,
"text": "public String toString() − Returns the name of the class concatenated with the result of getMessage()."
},
{
"code": null,
"e": 10155,
"s": 10052,
"text": "public String toString() − Returns the name of the class concatenated with the result of getMessage()."
},
{
"code": null,
"e": 10286,
"s": 10155,
"text": "public void printStackTrace() − Prints the result of toString() along with the stack trace to System.err, the error output stream."
},
{
"code": null,
"e": 10417,
"s": 10286,
"text": "public void printStackTrace() − Prints the result of toString() along with the stack trace to System.err, the error output stream."
},
{
"code": null,
"e": 10674,
"s": 10417,
"text": "public StackTraceElement [] getStackTrace() − Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack."
},
{
"code": null,
"e": 10931,
"s": 10674,
"text": "public StackTraceElement [] getStackTrace() − Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack."
},
{
"code": null,
"e": 11101,
"s": 10931,
"text": "public Throwable fillInStackTrace() − Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace."
},
{
"code": null,
"e": 11271,
"s": 11101,
"text": "public Throwable fillInStackTrace() − Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace."
},
{
"code": null,
"e": 11345,
"s": 11271,
"text": "Following is the example code that uses some of the methods listed above."
},
{
"code": null,
"e": 11774,
"s": 11345,
"text": "(ns clojure.examples.example\n (:gen-class))\n(defn Example []\n (try\n (def string1 (slurp \"Example.txt\"))\n (println string1)\n \n (catch java.io.FileNotFoundException e (println (str \"caught file\n exception: \" (.toString e))))\n \n (catch Exception e (println (str \"caught exception: \" (.toString e))))\n (finally (println \"This is our final block\")))\n (println \"Let's move on\"))\n(Example)"
},
{
"code": null,
"e": 11823,
"s": 11774,
"text": "The above program produces the following output."
},
{
"code": null,
"e": 11956,
"s": 11823,
"text": "caught file exception: java.io.FileNotFoundException: Example.txt (No such file\nor directory)\nThis is our final block\nLet's move on\n"
},
{
"code": null,
"e": 11963,
"s": 11956,
"text": " Print"
},
{
"code": null,
"e": 11974,
"s": 11963,
"text": " Add Notes"
}
] |
The Ultimate Guide to Logical Operators in R | by Linda Ngo | Towards Data Science
|
Suppose we want to change or compare the results of the comparisons made using relational operators. How would we go about doing that?
R does this using the AND, the OR, and the NOT operator.
AND operator &
OR operator |
NOT operator !
The AND operator takes two logical values and returns TRUE only if both values are TRUE themselves. This means that TRUE & TRUE evaluates to TRUE, but that FALSE & TRUE, TRUE & FALSE, and FALSE & FALSE evaluates to FALSE.
Instead of using logical values, we can use the results of comparisons. Suppose we have a variable x, equal to 12. To check if this variable is greater than 5 but less than 15, we can use x greater than 5 and x less than 15.
x <- 12x > 5 & x < 15
The first part, x > 5 will evaluate to TRUE since 12 is greater than 5. The second part, x < 15 will also evaluate to TRUE since 12 is also less than 15. So, the result of this expression is TRUE since TRUE & TRUE is TRUE. This makes sense, because 12 lies between 5 and 15.
However, if x were 17, the expression x > 5 & x < 15 would simplify to TRUE & FALSE, which results in the expression being FALSE.
Consider the following vector and variable:
linkedin <- c(16, 9, 13, 5, 2, 17, 14)last <- tail(linkedin, 1)
The linkedin vector represents the number of LinekdIn views you profile has gotten in the last seven days. The last variable represents the last value of the linkedin vector.
Determine whether the last variable is between 15 and 20, excluding 15 but including 20.
# We are looking for the R equivalent of 15 < last <= 20last > 15 & last <= 20
Consider the following vectors:
linkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)
The linkedin vector represents the views on your LinkedIn profile from the past 7 days, and the facebook vector represents the views on your Facebook profile from the past 7 days.
Determine when LinkedIn views exceeded 10 and Facebook views failed to reach 10 for a particular day. Use the linkedin and facebook vectors.
# linkedin exceeds 10 but facebook below 10linkedin > 10 & facebook < 10
Consider the following matrix:
views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)
The linkedin and facebook variable corresponds to the same vectors in the previous for you to try.
The matrix views has the first and second row corresponding to the linkedin and facebook vectors, respectively.
Determine when the views matrix equals to a number between 11 and 14, excluding 11 and including 14.
# When is views between 11 (exclusive) and 14 (inclusive)?views > 11 & views <= 14
The OR operator (|) works similarly, but the difference is that only at least one of the logical values should be equal to TRUE for the entire OR operation to evaluate to TRUE.
This means that TRUE | TRUE equals TRUE, but also, TRUE | FALSE and FALSE | TRUE evaluates to TRUE. When both logicals are FALSE in an OR operation, so in the case of FALSE | FALSE, the result is FALSE. Remember, the OR operation is not an exclusive or operation, so TRUE | TRUE equals TRUE as well.
With the AND operator, only TRUE & TRUE makes a TRUE, anything else is FALSE. With the OR operator, only FALSE | FALSE makes a FALSE, anything else is TRUE.
Just as for AND operations, we can use comparisons together with the OR operator. Suppose we have a variable y, equal to 4. To see if this variable is less than 5 or greater than 15, we can use the following expression:
y <- 4y < 5 | y > 15
R will first carry out the comparisons, resulting in TRUE | FALSE, which in turn results in TRUE.
Now, suppose y is 14. The expression y < 5 | y > 15 now evaluates to FALSE | FALSE. Neither one of the comparisons are TRUE, so the result is FALSE.
Using the same variables from the last for you to try, determine if last is under 5 or above 10.
linkedin <- c(16, 9, 13, 5, 2, 17, 14)last <- tail(linkedin, 1)
# Is last under 5 or above 10?last < 5 | last > 10
Consider the same linkedin and facebook vectors from earlier exercises.
linkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)
Determine when one or both social profiles were visited at least 12 times.
# When were one or both visited at least 12 times?linkedin >= 12 | facebook >= 12
The NOT operator, represented by an exclamation mark !, simply negates the logical value it is used on. That is, !TRUE evaluates to FALSE, while !FALSE evaluates to TRUE.
Just like the OR and AND operators, we can use the NOT operator in combination with logical operators. This is not always necessary. For example, !(x < 5) is the same as x >= 5.
However, there are cases in R where the NOT operator is especially handy. For example, the built-in R function, is.numeric() checks if an R object is a numeric. There is no respective built-in function that checks if it isn’t a numeric. To check, we would have to negate the result ( !is.numeric()). So, is.numeric(5) evaluates to TRUE, as 5 is a numeric. If we negate this result using the NOT operator (!is.numeric(5)), we get FALSE. If, however, we use is.numeric("hello") we get FALSE. Negating this result ( !is.numeric("hello")) gives us TRUE.
Now, how do logical operators work with vectors and matrices? Just as relational operators, they perform the operations element-wise. Consider theses two vectors:
c(TRUE, TRUE, FALSE) & c(TRUE, FALSE, FALSE)
The AND operation on these two vectors, results in a vector with the elements TRUE, FALSE, and FALSE.
TRUE FALSE FALSE
The first elements in both vectors are TRUE, so the first element of the resulting vector contains TRUE. Similarly, for the second elements where TRUE & FALSE result in FALSE, and in the third elements, where FALSE & FALSE give FALSE.
A similar thing happens with the OR operator:
c(TRUE, TRUE, FALSE) | c(TRUE, FALSE, FALSE)
TRUE | TRUE gives TRUE, TRUE | FALSE also gives TRUE, and FALSE | FALSE gives FALSE. So, we would get the result:
TRUE TRUE FALSE
The NOT operator also works on every element on the vector:
!c(TRUE, TRUE, FALSE)
TRUE are converted to FALSE, and FALSE are converted to TRUE. So, we would get the result
FALSE FALSE TRUE
What would the following set of R expressions return:
x <- 5y <- 7!(!(x < 4) & !!!(y > 12))
FALSE
To determine the answer, it is helpful to break down the query to smaller expressions:
We first have the left expression !(x < 4) of the inner expression (!(x < 4) & !!!(y > 12)).
x < 4 — since x is 5, and 5 < 4 is not true, this statement evaluates to FALSE!(x < 4) — From the step above, we determined that x < 4 evaluates to FALSE. Negating this result gives us !FALSE, which is TRUE.
x < 4 — since x is 5, and 5 < 4 is not true, this statement evaluates to FALSE
!(x < 4) — From the step above, we determined that x < 4 evaluates to FALSE. Negating this result gives us !FALSE, which is TRUE.
Next, we have the right expression !!!(y > 12) of the inner expression (!(x < 4) & !!!(y > 12)).
y > 12 — Since y is 7, and 7 > 12 is not true, this expression evaluates to FALSE .!(y > 12) — Negating the result from step 1, we get !FALSE, or TRUE.!!(y > 12) — Negating the result from step 2, we get !TRUE, or FALSE.!!!(y > 12) — Negating the result from step 3, we get !FALSE, or TRUE.
y > 12 — Since y is 7, and 7 > 12 is not true, this expression evaluates to FALSE .
!(y > 12) — Negating the result from step 1, we get !FALSE, or TRUE.
!!(y > 12) — Negating the result from step 2, we get !TRUE, or FALSE.
!!!(y > 12) — Negating the result from step 3, we get !FALSE, or TRUE.
So for the inner expression (!(x < 4) & !!!(y > 12)), it evaluates to TRUE & TRUE, which equals TRUE.
The outer NOT operator ! negates this TRUE making !(!(x < 4) & !!!(y > 12)) equal to !TRUE or FALSE.
What is the difference between a single and a double ampersand or vertical bar? In R, you can use both the single sign version or the double sign version, but the result of the logical operation you’re carrying out can be different. The biggest difference occurs when you use the two types of operations on vectors.
c(TRUE, TRUE, FALSE) & c(TRUE, FALSE, FALSE)
As we’ve seen before, the above expression evaluates to a vector:
TRUE FALSE FALSE
However, if we use double ampersand, we simply get TRUE.
c(TRUE, TRUE, FALSE) && c(TRUE, FALSE, FALSE)
This is because the double ampersand operation only examines the first element of each vector. In this case, the first elements are TRUE and TRUE, so the expression returns TRUE.
You can see similar things happening with the OR operator. The single sign version | returns and entire vector. The double sign version || returns the result of the OR operator on the first element of each vector.
So pay attention when doing logical operations on vectors. You will likely want to use the single sign version.
All images, unless specified, are owned by the author. The banner image was created using Canva.
|
[
{
"code": null,
"e": 307,
"s": 172,
"text": "Suppose we want to change or compare the results of the comparisons made using relational operators. How would we go about doing that?"
},
{
"code": null,
"e": 364,
"s": 307,
"text": "R does this using the AND, the OR, and the NOT operator."
},
{
"code": null,
"e": 379,
"s": 364,
"text": "AND operator &"
},
{
"code": null,
"e": 393,
"s": 379,
"text": "OR operator |"
},
{
"code": null,
"e": 408,
"s": 393,
"text": "NOT operator !"
},
{
"code": null,
"e": 630,
"s": 408,
"text": "The AND operator takes two logical values and returns TRUE only if both values are TRUE themselves. This means that TRUE & TRUE evaluates to TRUE, but that FALSE & TRUE, TRUE & FALSE, and FALSE & FALSE evaluates to FALSE."
},
{
"code": null,
"e": 855,
"s": 630,
"text": "Instead of using logical values, we can use the results of comparisons. Suppose we have a variable x, equal to 12. To check if this variable is greater than 5 but less than 15, we can use x greater than 5 and x less than 15."
},
{
"code": null,
"e": 877,
"s": 855,
"text": "x <- 12x > 5 & x < 15"
},
{
"code": null,
"e": 1152,
"s": 877,
"text": "The first part, x > 5 will evaluate to TRUE since 12 is greater than 5. The second part, x < 15 will also evaluate to TRUE since 12 is also less than 15. So, the result of this expression is TRUE since TRUE & TRUE is TRUE. This makes sense, because 12 lies between 5 and 15."
},
{
"code": null,
"e": 1282,
"s": 1152,
"text": "However, if x were 17, the expression x > 5 & x < 15 would simplify to TRUE & FALSE, which results in the expression being FALSE."
},
{
"code": null,
"e": 1326,
"s": 1282,
"text": "Consider the following vector and variable:"
},
{
"code": null,
"e": 1390,
"s": 1326,
"text": "linkedin <- c(16, 9, 13, 5, 2, 17, 14)last <- tail(linkedin, 1)"
},
{
"code": null,
"e": 1565,
"s": 1390,
"text": "The linkedin vector represents the number of LinekdIn views you profile has gotten in the last seven days. The last variable represents the last value of the linkedin vector."
},
{
"code": null,
"e": 1654,
"s": 1565,
"text": "Determine whether the last variable is between 15 and 20, excluding 15 but including 20."
},
{
"code": null,
"e": 1733,
"s": 1654,
"text": "# We are looking for the R equivalent of 15 < last <= 20last > 15 & last <= 20"
},
{
"code": null,
"e": 1765,
"s": 1733,
"text": "Consider the following vectors:"
},
{
"code": null,
"e": 1842,
"s": 1765,
"text": "linkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)"
},
{
"code": null,
"e": 2022,
"s": 1842,
"text": "The linkedin vector represents the views on your LinkedIn profile from the past 7 days, and the facebook vector represents the views on your Facebook profile from the past 7 days."
},
{
"code": null,
"e": 2163,
"s": 2022,
"text": "Determine when LinkedIn views exceeded 10 and Facebook views failed to reach 10 for a particular day. Use the linkedin and facebook vectors."
},
{
"code": null,
"e": 2236,
"s": 2163,
"text": "# linkedin exceeds 10 but facebook below 10linkedin > 10 & facebook < 10"
},
{
"code": null,
"e": 2267,
"s": 2236,
"text": "Consider the following matrix:"
},
{
"code": null,
"e": 2330,
"s": 2267,
"text": "views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE)"
},
{
"code": null,
"e": 2429,
"s": 2330,
"text": "The linkedin and facebook variable corresponds to the same vectors in the previous for you to try."
},
{
"code": null,
"e": 2541,
"s": 2429,
"text": "The matrix views has the first and second row corresponding to the linkedin and facebook vectors, respectively."
},
{
"code": null,
"e": 2642,
"s": 2541,
"text": "Determine when the views matrix equals to a number between 11 and 14, excluding 11 and including 14."
},
{
"code": null,
"e": 2725,
"s": 2642,
"text": "# When is views between 11 (exclusive) and 14 (inclusive)?views > 11 & views <= 14"
},
{
"code": null,
"e": 2902,
"s": 2725,
"text": "The OR operator (|) works similarly, but the difference is that only at least one of the logical values should be equal to TRUE for the entire OR operation to evaluate to TRUE."
},
{
"code": null,
"e": 3202,
"s": 2902,
"text": "This means that TRUE | TRUE equals TRUE, but also, TRUE | FALSE and FALSE | TRUE evaluates to TRUE. When both logicals are FALSE in an OR operation, so in the case of FALSE | FALSE, the result is FALSE. Remember, the OR operation is not an exclusive or operation, so TRUE | TRUE equals TRUE as well."
},
{
"code": null,
"e": 3359,
"s": 3202,
"text": "With the AND operator, only TRUE & TRUE makes a TRUE, anything else is FALSE. With the OR operator, only FALSE | FALSE makes a FALSE, anything else is TRUE."
},
{
"code": null,
"e": 3579,
"s": 3359,
"text": "Just as for AND operations, we can use comparisons together with the OR operator. Suppose we have a variable y, equal to 4. To see if this variable is less than 5 or greater than 15, we can use the following expression:"
},
{
"code": null,
"e": 3600,
"s": 3579,
"text": "y <- 4y < 5 | y > 15"
},
{
"code": null,
"e": 3698,
"s": 3600,
"text": "R will first carry out the comparisons, resulting in TRUE | FALSE, which in turn results in TRUE."
},
{
"code": null,
"e": 3847,
"s": 3698,
"text": "Now, suppose y is 14. The expression y < 5 | y > 15 now evaluates to FALSE | FALSE. Neither one of the comparisons are TRUE, so the result is FALSE."
},
{
"code": null,
"e": 3944,
"s": 3847,
"text": "Using the same variables from the last for you to try, determine if last is under 5 or above 10."
},
{
"code": null,
"e": 4008,
"s": 3944,
"text": "linkedin <- c(16, 9, 13, 5, 2, 17, 14)last <- tail(linkedin, 1)"
},
{
"code": null,
"e": 4059,
"s": 4008,
"text": "# Is last under 5 or above 10?last < 5 | last > 10"
},
{
"code": null,
"e": 4131,
"s": 4059,
"text": "Consider the same linkedin and facebook vectors from earlier exercises."
},
{
"code": null,
"e": 4208,
"s": 4131,
"text": "linkedin <- c(16, 9, 13, 5, 2, 17, 14)facebook <- c(17, 7, 5, 16, 8, 13, 14)"
},
{
"code": null,
"e": 4283,
"s": 4208,
"text": "Determine when one or both social profiles were visited at least 12 times."
},
{
"code": null,
"e": 4365,
"s": 4283,
"text": "# When were one or both visited at least 12 times?linkedin >= 12 | facebook >= 12"
},
{
"code": null,
"e": 4536,
"s": 4365,
"text": "The NOT operator, represented by an exclamation mark !, simply negates the logical value it is used on. That is, !TRUE evaluates to FALSE, while !FALSE evaluates to TRUE."
},
{
"code": null,
"e": 4714,
"s": 4536,
"text": "Just like the OR and AND operators, we can use the NOT operator in combination with logical operators. This is not always necessary. For example, !(x < 5) is the same as x >= 5."
},
{
"code": null,
"e": 5264,
"s": 4714,
"text": "However, there are cases in R where the NOT operator is especially handy. For example, the built-in R function, is.numeric() checks if an R object is a numeric. There is no respective built-in function that checks if it isn’t a numeric. To check, we would have to negate the result ( !is.numeric()). So, is.numeric(5) evaluates to TRUE, as 5 is a numeric. If we negate this result using the NOT operator (!is.numeric(5)), we get FALSE. If, however, we use is.numeric(\"hello\") we get FALSE. Negating this result ( !is.numeric(\"hello\")) gives us TRUE."
},
{
"code": null,
"e": 5427,
"s": 5264,
"text": "Now, how do logical operators work with vectors and matrices? Just as relational operators, they perform the operations element-wise. Consider theses two vectors:"
},
{
"code": null,
"e": 5472,
"s": 5427,
"text": "c(TRUE, TRUE, FALSE) & c(TRUE, FALSE, FALSE)"
},
{
"code": null,
"e": 5574,
"s": 5472,
"text": "The AND operation on these two vectors, results in a vector with the elements TRUE, FALSE, and FALSE."
},
{
"code": null,
"e": 5591,
"s": 5574,
"text": "TRUE FALSE FALSE"
},
{
"code": null,
"e": 5826,
"s": 5591,
"text": "The first elements in both vectors are TRUE, so the first element of the resulting vector contains TRUE. Similarly, for the second elements where TRUE & FALSE result in FALSE, and in the third elements, where FALSE & FALSE give FALSE."
},
{
"code": null,
"e": 5872,
"s": 5826,
"text": "A similar thing happens with the OR operator:"
},
{
"code": null,
"e": 5917,
"s": 5872,
"text": "c(TRUE, TRUE, FALSE) | c(TRUE, FALSE, FALSE)"
},
{
"code": null,
"e": 6031,
"s": 5917,
"text": "TRUE | TRUE gives TRUE, TRUE | FALSE also gives TRUE, and FALSE | FALSE gives FALSE. So, we would get the result:"
},
{
"code": null,
"e": 6047,
"s": 6031,
"text": "TRUE TRUE FALSE"
},
{
"code": null,
"e": 6107,
"s": 6047,
"text": "The NOT operator also works on every element on the vector:"
},
{
"code": null,
"e": 6129,
"s": 6107,
"text": "!c(TRUE, TRUE, FALSE)"
},
{
"code": null,
"e": 6219,
"s": 6129,
"text": "TRUE are converted to FALSE, and FALSE are converted to TRUE. So, we would get the result"
},
{
"code": null,
"e": 6236,
"s": 6219,
"text": "FALSE FALSE TRUE"
},
{
"code": null,
"e": 6290,
"s": 6236,
"text": "What would the following set of R expressions return:"
},
{
"code": null,
"e": 6328,
"s": 6290,
"text": "x <- 5y <- 7!(!(x < 4) & !!!(y > 12))"
},
{
"code": null,
"e": 6334,
"s": 6328,
"text": "FALSE"
},
{
"code": null,
"e": 6421,
"s": 6334,
"text": "To determine the answer, it is helpful to break down the query to smaller expressions:"
},
{
"code": null,
"e": 6514,
"s": 6421,
"text": "We first have the left expression !(x < 4) of the inner expression (!(x < 4) & !!!(y > 12))."
},
{
"code": null,
"e": 6722,
"s": 6514,
"text": "x < 4 — since x is 5, and 5 < 4 is not true, this statement evaluates to FALSE!(x < 4) — From the step above, we determined that x < 4 evaluates to FALSE. Negating this result gives us !FALSE, which is TRUE."
},
{
"code": null,
"e": 6801,
"s": 6722,
"text": "x < 4 — since x is 5, and 5 < 4 is not true, this statement evaluates to FALSE"
},
{
"code": null,
"e": 6931,
"s": 6801,
"text": "!(x < 4) — From the step above, we determined that x < 4 evaluates to FALSE. Negating this result gives us !FALSE, which is TRUE."
},
{
"code": null,
"e": 7028,
"s": 6931,
"text": "Next, we have the right expression !!!(y > 12) of the inner expression (!(x < 4) & !!!(y > 12))."
},
{
"code": null,
"e": 7319,
"s": 7028,
"text": "y > 12 — Since y is 7, and 7 > 12 is not true, this expression evaluates to FALSE .!(y > 12) — Negating the result from step 1, we get !FALSE, or TRUE.!!(y > 12) — Negating the result from step 2, we get !TRUE, or FALSE.!!!(y > 12) — Negating the result from step 3, we get !FALSE, or TRUE."
},
{
"code": null,
"e": 7403,
"s": 7319,
"text": "y > 12 — Since y is 7, and 7 > 12 is not true, this expression evaluates to FALSE ."
},
{
"code": null,
"e": 7472,
"s": 7403,
"text": "!(y > 12) — Negating the result from step 1, we get !FALSE, or TRUE."
},
{
"code": null,
"e": 7542,
"s": 7472,
"text": "!!(y > 12) — Negating the result from step 2, we get !TRUE, or FALSE."
},
{
"code": null,
"e": 7613,
"s": 7542,
"text": "!!!(y > 12) — Negating the result from step 3, we get !FALSE, or TRUE."
},
{
"code": null,
"e": 7715,
"s": 7613,
"text": "So for the inner expression (!(x < 4) & !!!(y > 12)), it evaluates to TRUE & TRUE, which equals TRUE."
},
{
"code": null,
"e": 7816,
"s": 7715,
"text": "The outer NOT operator ! negates this TRUE making !(!(x < 4) & !!!(y > 12)) equal to !TRUE or FALSE."
},
{
"code": null,
"e": 8132,
"s": 7816,
"text": "What is the difference between a single and a double ampersand or vertical bar? In R, you can use both the single sign version or the double sign version, but the result of the logical operation you’re carrying out can be different. The biggest difference occurs when you use the two types of operations on vectors."
},
{
"code": null,
"e": 8177,
"s": 8132,
"text": "c(TRUE, TRUE, FALSE) & c(TRUE, FALSE, FALSE)"
},
{
"code": null,
"e": 8243,
"s": 8177,
"text": "As we’ve seen before, the above expression evaluates to a vector:"
},
{
"code": null,
"e": 8260,
"s": 8243,
"text": "TRUE FALSE FALSE"
},
{
"code": null,
"e": 8317,
"s": 8260,
"text": "However, if we use double ampersand, we simply get TRUE."
},
{
"code": null,
"e": 8363,
"s": 8317,
"text": "c(TRUE, TRUE, FALSE) && c(TRUE, FALSE, FALSE)"
},
{
"code": null,
"e": 8542,
"s": 8363,
"text": "This is because the double ampersand operation only examines the first element of each vector. In this case, the first elements are TRUE and TRUE, so the expression returns TRUE."
},
{
"code": null,
"e": 8756,
"s": 8542,
"text": "You can see similar things happening with the OR operator. The single sign version | returns and entire vector. The double sign version || returns the result of the OR operator on the first element of each vector."
},
{
"code": null,
"e": 8868,
"s": 8756,
"text": "So pay attention when doing logical operations on vectors. You will likely want to use the single sign version."
}
] |
C++ program for Finite Automata algorithm for Pattern Searching
|
In this article, we will be discussing a program to execute the Finite Automata algorithm for pattern searching.
We are provided with a text[0...n-1] and a pattern[0...m-1]. We have to find all the occurrences of the pattern[] in the text[].
For this we would preprocess the text[] and build a 2-d array to represent it. After that we just have to traverse between the elements of the text[] and the different states of the automata.
Live Demo
#include<stdio.h>
#include<string.h>
#define total_chars 256
int calc_nextstate(char *pat, int M, int state, int x) {
if (state < M && x == pat[state])
return state+1;
int ns, i;
for (ns = state; ns > 0; ns--) {
if (pat[ns-1] == x) {
for (i = 0; i < ns-1; i++)
if (pat[i] != pat[state-ns+1+i])
break;
if (i == ns-1)
return ns;
}
}
return 0;
}
//builds Finite Automata
void calc_TF(char *pat, int M, int TF[][total_chars]) {
int state, x;
for (state = 0; state <= M; ++state)
for (x = 0; x < total_chars; ++x)
TF[state][x] = calc_nextstate(pat, M, state, x);
}
//prints all occurrences of pattern in text
void calc_occur(char *pat, char *txt) {
int M = strlen(pat);
int N = strlen(txt);
int TF[M+1][total_chars];
calc_TF(pat, M, TF);
int i, state=0;
for (i = 0; i < N; i++){
state = TF[state][txt[i]];
if (state == M)
printf ("\n Given pattern is found at the index%d",i-M+1);
}
}
int main() {
char *txt = "AABCDAABBDCAABADAABDABAABA";
char *pat = "AABA";
calc_occur(pat, txt);
return 0;
}
Given pattern is found at the index 11
Given pattern is found at the index 22
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "In this article, we will be discussing a program to execute the Finite Automata algorithm for pattern searching."
},
{
"code": null,
"e": 1304,
"s": 1175,
"text": "We are provided with a text[0...n-1] and a pattern[0...m-1]. We have to find all the occurrences of the pattern[] in the text[]."
},
{
"code": null,
"e": 1496,
"s": 1304,
"text": "For this we would preprocess the text[] and build a 2-d array to represent it. After that we just have to traverse between the elements of the text[] and the different states of the automata."
},
{
"code": null,
"e": 1507,
"s": 1496,
"text": " Live Demo"
},
{
"code": null,
"e": 2661,
"s": 1507,
"text": "#include<stdio.h>\n#include<string.h>\n#define total_chars 256\nint calc_nextstate(char *pat, int M, int state, int x) {\n if (state < M && x == pat[state])\n return state+1;\n int ns, i;\n for (ns = state; ns > 0; ns--) {\n if (pat[ns-1] == x) {\n for (i = 0; i < ns-1; i++)\n if (pat[i] != pat[state-ns+1+i])\n break;\n if (i == ns-1)\n return ns;\n }\n }\n return 0;\n}\n//builds Finite Automata\nvoid calc_TF(char *pat, int M, int TF[][total_chars]) {\n int state, x;\n for (state = 0; state <= M; ++state)\n for (x = 0; x < total_chars; ++x)\n TF[state][x] = calc_nextstate(pat, M, state, x);\n}\n//prints all occurrences of pattern in text\nvoid calc_occur(char *pat, char *txt) {\n int M = strlen(pat);\n int N = strlen(txt);\n int TF[M+1][total_chars];\n calc_TF(pat, M, TF);\n int i, state=0;\n for (i = 0; i < N; i++){\n state = TF[state][txt[i]];\n if (state == M)\n printf (\"\\n Given pattern is found at the index%d\",i-M+1);\n }\n}\nint main() {\n char *txt = \"AABCDAABBDCAABADAABDABAABA\";\n char *pat = \"AABA\";\n calc_occur(pat, txt);\n return 0;\n}"
},
{
"code": null,
"e": 2739,
"s": 2661,
"text": "Given pattern is found at the index 11\nGiven pattern is found at the index 22"
}
] |
How to print text from a list of all web elements with same class name in Selenium?
|
We can get the text from a list of all web elements with the same class name in Selenium webdriver. We can use any of the locators like the class name with method By.className, xpath with method By.xpath, or css with method By.cssSelector.
Let us verify a xpath expression //h2[@class='store-name'] which represents multiple elements that have the same class name as store-name. If we validate this in Console with the expression - $x("//h2[@class='store-name']"), it yields all the matching elements as shown below:
Also, since we need to obtain multiple elements, we have to use the findElements method which returns a list. We shall iterate through this list and obtain the text of the elements with getText method.
List<WebElement> m =
driver.findElements(By.xpath("//h2[@class='store-name']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ElementsSameclsname{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.justdial.com/Bangalore/Bakeries");
// identify elements list with same class name
List<WebElement> m = driver.findElements(By.xpath("//h2[@class='store-name']"));
// iterate over list
for(int i = 0; i< m.size(); i++) {
//obtain text
String s = m.get(i).getText();
System.out.println("Text is: " + s);
}
driver.quit();
}
}
|
[
{
"code": null,
"e": 1302,
"s": 1062,
"text": "We can get the text from a list of all web elements with the same class name in Selenium webdriver. We can use any of the locators like the class name with method By.className, xpath with method By.xpath, or css with method By.cssSelector."
},
{
"code": null,
"e": 1579,
"s": 1302,
"text": "Let us verify a xpath expression //h2[@class='store-name'] which represents multiple elements that have the same class name as store-name. If we validate this in Console with the expression - $x(\"//h2[@class='store-name']\"), it yields all the matching elements as shown below:"
},
{
"code": null,
"e": 1781,
"s": 1579,
"text": "Also, since we need to obtain multiple elements, we have to use the findElements method which returns a list. We shall iterate through this list and obtain the text of the elements with getText method."
},
{
"code": null,
"e": 1862,
"s": 1781,
"text": "List<WebElement> m =\ndriver.findElements(By.xpath(\"//h2[@class='store-name']\"));"
},
{
"code": null,
"e": 2839,
"s": 1862,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\npublic class ElementsSameclsname{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.justdial.com/Bangalore/Bakeries\");\n // identify elements list with same class name\n List<WebElement> m = driver.findElements(By.xpath(\"//h2[@class='store-name']\"));\n // iterate over list\n for(int i = 0; i< m.size(); i++) {\n //obtain text\n String s = m.get(i).getText();\n System.out.println(\"Text is: \" + s);\n }\n driver.quit();\n }\n}"
}
] |
BabylonJS - Physics Engine
|
Babylon.js has plugin system for Physics engine which helps to add interactions to the scene.It shows the collision and bouncing between 2 objects and makes it more like real life interaction.The demo will show the balls colliding with each other and moving around with the collision and later resting.We notice the same behavior with games like billiards,where the player hits the ball with the stick and the balls collide with the other balls and so on.Here, the Physics Engine tries to give a realistic view of balls colliding and bouncing when they hit the ground surface. The engine has classes and APIthat help in applying apply impulse, force, changing velocity, callback functions to be called whenever required and also when we need to perform certain actions if the meshes collide against other meshes.
There are 3 Physics plugins that can be used −
Cannon.js
Oimo.js
Energy.js
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>BabylonJs - Ball/Ground Demo</title>
<script type = "text/javascript" src="https://cdn.babylonjs.com/Oimo.js"></script>
<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 v3 = BABYLON.Vector3;
var createScene = function () {
// This creates a basic Babylon Scene object (non-mesh)
var scene = new BABYLON.Scene(engine);
var camera = new BABYLON.ArcRotateCamera("Camera", 0.86, 1.37, 250, BABYLON.Vector3.Zero(), scene);
camera.attachControl(canvas);
camera.maxZ = 5000;
camera.lowerRadiusLimit = 120;
camera.upperRadiusLimit = 430;
camera.lowerBetaLimit =0.75;
camera.upperBetaLimit =1.58 ;
new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 1, 0), scene);
var randomNumber = function (min, max) {
if (min == max) {
return (min);
}
var random = Math.random();
return ((random * (max - min)) + min);
};
var mat = new BABYLON.StandardMaterial("ground", scene);
var t = new BABYLON.Texture("images/gr1.jpg", scene);
t.uScale = t.vScale = 10;
mat.diffuseTexture = t;
mat.specularColor = BABYLON.Color3.Black();
var g = BABYLON.Mesh.CreateBox("ground", 200, scene);
g.position.y = -20;
g.position.x = 0
g.scaling.y = 0.01;
g.material = mat;
scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.OimoJSPlugin());
g.physicsImpostor = new BABYLON.PhysicsImpostor(g, BABYLON.PhysicsImpostor.BoxImpostor, {
mass: 0,
restitution: 0.9
}, scene);
var getPosition = function(y) {
return new v3(randomNumber(-100, 100), y, randomNumber(-100, 100));
};
var allspheres = [];
var y = 50;
var max = 50;
for (var index = 0; index < max; index++) {
var redSphere = BABYLON.Mesh.CreateSphere("s" + index, 32, 8, scene);
redSphere.position = getPosition(y);
redSphere.physicsImpostor = new BABYLON.PhysicsImpostor(redSphere, BABYLON.PhysicsImpostor.SphereImpostor,{
mass: 1, restitution:0.9
}, scene);
redSphere.physicsImpostor.applyImpulse(new BABYLON.Vector3(1, 2, -1), new BABYLON.Vector3(1, 2, 0));
var redMat = new BABYLON.StandardMaterial("ground", scene);
redMat.diffuseColor = new BABYLON.Color3(0.4, 0.4, 0.4);
redMat.specularColor = new BABYLON.Color3(0.4, 0.4, 0.4);
redMat.emissiveColor = BABYLON.Color3.Red();
redSphere.material = redMat;
// push all spheres in the allspheres variable
allspheres.push(redSphere);
y += 10; // increment height
}
scene.registerBeforeRender(function() {
allspheres.forEach(function(obj) {
// if the sphers falls down its updated again over here
// If object falls
if (obj.position.y < -100) {
obj.position = getPosition(200);
}
});
})
return scene;
};
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
</script>
</body>
</html>
The above line of code generates the following output −
In this demo, we have used image images/gr1.jpg. The images are stored in images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link.
scene.enablePhysics(new BABYLON.Vector3(0,-10,0), new BABYLON.OimoJSPlugin());
The above line enables the Physics plugin. You can use the plugin of your choice. We have used OimoJsplugin().
g.physicsImpostor = newBABYLON.PhysicsImpostor(g, BABYLON.PhysicsImpostor.BoxImpostor, {
mass: 0,
restitution: 0.9
}, scene);
For interaction, Physics engine uses impostor. When applied to impostor, the shape of the object cannot be changed. If changed, a new impostor will have to be created.
For the sphere, we will set the imposter and also added impulse to it for a bounce effect as shown −
redSphere.physicsImpostor = new BABYLON.PhysicsImpostor(
redSphere, BABYLON.PhysicsImpostor.SphereImpostor, {
mass: 1,
restitution:0.9
}, scene
);
redSphere.physicsImpostor.applyImpulse(
new BABYLON.Vector3(1, 2, -1),
new BABYLON.Vector3(1, 2, 0)
);
Consider the following parameters for Physics effects −
Here the object is on which you want to apply the interaction. For example, sphere, box, etc.
Type can be one of the following −
BABYLON.PhysicsImpostor.SphereImpostor;
BABYLON.PhysicsImpostor.BoxImpostor;
BABYLON.PhysicsImpostor.PlaneImpostor;
BABYLON.PhysicsImpostor.MeshImpostor;
BABYLON.PhysicsImpostor.CylinderImpostor;
BABYLON.PhysicsImpostor.ParticleImpostor;
BABYLON.PhysicsImpostor.HeightmapImpostor;
The only mandatory parameter is mass, which is the object's mass in kg. A 0 as a value will create a static impostor - good for floors.
This is the amount of force the body will "give back" when colliding. A low value will create no bounce and a value of 1 will be a very bouncy interaction.
scene.registerBeforeRender(function() {
allspheres.forEach(function(obj) {
// if the sphers falls down its updated again over here
// If object falls
if (obj.position.y < -100) {
obj.position = getPosition(200);
}
});
})
The above code brings back the fallen spheres on the ground. It keeps updating the ground for any fallen sphere. Try the above demo in the browser to see the Physics effect.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2996,
"s": 2183,
"text": "Babylon.js has plugin system for Physics engine which helps to add interactions to the scene.It shows the collision and bouncing between 2 objects and makes it more like real life interaction.The demo will show the balls colliding with each other and moving around with the collision and later resting.We notice the same behavior with games like billiards,where the player hits the ball with the stick and the balls collide with the other balls and so on.Here, the Physics Engine tries to give a realistic view of balls colliding and bouncing when they hit the ground surface. The engine has classes and APIthat help in applying apply impulse, force, changing velocity, callback functions to be called whenever required and also when we need to perform certain actions if the meshes collide against other meshes."
},
{
"code": null,
"e": 3043,
"s": 2996,
"text": "There are 3 Physics plugins that can be used −"
},
{
"code": null,
"e": 3053,
"s": 3043,
"text": "Cannon.js"
},
{
"code": null,
"e": 3061,
"s": 3053,
"text": "Oimo.js"
},
{
"code": null,
"e": 3071,
"s": 3061,
"text": "Energy.js"
},
{
"code": null,
"e": 7182,
"s": 3071,
"text": "<!doctype html>\n<html>\n <head>\n <meta charset = \"utf-8\">\n <title>BabylonJs - Ball/Ground Demo</title>\n <script type = \"text/javascript\" src=\"https://cdn.babylonjs.com/Oimo.js\"></script>\n <script src = \"babylon.js\"></script>\t\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 var v3 = BABYLON.Vector3;\n \n var createScene = function () {\t\n // This creates a basic Babylon Scene object (non-mesh)\n var scene = new BABYLON.Scene(engine);\n\n var camera = new BABYLON.ArcRotateCamera(\"Camera\", 0.86, 1.37, 250, BABYLON.Vector3.Zero(), scene);\n \n camera.attachControl(canvas);\n camera.maxZ = 5000;\n camera.lowerRadiusLimit = 120;\n camera.upperRadiusLimit = 430;\n camera.lowerBetaLimit =0.75;\n camera.upperBetaLimit =1.58 ;\n\n new BABYLON.HemisphericLight(\"hemi\", new BABYLON.Vector3(0, 1, 0), scene);\n\n var randomNumber = function (min, max) {\n if (min == max) {\n return (min);\n }\n var random = Math.random();\n return ((random * (max - min)) + min);\n };\n\n var mat = new BABYLON.StandardMaterial(\"ground\", scene);\n var t = new BABYLON.Texture(\"images/gr1.jpg\", scene);\n t.uScale = t.vScale = 10;\n mat.diffuseTexture = t;\n mat.specularColor = BABYLON.Color3.Black();\n \n var g = BABYLON.Mesh.CreateBox(\"ground\", 200, scene);\n \n g.position.y = -20;\n g.position.x = 0\n g.scaling.y = 0.01;\n g.material = mat;\t\n \n scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.OimoJSPlugin());\n \n g.physicsImpostor = new BABYLON.PhysicsImpostor(g, BABYLON.PhysicsImpostor.BoxImpostor, { \n mass: 0, \n restitution: 0.9 \n }, scene);\n \n var getPosition = function(y) {\n return new v3(randomNumber(-100, 100), y, randomNumber(-100, 100));\n };\n \n var allspheres = [];\n var y = 50;\n var max = 50;\n \n for (var index = 0; index < max; index++) {\n var redSphere = BABYLON.Mesh.CreateSphere(\"s\" + index, 32, 8, scene);\n redSphere.position = getPosition(y);\n redSphere.physicsImpostor = new BABYLON.PhysicsImpostor(redSphere, BABYLON.PhysicsImpostor.SphereImpostor,{\n mass: 1, restitution:0.9\n }, scene);\n \n redSphere.physicsImpostor.applyImpulse(new BABYLON.Vector3(1, 2, -1), new BABYLON.Vector3(1, 2, 0));\n \n var redMat = new BABYLON.StandardMaterial(\"ground\", scene);\n redMat.diffuseColor = new BABYLON.Color3(0.4, 0.4, 0.4);\n redMat.specularColor = new BABYLON.Color3(0.4, 0.4, 0.4);\n redMat.emissiveColor = BABYLON.Color3.Red();\n redSphere.material = redMat;\n \n // push all spheres in the allspheres variable\n allspheres.push(redSphere);\t\t\t\n y += 10; // increment height\n }\n scene.registerBeforeRender(function() {\n allspheres.forEach(function(obj) { \n // if the sphers falls down its updated again over here\n // If object falls\n if (obj.position.y < -100) {\n obj.position = getPosition(200);\t\t\t\t\n }\n });\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": 7238,
"s": 7182,
"text": "The above line of code generates the following output −"
},
{
"code": null,
"e": 7444,
"s": 7238,
"text": "In this demo, we have used image images/gr1.jpg. The images are stored in images/ folder locally and are also pasted below for reference. You can download any image of your choice and use in the demo link."
},
{
"code": null,
"e": 7524,
"s": 7444,
"text": "scene.enablePhysics(new BABYLON.Vector3(0,-10,0), new BABYLON.OimoJSPlugin());\n"
},
{
"code": null,
"e": 7635,
"s": 7524,
"text": "The above line enables the Physics plugin. You can use the plugin of your choice. We have used OimoJsplugin()."
},
{
"code": null,
"e": 7771,
"s": 7635,
"text": "g.physicsImpostor = newBABYLON.PhysicsImpostor(g, BABYLON.PhysicsImpostor.BoxImpostor, { \n mass: 0, \n restitution: 0.9 \n}, scene);\n"
},
{
"code": null,
"e": 7939,
"s": 7771,
"text": "For interaction, Physics engine uses impostor. When applied to impostor, the shape of the object cannot be changed. If changed, a new impostor will have to be created."
},
{
"code": null,
"e": 8040,
"s": 7939,
"text": "For the sphere, we will set the imposter and also added impulse to it for a bounce effect as shown −"
},
{
"code": null,
"e": 8319,
"s": 8040,
"text": "redSphere.physicsImpostor = new BABYLON.PhysicsImpostor(\n redSphere, BABYLON.PhysicsImpostor.SphereImpostor, { \n mass: 1, \n restitution:0.9\n }, scene\n);\n\nredSphere.physicsImpostor.applyImpulse(\n new BABYLON.Vector3(1, 2, -1), \n new BABYLON.Vector3(1, 2, 0)\n);\n"
},
{
"code": null,
"e": 8375,
"s": 8319,
"text": "Consider the following parameters for Physics effects −"
},
{
"code": null,
"e": 8469,
"s": 8375,
"text": "Here the object is on which you want to apply the interaction. For example, sphere, box, etc."
},
{
"code": null,
"e": 8504,
"s": 8469,
"text": "Type can be one of the following −"
},
{
"code": null,
"e": 8544,
"s": 8504,
"text": "BABYLON.PhysicsImpostor.SphereImpostor;"
},
{
"code": null,
"e": 8581,
"s": 8544,
"text": "BABYLON.PhysicsImpostor.BoxImpostor;"
},
{
"code": null,
"e": 8620,
"s": 8581,
"text": "BABYLON.PhysicsImpostor.PlaneImpostor;"
},
{
"code": null,
"e": 8658,
"s": 8620,
"text": "BABYLON.PhysicsImpostor.MeshImpostor;"
},
{
"code": null,
"e": 8700,
"s": 8658,
"text": "BABYLON.PhysicsImpostor.CylinderImpostor;"
},
{
"code": null,
"e": 8742,
"s": 8700,
"text": "BABYLON.PhysicsImpostor.ParticleImpostor;"
},
{
"code": null,
"e": 8785,
"s": 8742,
"text": "BABYLON.PhysicsImpostor.HeightmapImpostor;"
},
{
"code": null,
"e": 8921,
"s": 8785,
"text": "The only mandatory parameter is mass, which is the object's mass in kg. A 0 as a value will create a static impostor - good for floors."
},
{
"code": null,
"e": 9077,
"s": 8921,
"text": "This is the amount of force the body will \"give back\" when colliding. A low value will create no bounce and a value of 1 will be a very bouncy interaction."
},
{
"code": null,
"e": 9344,
"s": 9077,
"text": "scene.registerBeforeRender(function() {\n allspheres.forEach(function(obj) { \n // if the sphers falls down its updated again over here\n // If object falls\n if (obj.position.y < -100) {\n obj.position = getPosition(200);\n }\t\t\t\t\t\n });\n})\n"
},
{
"code": null,
"e": 9518,
"s": 9344,
"text": "The above code brings back the fallen spheres on the ground. It keeps updating the ground for any fallen sphere. Try the above demo in the browser to see the Physics effect."
},
{
"code": null,
"e": 9525,
"s": 9518,
"text": " Print"
},
{
"code": null,
"e": 9536,
"s": 9525,
"text": " Add Notes"
}
] |
Delete data from a collection in MongoDB using multiple conditions?
|
You can use remove() for this. Let us first create a collection with documents −
> db.deleteDataDemo.insertOne({_id:1,"Name":"Larry"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.deleteDataDemo.insertOne({_id:2,"Name":"Chris"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.deleteDataDemo.insertOne({_id:3,"Name":"Robert"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.deleteDataDemo.insertOne({_id:4,"Name":"David"});
{ "acknowledged" : true, "insertedId" : 4 }
> db.deleteDataDemo.insertOne({_id:5,"Name":"Carol"});
{ "acknowledged" : true, "insertedId" : 5 }
> db.deleteDataDemo.insertOne({_id:6,"Name":"Sam"});
{ "acknowledged" : true, "insertedId" : 6 }
Following is the query to display all documents from a collection with the help of find() method −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" }
{ "_id" : 2, "Name" : "Chris" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 4, "Name" : "David" }
{ "_id" : 5, "Name" : "Carol" }
{ "_id" : 6, "Name" : "Sam" }
Following is the query to delete data from a collection in MongoDB by using multiple conditions. Here we have used two conditions i.e. _id 4 and Name David −
> db.deleteDataDemo.remove({'_id':4,'Name':"David"});
WriteResult({ "nRemoved" : 1 })
Let us check all the documents once again −
> db.deleteDataDemo.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "Larry" }
{ "_id" : 2, "Name" : "Chris" }
{ "_id" : 3, "Name" : "Robert" }
{ "_id" : 5, "Name" : "Carol" }
{ "_id" : 6, "Name" : "Sam" }
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "You can use remove() for this. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1736,
"s": 1143,
"text": "> db.deleteDataDemo.insertOne({_id:1,\"Name\":\"Larry\"});\n{ \"acknowledged\" : true, \"insertedId\" : 1 }\n> db.deleteDataDemo.insertOne({_id:2,\"Name\":\"Chris\"});\n{ \"acknowledged\" : true, \"insertedId\" : 2 }\n> db.deleteDataDemo.insertOne({_id:3,\"Name\":\"Robert\"});\n{ \"acknowledged\" : true, \"insertedId\" : 3 }\n> db.deleteDataDemo.insertOne({_id:4,\"Name\":\"David\"});\n{ \"acknowledged\" : true, \"insertedId\" : 4 }\n> db.deleteDataDemo.insertOne({_id:5,\"Name\":\"Carol\"});\n{ \"acknowledged\" : true, \"insertedId\" : 5 }\n> db.deleteDataDemo.insertOne({_id:6,\"Name\":\"Sam\"});\n{ \"acknowledged\" : true, \"insertedId\" : 6 }"
},
{
"code": null,
"e": 1835,
"s": 1736,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1872,
"s": 1835,
"text": "> db.deleteDataDemo.find().pretty();"
},
{
"code": null,
"e": 1913,
"s": 1872,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2104,
"s": 1913,
"text": "{ \"_id\" : 1, \"Name\" : \"Larry\" }\n{ \"_id\" : 2, \"Name\" : \"Chris\" }\n{ \"_id\" : 3, \"Name\" : \"Robert\" }\n{ \"_id\" : 4, \"Name\" : \"David\" }\n{ \"_id\" : 5, \"Name\" : \"Carol\" }\n{ \"_id\" : 6, \"Name\" : \"Sam\" }"
},
{
"code": null,
"e": 2262,
"s": 2104,
"text": "Following is the query to delete data from a collection in MongoDB by using multiple conditions. Here we have used two conditions i.e. _id 4 and Name David −"
},
{
"code": null,
"e": 2348,
"s": 2262,
"text": "> db.deleteDataDemo.remove({'_id':4,'Name':\"David\"});\nWriteResult({ \"nRemoved\" : 1 })"
},
{
"code": null,
"e": 2392,
"s": 2348,
"text": "Let us check all the documents once again −"
},
{
"code": null,
"e": 2429,
"s": 2392,
"text": "> db.deleteDataDemo.find().pretty();"
},
{
"code": null,
"e": 2470,
"s": 2429,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2629,
"s": 2470,
"text": "{ \"_id\" : 1, \"Name\" : \"Larry\" }\n{ \"_id\" : 2, \"Name\" : \"Chris\" }\n{ \"_id\" : 3, \"Name\" : \"Robert\" }\n{ \"_id\" : 5, \"Name\" : \"Carol\" }\n{ \"_id\" : 6, \"Name\" : \"Sam\" }"
}
] |
TypeScript Accessor - GeeksforGeeks
|
17 Nov, 2021
In TypeScript, there are two supported methods getter and setter to access and set the class members. The greater method control over how a member is accessed on each object. Methods of the typescript accessor property:
getter: This method comes when you want to access any property of an object.
setter: This method comes when you want to change any property of an object.
getter: For extracting the value of a variable getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. Syntax:
get accessName() {
// getter, the code executed on getting obj.accessName
},
Example:
javascript
class MyClass { private _with:number = 5; private _height:number = 10; get square() { return this._with * this._height; }}console.log(new MyClass().square);
Output:
50
A getter can be public, protected, private. It is just artificial to make something behave like a property or a function. So, get square() and new MyClass().square is the same as square() and new MyClass().square().Setter: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by set keyword in an object literal.Syntax:
set accessName(value) {
// the code executed on setting
//obj.accessName = value, from setter
}
Example:
javascript
set fullname { const parts = value.split (''); this.partname = firstname[0]; this.partname = firstname[1];}person fullname = "Hitangshu Agarwal"console.log(person);
output:
firstname: "Hitangshu"
lastname: "Agarwal"
Below example illustrates the concept of getter and setter clearly:Example:
javascript
const company = { companyName = "GeeksforGeeks", companyTag = "Edutech", // Function that return the Full description // combined both comapnyName and companyTag get full_Desc () { return `${company.companyName} ${company.CompanyTag}` }, // It will return separately companyName and companyTag set full_Desc(value) { const parts = value.split (''); this.partname = companyName[0]; this.partname = CompanyTag[1]; }}; company.full_Desc = "GeeksforGeeks Edutech";console.log(company);
Output:
GeeksforGeeks Edutech
Point To Be Remember:
We achieved a proper control over, how a member is accessed on each object with the help of getter and setter.
TypeScript accessors require to set the compiler to output ECMAScript 5 or higher we should require typescript accessor. It does not support below ECMAScript 5.
Accessor with a get and no set property are automatically assumed to be read-only no need for manual work. This is helpful when we are generating a .d.ts file from our code.
nidhi_biet
simmytarika5
TypeScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
File uploading in React.js
|
[
{
"code": null,
"e": 25063,
"s": 25035,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25285,
"s": 25063,
"text": "In TypeScript, there are two supported methods getter and setter to access and set the class members. The greater method control over how a member is accessed on each object. Methods of the typescript accessor property: "
},
{
"code": null,
"e": 25362,
"s": 25285,
"text": "getter: This method comes when you want to access any property of an object."
},
{
"code": null,
"e": 25439,
"s": 25362,
"text": "setter: This method comes when you want to change any property of an object."
},
{
"code": null,
"e": 25601,
"s": 25439,
"text": "getter: For extracting the value of a variable getter accessor property is the conventional method. It is denoted by get keyword, in an object literal. Syntax: "
},
{
"code": null,
"e": 25690,
"s": 25601,
"text": "get accessName() { \n // getter, the code executed on getting obj.accessName \n }, "
},
{
"code": null,
"e": 25701,
"s": 25690,
"text": "Example: "
},
{
"code": null,
"e": 25712,
"s": 25701,
"text": "javascript"
},
{
"code": "class MyClass { private _with:number = 5; private _height:number = 10; get square() { return this._with * this._height; }}console.log(new MyClass().square);",
"e": 25888,
"s": 25712,
"text": null
},
{
"code": null,
"e": 25898,
"s": 25888,
"text": "Output: "
},
{
"code": null,
"e": 25901,
"s": 25898,
"text": "50"
},
{
"code": null,
"e": 26295,
"s": 25901,
"text": "A getter can be public, protected, private. It is just artificial to make something behave like a property or a function. So, get square() and new MyClass().square is the same as square() and new MyClass().square().Setter: For updating the value of a variable the setter accessor property is the conventional method which is used. They are denoted by set keyword in an object literal.Syntax: "
},
{
"code": null,
"e": 26408,
"s": 26295,
"text": "set accessName(value) { \n // the code executed on setting \n //obj.accessName = value, from setter \n } "
},
{
"code": null,
"e": 26419,
"s": 26408,
"text": "Example: "
},
{
"code": null,
"e": 26430,
"s": 26419,
"text": "javascript"
},
{
"code": "set fullname { const parts = value.split (''); this.partname = firstname[0]; this.partname = firstname[1];}person fullname = \"Hitangshu Agarwal\"console.log(person);",
"e": 26604,
"s": 26430,
"text": null
},
{
"code": null,
"e": 26614,
"s": 26604,
"text": "output: "
},
{
"code": null,
"e": 26657,
"s": 26614,
"text": "firstname: \"Hitangshu\"\nlastname: \"Agarwal\""
},
{
"code": null,
"e": 26735,
"s": 26657,
"text": "Below example illustrates the concept of getter and setter clearly:Example: "
},
{
"code": null,
"e": 26746,
"s": 26735,
"text": "javascript"
},
{
"code": "const company = { companyName = \"GeeksforGeeks\", companyTag = \"Edutech\", // Function that return the Full description // combined both comapnyName and companyTag get full_Desc () { return `${company.companyName} ${company.CompanyTag}` }, // It will return separately companyName and companyTag set full_Desc(value) { const parts = value.split (''); this.partname = companyName[0]; this.partname = CompanyTag[1]; }}; company.full_Desc = \"GeeksforGeeks Edutech\";console.log(company);",
"e": 27298,
"s": 26746,
"text": null
},
{
"code": null,
"e": 27308,
"s": 27298,
"text": "Output: "
},
{
"code": null,
"e": 27330,
"s": 27308,
"text": "GeeksforGeeks Edutech"
},
{
"code": null,
"e": 27354,
"s": 27330,
"text": "Point To Be Remember: "
},
{
"code": null,
"e": 27465,
"s": 27354,
"text": "We achieved a proper control over, how a member is accessed on each object with the help of getter and setter."
},
{
"code": null,
"e": 27626,
"s": 27465,
"text": "TypeScript accessors require to set the compiler to output ECMAScript 5 or higher we should require typescript accessor. It does not support below ECMAScript 5."
},
{
"code": null,
"e": 27800,
"s": 27626,
"text": "Accessor with a get and no set property are automatically assumed to be read-only no need for manual work. This is helpful when we are generating a .d.ts file from our code."
},
{
"code": null,
"e": 27813,
"s": 27802,
"text": "nidhi_biet"
},
{
"code": null,
"e": 27826,
"s": 27813,
"text": "simmytarika5"
},
{
"code": null,
"e": 27837,
"s": 27826,
"text": "TypeScript"
},
{
"code": null,
"e": 27854,
"s": 27837,
"text": "Web Technologies"
},
{
"code": null,
"e": 27952,
"s": 27854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27961,
"s": 27952,
"text": "Comments"
},
{
"code": null,
"e": 27974,
"s": 27961,
"text": "Old Comments"
},
{
"code": null,
"e": 28030,
"s": 27974,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28073,
"s": 28030,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28134,
"s": 28073,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28179,
"s": 28134,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28251,
"s": 28179,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28311,
"s": 28251,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28369,
"s": 28311,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 28402,
"s": 28369,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 28463,
"s": 28402,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python - Convert Nested Tuple to Custom Key Dictionary - GeeksforGeeks
|
10 Jul, 2020
Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple = ((1, ‘Gfg’, 2), (3, ‘best’, 4)), keys = [‘key’, ‘value’, ‘id’]Output : [{‘key’: 1, ‘value’: ‘Gfg’, ‘id’: 2}, {‘key’: 3, ‘value’: ‘best’, ‘id’: 4}]
Input : test_tuple = test_tuple = ((1, ‘Gfg’), (2, 3)), keys = [‘key’, ‘value’]Output : [{‘key’: 1, ‘value’: ‘Gfg’}, {‘key’: 2, ‘value’: 3}]
Method #1 : Using list comprehension + dictionary comprehensionThe combination of above functionalities can be used to solve this problem. In this, we perform the task of assigning keys using dictionary comprehension and iteration of all keys and constructing data using list comprehension.
# Python3 code to demonstrate working of # Convert Nested Tuple to Custom Key Dictionary# Using list comprehension + dictionary comprehension # initializing tupletest_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)) # printing original tupleprint("The original tuple : " + str(test_tuple)) # Convert Nested Tuple to Custom Key Dictionary# Using list comprehension + dictionary comprehensionres = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in test_tuple] # printing result print("The converted dictionary : " + str(res))
The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]
Method #2 : Using zip() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we assign index wise keys using list content and mapping using zip(). In this, flexibility of predefining/scaling keys is provided.
# Python3 code to demonstrate working of # Convert Nested Tuple to Custom Key Dictionary# Using zip() + list comprehension # initializing tupletest_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)) # printing original tupleprint("The original tuple : " + str(test_tuple)) # initializing Keys keys = ['key', 'value', 'id'] # Convert Nested Tuple to Custom Key Dictionary# Using zip() + list comprehensionres = [{key: val for key, val in zip(keys, sub)} for sub in test_tuple] # printing result print("The converted dictionary : " + str(res))
The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]
Python dictionary-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24309,
"s": 24281,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24680,
"s": 24309,
"text": "Sometimes, while working with Python records, we can have data that come without proper column names/identifiers, which can just be identified by their index, but we intend to assign them keys and render in form of dictionaries. This kind of problem can have application in domains such as web development. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24848,
"s": 24680,
"text": "Input : test_tuple = ((1, ‘Gfg’, 2), (3, ‘best’, 4)), keys = [‘key’, ‘value’, ‘id’]Output : [{‘key’: 1, ‘value’: ‘Gfg’, ‘id’: 2}, {‘key’: 3, ‘value’: ‘best’, ‘id’: 4}]"
},
{
"code": null,
"e": 24989,
"s": 24848,
"text": "Input : test_tuple = test_tuple = ((1, ‘Gfg’), (2, 3)), keys = [‘key’, ‘value’]Output : [{‘key’: 1, ‘value’: ‘Gfg’}, {‘key’: 2, ‘value’: 3}]"
},
{
"code": null,
"e": 25280,
"s": 24989,
"text": "Method #1 : Using list comprehension + dictionary comprehensionThe combination of above functionalities can be used to solve this problem. In this, we perform the task of assigning keys using dictionary comprehension and iteration of all keys and constructing data using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Convert Nested Tuple to Custom Key Dictionary# Using list comprehension + dictionary comprehension # initializing tupletest_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)) # printing original tupleprint(\"The original tuple : \" + str(test_tuple)) # Convert Nested Tuple to Custom Key Dictionary# Using list comprehension + dictionary comprehensionres = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in test_tuple] # printing result print(\"The converted dictionary : \" + str(res))",
"e": 25855,
"s": 25280,
"text": null
},
{
"code": null,
"e": 26064,
"s": 25855,
"text": "The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]"
},
{
"code": null,
"e": 26321,
"s": 26066,
"text": "Method #2 : Using zip() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we assign index wise keys using list content and mapping using zip(). In this, flexibility of predefining/scaling keys is provided."
},
{
"code": "# Python3 code to demonstrate working of # Convert Nested Tuple to Custom Key Dictionary# Using zip() + list comprehension # initializing tupletest_tuple = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)) # printing original tupleprint(\"The original tuple : \" + str(test_tuple)) # initializing Keys keys = ['key', 'value', 'id'] # Convert Nested Tuple to Custom Key Dictionary# Using zip() + list comprehensionres = [{key: val for key, val in zip(keys, sub)} for sub in test_tuple] # printing result print(\"The converted dictionary : \" + str(res))",
"e": 26898,
"s": 26321,
"text": null
},
{
"code": null,
"e": 27107,
"s": 26898,
"text": "The original tuple : ((4, ‘Gfg’, 10), (3, ‘is’, 8), (6, ‘Best’, 10))The converted dictionary : [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}]"
},
{
"code": null,
"e": 27134,
"s": 27107,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27156,
"s": 27134,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 27163,
"s": 27156,
"text": "Python"
},
{
"code": null,
"e": 27179,
"s": 27163,
"text": "Python Programs"
},
{
"code": null,
"e": 27277,
"s": 27179,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27286,
"s": 27277,
"text": "Comments"
},
{
"code": null,
"e": 27299,
"s": 27286,
"text": "Old Comments"
},
{
"code": null,
"e": 27317,
"s": 27299,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27352,
"s": 27317,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27374,
"s": 27352,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27406,
"s": 27374,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27436,
"s": 27406,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27479,
"s": 27436,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27501,
"s": 27479,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27540,
"s": 27501,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27578,
"s": 27540,
"text": "Python | Convert a list to dictionary"
}
] |
Minimum changes required to make two arrays identical - GeeksforGeeks
|
25 Aug, 2021
Given two arrays, and with n elements each. The task is to make these two arrays identical i:e, for each , we want to make . In a single operation, you can choose two integers x and y, and replace all the occurrences of x in both the arrays with y. Notice that regardless of the number of occurrences replaced, it will still be counted as a single operation. You have to output the minimum number of operations required.
Examples:
Input : 1 2 2
1 2 5
Output: 1
Here, (x, y) = (5, 2) hence ans = 1.
Input : 2 1 1 3 5
1 2 2 4 5
Output: 2
Here, (x, y) = (1, 2) and (3, 4) thus ans = 2.
Other pairs are also possible.
This problem can be solved with the help of Disjoint Set Union.We will check all elements of both the arrays i:e for each . If the elements belong to the same id then we skip it. Otherwise, we do a Union operation on both elements. Finally, the answer will be the sum of the sizes of all the different disjoint sets formed i:e . We subtract 1 because, initially, we take the size of each set to be 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum changes// required to make two arrays identical#include <bits/stdc++.h>using namespace std; #define N 100010 /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */int id[N], sz[N]; // Function to assign rootint Root(int idx){ int i = idx; while (i != id[i]) id[i] = id[id[i]], i = id[i]; return i;} // Function to find Unionvoid Union(int a, int b){ int i = Root(a), j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i, sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j, sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.int minChange(int n, int a[], int b[]){ // Sets as single elements for (int i = 0; i < N; i++) id[i] = i, sz[i] = 1; // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programint main(){ int a[] = { 2, 1, 1, 3, 5 }, b[] = { 1, 2, 2, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); cout << minChange(n, a, b); return 0;}
// Java program to find minimum changes// required to make two arrays identical class GFG{static int N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */static int[] id=new int[100010];static int[] sz=new int[100010]; // Function to assign rootstatic int Root(int idx){ int i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i;} // Function to find Unionstatic void Union(int a, int b){ int i = Root(a); int j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.static int minChange(int n, int a[], int b[]){ // Sets as single elements for (int i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programpublic static void main(String[] args){ int a[] = { 2, 1, 1, 3, 5 }, b[] = { 1, 2, 2, 4, 5 }; int n = a.length; System.out.println(minChange(n, a, b));}}// This code is contributed by mits
# Python 3 program to find minimum changes# required to make two arrays identical N = 100010 # 'id':stores parent of a node# 'sz':stores size of a DSU treeID = [0 for i in range(N)]sz = [0 for i in range(N)] # function to assign rootdef Root(idx): i = idx while i != ID[i]: ID[i], i = ID[ID[i]], ID[i] return i # Function to find Uniondef Union(a, b): i, j = Root(a), Root(b) if i != j: if sz[i] >= sz[j]: ID[j] = i sz[i] += sz[j] sz[j] = 0 else: ID[i] = j sz[j] += sz[i] sz[i] = 0 # function to find minimum changes# required to make both array equaldef minChange(n, a, b): # sets as single elements for i in range(N): ID[i] = i sz[i] = 1 # Combine items if they belong # to different sets for i in range(n): # true if both elements have # different root if Root(a[i]) != Root(b[i]): Union(a[i], b[i]) # find sum sizes of all sets formed ans = 0 for i in range(n): if ID[i] == i: ans += (sz[i] - 1) return ans # Driver Codea = [2, 1, 1, 3, 5]b = [1, 2, 2, 4, 5]n = len(a) print(minChange(n, a, b)) # This code is contributed# by Mohit kumar 29 (IIIT gwalior)
// C# program to find minimum changes// required to make two arrays identicalusing System; class GFG{static int N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */static int []id=new int[100010];static int []sz=new int[100010]; // Function to assign rootstatic int Root(int idx){ int i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i;} // Function to find Unionstatic void Union(int a, int b){ int i = Root(a); int j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.static int minChange(int n, int []a, int []b){ // Sets as single elements for (int i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programpublic static void Main(){ int []a = { 2, 1, 1, 3, 5 }; int []b = { 1, 2, 2, 4, 5 }; int n = a.Length; Console.WriteLine(minChange(n, a, b));}}// This code is contributed by anuj_67..
<?php// PHP program to find minimum changes// required to make two arrays identical$N = 100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */$id = array_fill(0, $N, NULL);$sz = array_fill(0, $N, NULL); // Function to assign rootfunction Root($idx){ global $id; $i = $idx; while ($i != $id[$i]) { $id[$i] = $id[$id[$i]]; $i = $id[$i]; } return $i;} // Function to find Unionfunction Union($a, $b){ global $sz, $id; $i = Root($a); $j = Root($b); if ($i != $j) { if ($sz[$i] >= $sz[$j]) { $id[$j] = $i; $sz[$i] += $sz[$j]; $sz[$j] = 0; } else { $id[$i] = $j; $sz[$j] += $sz[$i]; $sz[$i] = 0; } }} // function to find minimum changes// required to make both array equal.function minChange($n, &$a, &$b){ global $id, $sz, $N; // Sets as single elements for ($i = 0; $i < $N; $i++) { $id[$i] = $i; $sz[$i] = 1; } // Combine items if they belong to // different sets. for ($i = 0; $i < $n; ++$i) // true if both elements have // different roots if (Root($a[$i]) != Root($b[$i])) Union($a[$i], $b[$i]); // make root equal // Find sum sizes of all sets formed. $ans = 0; for ($i = 0; $i < $n; ++$i) if ($id[$i] == $i) $ans += ($sz[$i] - 1); return $ans;} // Driver Code$a = array(2, 1, 1, 3, 5);$b = array(1, 2, 2, 4, 5);$n = sizeof($a);echo minChange($n, $a, $b); // This code is contributed by ita_c?>
<script>// Javascript program to find minimum changes// required to make two arrays identical let N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */ let id=new Array(100010); let sz=new Array(100010); // Function to assign root function Root(idx) { let i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } // Function to find Union function Union(a,b) { let i = Root(a); let j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } } } // function to find minimum changes required // to make both array equal. function minChange(n,a,b) { // Sets as single elements for (let i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (let i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. let ans = 0; for (let i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans; } // Driver program let a=[2, 1, 1, 3, 5 ]; let b=[ 1, 2, 2, 4, 5 ]; let n = a.length; document.write(minChange(n, a, b)); // This code is contributed by rag2127</script>
2
Time Complexity: O(N + n) where N is the maximum possible value of an array item and n is the number of elements in the array.
Mithun Kumar
vt_m
mohit kumar 29
ukasp
rag2127
akshaysingh98088
sweetyty
union-find
Advanced Data Structure
Arrays
Competitive Programming
Arrays
union-find
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
Disjoint Set Data Structures
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
|
[
{
"code": null,
"e": 24810,
"s": 24782,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 25231,
"s": 24810,
"text": "Given two arrays, and with n elements each. The task is to make these two arrays identical i:e, for each , we want to make . In a single operation, you can choose two integers x and y, and replace all the occurrences of x in both the arrays with y. Notice that regardless of the number of occurrences replaced, it will still be counted as a single operation. You have to output the minimum number of operations required."
},
{
"code": null,
"e": 25242,
"s": 25231,
"text": "Examples: "
},
{
"code": null,
"e": 25442,
"s": 25242,
"text": "Input : 1 2 2\n 1 2 5\nOutput: 1\nHere, (x, y) = (5, 2) hence ans = 1.\n\nInput : 2 1 1 3 5\n 1 2 2 4 5\nOutput: 2\nHere, (x, y) = (1, 2) and (3, 4) thus ans = 2.\nOther pairs are also possible."
},
{
"code": null,
"e": 25844,
"s": 25442,
"text": "This problem can be solved with the help of Disjoint Set Union.We will check all elements of both the arrays i:e for each . If the elements belong to the same id then we skip it. Otherwise, we do a Union operation on both elements. Finally, the answer will be the sum of the sizes of all the different disjoint sets formed i:e . We subtract 1 because, initially, we take the size of each set to be 1. "
},
{
"code": null,
"e": 25896,
"s": 25844,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25900,
"s": 25896,
"text": "C++"
},
{
"code": null,
"e": 25905,
"s": 25900,
"text": "Java"
},
{
"code": null,
"e": 25913,
"s": 25905,
"text": "Python3"
},
{
"code": null,
"e": 25916,
"s": 25913,
"text": "C#"
},
{
"code": null,
"e": 25920,
"s": 25916,
"text": "PHP"
},
{
"code": null,
"e": 25931,
"s": 25920,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum changes// required to make two arrays identical#include <bits/stdc++.h>using namespace std; #define N 100010 /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */int id[N], sz[N]; // Function to assign rootint Root(int idx){ int i = idx; while (i != id[i]) id[i] = id[id[i]], i = id[i]; return i;} // Function to find Unionvoid Union(int a, int b){ int i = Root(a), j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i, sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j, sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.int minChange(int n, int a[], int b[]){ // Sets as single elements for (int i = 0; i < N; i++) id[i] = i, sz[i] = 1; // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programint main(){ int a[] = { 2, 1, 1, 3, 5 }, b[] = { 1, 2, 2, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); cout << minChange(n, a, b); return 0;}",
"e": 27349,
"s": 25931,
"text": null
},
{
"code": "// Java program to find minimum changes// required to make two arrays identical class GFG{static int N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */static int[] id=new int[100010];static int[] sz=new int[100010]; // Function to assign rootstatic int Root(int idx){ int i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i;} // Function to find Unionstatic void Union(int a, int b){ int i = Root(a); int j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.static int minChange(int n, int a[], int b[]){ // Sets as single elements for (int i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programpublic static void main(String[] args){ int a[] = { 2, 1, 1, 3, 5 }, b[] = { 1, 2, 2, 4, 5 }; int n = a.length; System.out.println(minChange(n, a, b));}}// This code is contributed by mits",
"e": 28947,
"s": 27349,
"text": null
},
{
"code": "# Python 3 program to find minimum changes# required to make two arrays identical N = 100010 # 'id':stores parent of a node# 'sz':stores size of a DSU treeID = [0 for i in range(N)]sz = [0 for i in range(N)] # function to assign rootdef Root(idx): i = idx while i != ID[i]: ID[i], i = ID[ID[i]], ID[i] return i # Function to find Uniondef Union(a, b): i, j = Root(a), Root(b) if i != j: if sz[i] >= sz[j]: ID[j] = i sz[i] += sz[j] sz[j] = 0 else: ID[i] = j sz[j] += sz[i] sz[i] = 0 # function to find minimum changes# required to make both array equaldef minChange(n, a, b): # sets as single elements for i in range(N): ID[i] = i sz[i] = 1 # Combine items if they belong # to different sets for i in range(n): # true if both elements have # different root if Root(a[i]) != Root(b[i]): Union(a[i], b[i]) # find sum sizes of all sets formed ans = 0 for i in range(n): if ID[i] == i: ans += (sz[i] - 1) return ans # Driver Codea = [2, 1, 1, 3, 5]b = [1, 2, 2, 4, 5]n = len(a) print(minChange(n, a, b)) # This code is contributed# by Mohit kumar 29 (IIIT gwalior)",
"e": 30242,
"s": 28947,
"text": null
},
{
"code": "// C# program to find minimum changes// required to make two arrays identicalusing System; class GFG{static int N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */static int []id=new int[100010];static int []sz=new int[100010]; // Function to assign rootstatic int Root(int idx){ int i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i;} // Function to find Unionstatic void Union(int a, int b){ int i = Root(a); int j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } }} // function to find minimum changes required// to make both array equal.static int minChange(int n, int []a, int []b){ // Sets as single elements for (int i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (int i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. int ans = 0; for (int i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans;} // Driver programpublic static void Main(){ int []a = { 2, 1, 1, 3, 5 }; int []b = { 1, 2, 2, 4, 5 }; int n = a.Length; Console.WriteLine(minChange(n, a, b));}}// This code is contributed by anuj_67..",
"e": 31849,
"s": 30242,
"text": null
},
{
"code": "<?php// PHP program to find minimum changes// required to make two arrays identical$N = 100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */$id = array_fill(0, $N, NULL);$sz = array_fill(0, $N, NULL); // Function to assign rootfunction Root($idx){ global $id; $i = $idx; while ($i != $id[$i]) { $id[$i] = $id[$id[$i]]; $i = $id[$i]; } return $i;} // Function to find Unionfunction Union($a, $b){ global $sz, $id; $i = Root($a); $j = Root($b); if ($i != $j) { if ($sz[$i] >= $sz[$j]) { $id[$j] = $i; $sz[$i] += $sz[$j]; $sz[$j] = 0; } else { $id[$i] = $j; $sz[$j] += $sz[$i]; $sz[$i] = 0; } }} // function to find minimum changes// required to make both array equal.function minChange($n, &$a, &$b){ global $id, $sz, $N; // Sets as single elements for ($i = 0; $i < $N; $i++) { $id[$i] = $i; $sz[$i] = 1; } // Combine items if they belong to // different sets. for ($i = 0; $i < $n; ++$i) // true if both elements have // different roots if (Root($a[$i]) != Root($b[$i])) Union($a[$i], $b[$i]); // make root equal // Find sum sizes of all sets formed. $ans = 0; for ($i = 0; $i < $n; ++$i) if ($id[$i] == $i) $ans += ($sz[$i] - 1); return $ans;} // Driver Code$a = array(2, 1, 1, 3, 5);$b = array(1, 2, 2, 4, 5);$n = sizeof($a);echo minChange($n, $a, $b); // This code is contributed by ita_c?>",
"e": 33436,
"s": 31849,
"text": null
},
{
"code": "<script>// Javascript program to find minimum changes// required to make two arrays identical let N=100010; /* 'id': stores parent of a node. 'sz': stores size of a DSU tree. */ let id=new Array(100010); let sz=new Array(100010); // Function to assign root function Root(idx) { let i = idx; while (i != id[i]) { id[i] = id[id[i]]; i = id[i]; } return i; } // Function to find Union function Union(a,b) { let i = Root(a); let j = Root(b); if (i != j) { if (sz[i] >= sz[j]) { id[j] = i; sz[i] += sz[j]; sz[j] = 0; } else { id[i] = j; sz[j] += sz[i]; sz[i] = 0; } } } // function to find minimum changes required // to make both array equal. function minChange(n,a,b) { // Sets as single elements for (let i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } // Combine items if they belong to different // sets. for (let i = 0; i < n; ++i) // true if both elements have different root if (Root(a[i]) != Root(b[i])) Union(a[i], b[i]); // make root equal // Find sum sizes of all sets formed. let ans = 0; for (let i = 0; i < n; ++i) if (id[i] == i) ans += (sz[i] - 1); return ans; } // Driver program let a=[2, 1, 1, 3, 5 ]; let b=[ 1, 2, 2, 4, 5 ]; let n = a.length; document.write(minChange(n, a, b)); // This code is contributed by rag2127</script>",
"e": 35148,
"s": 33436,
"text": null
},
{
"code": null,
"e": 35150,
"s": 35148,
"text": "2"
},
{
"code": null,
"e": 35280,
"s": 35152,
"text": "Time Complexity: O(N + n) where N is the maximum possible value of an array item and n is the number of elements in the array. "
},
{
"code": null,
"e": 35293,
"s": 35280,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 35298,
"s": 35293,
"text": "vt_m"
},
{
"code": null,
"e": 35313,
"s": 35298,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35319,
"s": 35313,
"text": "ukasp"
},
{
"code": null,
"e": 35327,
"s": 35319,
"text": "rag2127"
},
{
"code": null,
"e": 35344,
"s": 35327,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 35353,
"s": 35344,
"text": "sweetyty"
},
{
"code": null,
"e": 35364,
"s": 35353,
"text": "union-find"
},
{
"code": null,
"e": 35388,
"s": 35364,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 35395,
"s": 35388,
"text": "Arrays"
},
{
"code": null,
"e": 35419,
"s": 35395,
"text": "Competitive Programming"
},
{
"code": null,
"e": 35426,
"s": 35419,
"text": "Arrays"
},
{
"code": null,
"e": 35437,
"s": 35426,
"text": "union-find"
},
{
"code": null,
"e": 35535,
"s": 35437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35544,
"s": 35535,
"text": "Comments"
},
{
"code": null,
"e": 35557,
"s": 35544,
"text": "Old Comments"
},
{
"code": null,
"e": 35591,
"s": 35557,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 35631,
"s": 35591,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 35660,
"s": 35631,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 35688,
"s": 35660,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 35720,
"s": 35688,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 35735,
"s": 35720,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35751,
"s": 35735,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 35778,
"s": 35751,
"text": "Program for array rotation"
},
{
"code": null,
"e": 35826,
"s": 35778,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
The Doubly Linked List class in Javascript
|
Here is the complete implementation of the DoublyLinkedList Class −
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
insert(data, position = this.length) {
let node = new this.Node(data);
// List is currently empty
if (this.head === null) {
this.head = node;
this.tail = node;
this.length++;
return this.head;
}
// Insertion at head
if (position == 0) {
node.prev = null;
node.next = this.head;
this.head.prev = node;
this.head = node;
return this.head;
}
let iter = 1;
let currNode = this.head;
while (currNode.next != null && iter < position) {
currNode = currNode.next; iter++;
}
// Make new node point to next node in list
node.next = currNode.next;
// Make next node's previous point to new
node if (currNode.next != null) {
currNode.next.prev = node;
}
// Make our node point to previous node
node.prev = currNode;
// Make previous node's next point to new node
currNode.next = node;
// check if inserted element was at the tail, if yes then make tail point to it
if (this.tail.next != null) {
this.tail = this.tail.next;
}
this.length++;
return node;
}
remove(data, position = 0) {
if (this.length === 0) {
console.log("List is already empty");
return;
}
this.length--;
let currNode = this.head;
if (position <= 0) {
this.head = this.head.next;
this.head.prev = null;
} else if (position >= this.length - 1) {
this.tail = this.tail.prev;
this.tail.next = null;
} else {
let iter = 0;
while (iter < position) {
currNode = currNode.next;
iter++;
}
currNode.next = currNode.next.next;
currNode.next.prev = currNode;
}
return currNode;
}
display() {
let currNode = this.head;
while (currNode != null) {
console.log(currNode.data + " <-> ");
currNode = currNode.next;
}
}
}
DoublyLinkedList.prototype.Node = class {
constructor(data) {
this.data = data;
this.next = null;
this.prev = null;
}
};
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Here is the complete implementation of the DoublyLinkedList Class −"
},
{
"code": null,
"e": 3446,
"s": 1130,
"text": "class DoublyLinkedList {\n constructor() {\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n insert(data, position = this.length) {\n let node = new this.Node(data);\n // List is currently empty\n if (this.head === null) {\n this.head = node;\n this.tail = node;\n this.length++;\n return this.head;\n }\n // Insertion at head\n if (position == 0) {\n node.prev = null;\n node.next = this.head;\n this.head.prev = node;\n this.head = node;\n return this.head;\n }\n let iter = 1;\n let currNode = this.head;\n while (currNode.next != null && iter < position) {\n currNode = currNode.next; iter++;\n }\n // Make new node point to next node in list\n node.next = currNode.next;\n // Make next node's previous point to new\n node if (currNode.next != null) {\n currNode.next.prev = node;\n }\n // Make our node point to previous node\n node.prev = currNode;\n\n // Make previous node's next point to new node\n currNode.next = node;\n\n // check if inserted element was at the tail, if yes then make tail point to it\n if (this.tail.next != null) {\n this.tail = this.tail.next;\n }\n this.length++;\n return node;\n }\n remove(data, position = 0) {\n if (this.length === 0) {\n console.log(\"List is already empty\");\n return;\n }\n this.length--;\n let currNode = this.head;\n if (position <= 0) {\n this.head = this.head.next;\n this.head.prev = null;\n } else if (position >= this.length - 1) {\n this.tail = this.tail.prev;\n this.tail.next = null;\n } else {\n let iter = 0;\n while (iter < position) {\n currNode = currNode.next;\n iter++;\n }\n currNode.next = currNode.next.next;\n currNode.next.prev = currNode;\n }\n return currNode;\n }\n display() {\n let currNode = this.head;\n while (currNode != null) {\n console.log(currNode.data + \" <-> \");\n currNode = currNode.next;\n }\n }\n}\n\nDoublyLinkedList.prototype.Node = class {\n constructor(data) {\n this.data = data;\n this.next = null;\n this.prev = null;\n }\n};"
}
] |
Firebase - Twitter Authentication
|
In this chapter, we will explain how to use Twitter authentication.
You can create Twitter app on this link. Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2.
In your Firebase dashboard side menu, you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1.
Then you would need to copy the callback URL and paste it in your Twitter app. You can find the Callback URL of your Twitter app when you click on the Settings tab.
In this step, we will add two buttons inside the body tag of index.html.
<button onclick = "twitterSignin()">Twitter Signin</button>
<button onclick = "twitterSignout()">Twitter Signout</button>
Now we can create functions for Twitter authentication.
var provider = new firebase.auth.TwitterAuthProvider();
function twitterSignin() {
firebase.auth().signInWithPopup(provider)
.then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
console.log(token)
console.log(user)
}).catch(function(error) {
console.log(error.code)
console.log(error.message)
});
}
function twitterSignout() {
firebase.auth().signOut()
.then(function() {
console.log('Signout successful!')
}, function(error) {
console.log('Signout failed!')
});
}
When we start our app, we can sigin or signout by clicking the two buttons. The console will confirm that the authentication is successful.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2234,
"s": 2166,
"text": "In this chapter, we will explain how to use Twitter authentication."
},
{
"code": null,
"e": 2405,
"s": 2234,
"text": "You can create Twitter app on this link. Once your app is created click on Keys and Access Tokens where you can find API Key and API Secret. You will need this in step 2."
},
{
"code": null,
"e": 2584,
"s": 2405,
"text": "In your Firebase dashboard side menu, you need to click Auth. Then open SIGN-IN-METHOD tab. Click on Twitter to enable it. You need to add API Key and API Secret from the step 1."
},
{
"code": null,
"e": 2749,
"s": 2584,
"text": "Then you would need to copy the callback URL and paste it in your Twitter app. You can find the Callback URL of your Twitter app when you click on the Settings tab."
},
{
"code": null,
"e": 2822,
"s": 2749,
"text": "In this step, we will add two buttons inside the body tag of index.html."
},
{
"code": null,
"e": 2944,
"s": 2822,
"text": "<button onclick = \"twitterSignin()\">Twitter Signin</button>\n<button onclick = \"twitterSignout()\">Twitter Signout</button>"
},
{
"code": null,
"e": 3000,
"s": 2944,
"text": "Now we can create functions for Twitter authentication."
},
{
"code": null,
"e": 3589,
"s": 3000,
"text": "var provider = new firebase.auth.TwitterAuthProvider();\n\nfunction twitterSignin() {\n firebase.auth().signInWithPopup(provider)\n \n .then(function(result) {\n var token = result.credential.accessToken;\n var user = result.user;\n\t\t\n console.log(token)\n console.log(user)\n }).catch(function(error) {\n console.log(error.code)\n console.log(error.message)\n });\n}\n\nfunction twitterSignout() {\n firebase.auth().signOut()\n \n .then(function() {\n console.log('Signout successful!')\n }, function(error) {\n console.log('Signout failed!')\n });\n}"
},
{
"code": null,
"e": 3729,
"s": 3589,
"text": "When we start our app, we can sigin or signout by clicking the two buttons. The console will confirm that the authentication is successful."
},
{
"code": null,
"e": 3762,
"s": 3729,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3779,
"s": 3762,
"text": " University Code"
},
{
"code": null,
"e": 3814,
"s": 3779,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3825,
"s": 3814,
"text": " Appeteria"
},
{
"code": null,
"e": 3861,
"s": 3825,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 3872,
"s": 3861,
"text": " Appeteria"
},
{
"code": null,
"e": 3907,
"s": 3872,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3924,
"s": 3907,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 3959,
"s": 3924,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3974,
"s": 3959,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 4010,
"s": 3974,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 4025,
"s": 4010,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 4032,
"s": 4025,
"text": " Print"
},
{
"code": null,
"e": 4043,
"s": 4032,
"text": " Add Notes"
}
] |
Batch Script - PAUSE
|
This batch command prompts the user and waits for a line of input to be entered.
Pause
@echo off
pause
The command prompt will show the message “Press any key to continue....” to the user and wait for the user’s input.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2250,
"s": 2169,
"text": "This batch command prompts the user and waits for a line of input to be entered."
},
{
"code": null,
"e": 2257,
"s": 2250,
"text": "Pause\n"
},
{
"code": null,
"e": 2274,
"s": 2257,
"text": "@echo off \npause"
},
{
"code": null,
"e": 2390,
"s": 2274,
"text": "The command prompt will show the message “Press any key to continue....” to the user and wait for the user’s input."
},
{
"code": null,
"e": 2397,
"s": 2390,
"text": " Print"
},
{
"code": null,
"e": 2408,
"s": 2397,
"text": " Add Notes"
}
] |
BigInteger modPow() Method in Java - GeeksforGeeks
|
11 Aug, 2021
Prerequisite: BigInteger BasicsThe Java.math.BigInteger.modPow() method returns a BigInteger whose value is (thisexponent mod m ). If exponent == 1, the returned value is (this mod m) and if exponent < 0, the returned value is the modular multiplicative inverse of (this-exponent). The method throws an ArithmeticException if m <= 0.
Syntax:
public BigInteger modPow(BigInteger exponent, BigInteger m)
Parameters: The method accepts two parameters.
exponent: This parameter refers to the exponent.
m: This parameter refers to the modulus.
Return Value: The method returns a BigInteger object whose value is ( thisexponent mod m ).
Exceptions:
ArithmeticException: If (m <= 0) or the exponent is negative and this BigInteger is not relatively prime to m.
Examples:
Input: biginteger1 = 23895
exponent = 15
biginteger2 = 14189
Output: 344
Explanation:
result = biginteger1.modPow(exponent, biginteger2)
23895^15 % 14189 = 344
Input: biginteger1 = 6547890621
exponent = 4532415
biginteger2 = 76543278906
Output: 1039609179
Explanation:
6547890621^4532415 % 76543278906 = 1039609179
Below program illustrates the Java.math.BigInteger.modPow() method:
Java
// Code to illustrate modpow() method of BigIntegerimport java.math.*;import java.util.Scanner; public class GFG { public static void main(String[] args) { // Create 3 BigInteger objects BigInteger biginteger1, biginteger2, result; // Initializing all BigInteger Objects biginteger1 = new BigInteger("23895"); biginteger2 = new BigInteger("14189"); BigInteger exponent = new BigInteger("15"); // Perform modPow operation on the objects and exponent result = biginteger1.modPow(exponent, biginteger2); String expression = biginteger1 + "^" + exponent + " % " + biginteger2 + " = " + result; // Displaying the result System.out.println(expression); }}
23895^15 % 14189 = 344
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs()
anikaseth98
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
Stream In Java
|
[
{
"code": null,
"e": 24374,
"s": 24346,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 24709,
"s": 24374,
"text": "Prerequisite: BigInteger BasicsThe Java.math.BigInteger.modPow() method returns a BigInteger whose value is (thisexponent mod m ). If exponent == 1, the returned value is (this mod m) and if exponent < 0, the returned value is the modular multiplicative inverse of (this-exponent). The method throws an ArithmeticException if m <= 0. "
},
{
"code": null,
"e": 24719,
"s": 24709,
"text": "Syntax: "
},
{
"code": null,
"e": 24779,
"s": 24719,
"text": "public BigInteger modPow(BigInteger exponent, BigInteger m)"
},
{
"code": null,
"e": 24828,
"s": 24779,
"text": "Parameters: The method accepts two parameters. "
},
{
"code": null,
"e": 24877,
"s": 24828,
"text": "exponent: This parameter refers to the exponent."
},
{
"code": null,
"e": 24918,
"s": 24877,
"text": "m: This parameter refers to the modulus."
},
{
"code": null,
"e": 25011,
"s": 24918,
"text": "Return Value: The method returns a BigInteger object whose value is ( thisexponent mod m ). "
},
{
"code": null,
"e": 25025,
"s": 25011,
"text": "Exceptions: "
},
{
"code": null,
"e": 25136,
"s": 25025,
"text": "ArithmeticException: If (m <= 0) or the exponent is negative and this BigInteger is not relatively prime to m."
},
{
"code": null,
"e": 25147,
"s": 25136,
"text": "Examples: "
},
{
"code": null,
"e": 25526,
"s": 25147,
"text": "Input: biginteger1 = 23895 \n exponent = 15\n biginteger2 = 14189\nOutput: 344\nExplanation:\nresult = biginteger1.modPow(exponent, biginteger2)\n23895^15 % 14189 = 344\n\nInput: biginteger1 = 6547890621\n exponent = 4532415\n biginteger2 = 76543278906\nOutput: 1039609179\nExplanation:\n6547890621^4532415 % 76543278906 = 1039609179"
},
{
"code": null,
"e": 25596,
"s": 25526,
"text": "Below program illustrates the Java.math.BigInteger.modPow() method: "
},
{
"code": null,
"e": 25601,
"s": 25596,
"text": "Java"
},
{
"code": "// Code to illustrate modpow() method of BigIntegerimport java.math.*;import java.util.Scanner; public class GFG { public static void main(String[] args) { // Create 3 BigInteger objects BigInteger biginteger1, biginteger2, result; // Initializing all BigInteger Objects biginteger1 = new BigInteger(\"23895\"); biginteger2 = new BigInteger(\"14189\"); BigInteger exponent = new BigInteger(\"15\"); // Perform modPow operation on the objects and exponent result = biginteger1.modPow(exponent, biginteger2); String expression = biginteger1 + \"^\" + exponent + \" % \" + biginteger2 + \" = \" + result; // Displaying the result System.out.println(expression); }}",
"e": 26369,
"s": 25601,
"text": null
},
{
"code": null,
"e": 26392,
"s": 26369,
"text": "23895^15 % 14189 = 344"
},
{
"code": null,
"e": 26480,
"s": 26394,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs() "
},
{
"code": null,
"e": 26492,
"s": 26480,
"text": "anikaseth98"
},
{
"code": null,
"e": 26508,
"s": 26492,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 26523,
"s": 26508,
"text": "Java-Functions"
},
{
"code": null,
"e": 26533,
"s": 26523,
"text": "java-math"
},
{
"code": null,
"e": 26551,
"s": 26533,
"text": "Java-math-package"
},
{
"code": null,
"e": 26556,
"s": 26551,
"text": "Java"
},
{
"code": null,
"e": 26572,
"s": 26556,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 26577,
"s": 26572,
"text": "Java"
},
{
"code": null,
"e": 26675,
"s": 26577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26707,
"s": 26675,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26758,
"s": 26707,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26777,
"s": 26758,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26807,
"s": 26777,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26825,
"s": 26807,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26856,
"s": 26825,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26888,
"s": 26856,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26908,
"s": 26888,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26932,
"s": 26908,
"text": "Singleton Class in Java"
}
] |
Spring Setter-based Dependency Injection
|
Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection.
Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
public class TextEditor {
private SpellChecker spellChecker;
// a setter method to inject the dependency.
public void setSpellChecker(SpellChecker spellChecker) {
System.out.println("Inside setSpellChecker." );
this.spellChecker = spellChecker;
}
// a getter method to return spellChecker
public SpellChecker getSpellChecker() {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Here you need to check the naming convention of the setter methods. To set a variable spellChecker we are using setSpellChecker() method which is very similar to Java POJO classes. Let us create the content of another dependent class file SpellChecker.java −
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling() {
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml which has configuration for the setter-based injection −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
<property name = "spellChecker" ref = "spellChecker"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker"></bean>
</beans>
You should note the difference in Beans.xml file defined in the constructor-based injection and the setter-based injection. The only difference is inside the <bean> element where we have used <constructor-arg> tags for constructor-based injection and <property> tags for setter-based injection.
The second important point to note is that in case you are passing a reference to an object, you need to use ref attribute of <property> tag and if you are passing a value directly then you should use value attribute.
Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −
Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.
If you have many setter methods, then it is convenient to use p-namespace in the XML configuration file. Let us check the difference −
Let us consider the example of a standard XML configuration file with <property> tags −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "john-classic" class = "com.example.Person">
<property name = "name" value = "John Doe"/>
<property name = "spouse" ref = "jane"/>
</bean>
<bean name = "jane" class = "com.example.Person">
<property name = "name" value = "John Doe"/>
</bean>
</beans>
The above XML configuration can be re-written in a cleaner way using p-namespace as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:p = "http://www.springframework.org/schema/p"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "john-classic" class = "com.example.Person"
p:name = "John Doe"
p:spouse-ref = "jane"/>
</bean>
<bean name =" jane" class = "com.example.Person"
p:name = "John Doe"/>
</bean>
</beans>
Here, you should note the difference in specifying primitive values and object references with p-namespace. The -ref part indicates that this is not a straight value but rather a reference to another bean.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2482,
"s": 2292,
"text": "Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean."
},
{
"code": null,
"e": 2601,
"s": 2482,
"text": "The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection."
},
{
"code": null,
"e": 2706,
"s": 2601,
"text": "Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −"
},
{
"code": null,
"e": 2752,
"s": 2706,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 3246,
"s": 2752,
"text": "package com.tutorialspoint;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n\n // a setter method to inject the dependency.\n public void setSpellChecker(SpellChecker spellChecker) {\n System.out.println(\"Inside setSpellChecker.\" );\n this.spellChecker = spellChecker;\n }\n // a getter method to return spellChecker\n public SpellChecker getSpellChecker() {\n return spellChecker;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 3505,
"s": 3246,
"text": "Here you need to check the naming convention of the setter methods. To set a variable spellChecker we are using setSpellChecker() method which is very similar to Java POJO classes. Let us create the content of another dependent class file SpellChecker.java −"
},
{
"code": null,
"e": 3748,
"s": 3505,
"text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling() {\n System.out.println(\"Inside checkSpelling.\" );\n }\n}"
},
{
"code": null,
"e": 3800,
"s": 3748,
"text": "Following is the content of the MainApp.java file −"
},
{
"code": null,
"e": 4208,
"s": 3800,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n te.spellCheck();\n }\n}"
},
{
"code": null,
"e": 4311,
"s": 4208,
"text": "Following is the configuration file Beans.xml which has configuration for the setter-based injection −"
},
{
"code": null,
"e": 4933,
"s": 4311,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n <property name = \"spellChecker\" ref = \"spellChecker\"/>\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\"></bean>\n\n</beans>"
},
{
"code": null,
"e": 5228,
"s": 4933,
"text": "You should note the difference in Beans.xml file defined in the constructor-based injection and the setter-based injection. The only difference is inside the <bean> element where we have used <constructor-arg> tags for constructor-based injection and <property> tags for setter-based injection."
},
{
"code": null,
"e": 5446,
"s": 5228,
"text": "The second important point to note is that in case you are passing a reference to an object, you need to use ref attribute of <property> tag and if you are passing a value directly then you should use value attribute."
},
{
"code": null,
"e": 5627,
"s": 5446,
"text": "Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −"
},
{
"code": null,
"e": 5707,
"s": 5627,
"text": "Inside SpellChecker constructor.\nInside setSpellChecker.\nInside checkSpelling.\n"
},
{
"code": null,
"e": 5842,
"s": 5707,
"text": "If you have many setter methods, then it is convenient to use p-namespace in the XML configuration file. Let us check the difference −"
},
{
"code": null,
"e": 5930,
"s": 5842,
"text": "Let us consider the example of a standard XML configuration file with <property> tags −"
},
{
"code": null,
"e": 6528,
"s": 5930,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"john-classic\" class = \"com.example.Person\">\n <property name = \"name\" value = \"John Doe\"/>\n <property name = \"spouse\" ref = \"jane\"/>\n </bean>\n\n <bean name = \"jane\" class = \"com.example.Person\">\n <property name = \"name\" value = \"John Doe\"/>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 6622,
"s": 6528,
"text": "The above XML configuration can be re-written in a cleaner way using p-namespace as follows −"
},
{
"code": null,
"e": 7208,
"s": 6622,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:p = \"http://www.springframework.org/schema/p\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\n <bean id = \"john-classic\" class = \"com.example.Person\"\n p:name = \"John Doe\"\n p:spouse-ref = \"jane\"/>\n </bean>\n\n <bean name =\" jane\" class = \"com.example.Person\"\n p:name = \"John Doe\"/>\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 7414,
"s": 7208,
"text": "Here, you should note the difference in specifying primitive values and object references with p-namespace. The -ref part indicates that this is not a straight value but rather a reference to another bean."
},
{
"code": null,
"e": 7448,
"s": 7414,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7462,
"s": 7448,
"text": " Karthikeya T"
},
{
"code": null,
"e": 7495,
"s": 7462,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7510,
"s": 7495,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 7545,
"s": 7510,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7557,
"s": 7545,
"text": " Senol Atac"
},
{
"code": null,
"e": 7592,
"s": 7557,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7604,
"s": 7592,
"text": " Senol Atac"
},
{
"code": null,
"e": 7639,
"s": 7604,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7651,
"s": 7639,
"text": " Senol Atac"
},
{
"code": null,
"e": 7684,
"s": 7651,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7696,
"s": 7684,
"text": " Senol Atac"
},
{
"code": null,
"e": 7703,
"s": 7696,
"text": " Print"
},
{
"code": null,
"e": 7714,
"s": 7703,
"text": " Add Notes"
}
] |
Copy all files from one directory to another using Python - GeeksforGeeks
|
06 Sep, 2021
In this article, we will discuss how to copy all files from one directory to another using Python.
This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories.
The shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory. It is created during the copy operation execution.
Syntax: shutil.copytree(src, dst, copy_function = copy2)
Parameter:
src : source directory
dst : destination director
copy_function (optional): Default – copy2(). copy() method may also be used.
Returns :The newly created destination directory name
Extended support for the os package is also needed in Python to perform all the operations related to file manipulations effectively. It provides many functions to work with directories, and their corresponding files and folders contained.
os.listdir(dir), lists all the files in the specified directory, dir, and os.path.join(a, b) is used to create a path by joining sub-paths a followed by b respectively.
Directory in use:
Python3
import shutilimport os # path to source directorysrc_dir = 'fol1' # path to destination directorydest_dir = 'fol2' # getting all the files in the source directoryfiles = os.listdir(src_dir) shutil.copytree(src_dir, dest_dir)
Output:
The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method also preserving the file’s metadata.
Syntax:
shutil.copy2(src, dst)
Parameter:
src : source directory
dst : destination director
Returns: The destination directory path
In addition to this, the Pathlib module is also incorporated to work with filesystem paths concerned with different operating systems. The Path function in the Pathlib package is used to define concrete paths.
Note: In this method, the files are copied to an already existing folder.
Directory in use:
Python3
# importing required packagesfrom pathlib import Pathimport shutil # defining source and destination# pathssrc = 'source'trg = 'destination' files=os.listdir(src) # iterating over all the files in# the source directoryfor fname in files: # copying the files to the # destination directory shutil.copy2(os.path.join(src,fname), trg)
Output:
varshagumber28
adnanirshad158
Picked
Python directory-program
Python-shutil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24430,
"s": 24402,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 24529,
"s": 24430,
"text": "In this article, we will discuss how to copy all files from one directory to another using Python."
},
{
"code": null,
"e": 24759,
"s": 24529,
"text": "This can be done using the shutil module. This module can be used in Python to perform operations on files and folders in a directory. Shutil package facilitates the access, movement, and removal of the files between directories."
},
{
"code": null,
"e": 25058,
"s": 24759,
"text": "The shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the destination directory. It is used to recursively copy a file from one location to another. The destination should not be an existing directory. It is created during the copy operation execution. "
},
{
"code": null,
"e": 25115,
"s": 25058,
"text": "Syntax: shutil.copytree(src, dst, copy_function = copy2)"
},
{
"code": null,
"e": 25127,
"s": 25115,
"text": "Parameter: "
},
{
"code": null,
"e": 25150,
"s": 25127,
"text": "src : source directory"
},
{
"code": null,
"e": 25177,
"s": 25150,
"text": "dst : destination director"
},
{
"code": null,
"e": 25254,
"s": 25177,
"text": "copy_function (optional): Default – copy2(). copy() method may also be used."
},
{
"code": null,
"e": 25308,
"s": 25254,
"text": "Returns :The newly created destination directory name"
},
{
"code": null,
"e": 25549,
"s": 25308,
"text": "Extended support for the os package is also needed in Python to perform all the operations related to file manipulations effectively. It provides many functions to work with directories, and their corresponding files and folders contained. "
},
{
"code": null,
"e": 25719,
"s": 25549,
"text": "os.listdir(dir), lists all the files in the specified directory, dir, and os.path.join(a, b) is used to create a path by joining sub-paths a followed by b respectively. "
},
{
"code": null,
"e": 25738,
"s": 25719,
"text": "Directory in use: "
},
{
"code": null,
"e": 25746,
"s": 25738,
"text": "Python3"
},
{
"code": "import shutilimport os # path to source directorysrc_dir = 'fol1' # path to destination directorydest_dir = 'fol2' # getting all the files in the source directoryfiles = os.listdir(src_dir) shutil.copytree(src_dir, dest_dir)",
"e": 25971,
"s": 25746,
"text": null
},
{
"code": null,
"e": 25979,
"s": 25971,
"text": "Output:"
},
{
"code": null,
"e": 26180,
"s": 25979,
"text": "The copy2() method in Python is used to copy the content of the source file to the destination file or directory. This method is identical to shutil.copy() method also preserving the file’s metadata. "
},
{
"code": null,
"e": 26188,
"s": 26180,
"text": "Syntax:"
},
{
"code": null,
"e": 26211,
"s": 26188,
"text": "shutil.copy2(src, dst)"
},
{
"code": null,
"e": 26222,
"s": 26211,
"text": "Parameter:"
},
{
"code": null,
"e": 26245,
"s": 26222,
"text": "src : source directory"
},
{
"code": null,
"e": 26272,
"s": 26245,
"text": "dst : destination director"
},
{
"code": null,
"e": 26313,
"s": 26272,
"text": "Returns: The destination directory path "
},
{
"code": null,
"e": 26524,
"s": 26313,
"text": "In addition to this, the Pathlib module is also incorporated to work with filesystem paths concerned with different operating systems. The Path function in the Pathlib package is used to define concrete paths. "
},
{
"code": null,
"e": 26598,
"s": 26524,
"text": "Note: In this method, the files are copied to an already existing folder."
},
{
"code": null,
"e": 26617,
"s": 26598,
"text": "Directory in use: "
},
{
"code": null,
"e": 26625,
"s": 26617,
"text": "Python3"
},
{
"code": "# importing required packagesfrom pathlib import Pathimport shutil # defining source and destination# pathssrc = 'source'trg = 'destination' files=os.listdir(src) # iterating over all the files in# the source directoryfor fname in files: # copying the files to the # destination directory shutil.copy2(os.path.join(src,fname), trg)",
"e": 26971,
"s": 26625,
"text": null
},
{
"code": null,
"e": 26979,
"s": 26971,
"text": "Output:"
},
{
"code": null,
"e": 26994,
"s": 26979,
"text": "varshagumber28"
},
{
"code": null,
"e": 27009,
"s": 26994,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27016,
"s": 27009,
"text": "Picked"
},
{
"code": null,
"e": 27041,
"s": 27016,
"text": "Python directory-program"
},
{
"code": null,
"e": 27055,
"s": 27041,
"text": "Python-shutil"
},
{
"code": null,
"e": 27062,
"s": 27055,
"text": "Python"
},
{
"code": null,
"e": 27160,
"s": 27062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27178,
"s": 27160,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27213,
"s": 27178,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27235,
"s": 27213,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27267,
"s": 27235,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27297,
"s": 27267,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27339,
"s": 27297,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27365,
"s": 27339,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27408,
"s": 27365,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27445,
"s": 27408,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Python | os.utime() method - GeeksforGeeks
|
03 Oct, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.utime() method of os module in Python is used to set the access and modified time of the specified path.
Syntax: os.utime(path, times = None, *, [ns, ]dir_fd = None, follow_symlinks = True)
Parameter:path: A string or bytes object representing a valid file system path.times (optional): A 2-tuple of the form (atime, mtime) where each member is an integer or float value representing access time and modification time in seconds respectively.ns (optional): A 2-tuple of the form (atime_ns, mtime_ns) where each member is an integer or float value representing access time and modification time in nanoseconds respectively.dir_fd: A file descriptor referring to a directory. The default value of this parameter is None.follow_symlinks: A boolean value either True or False. If True method will follow symbolic link otherwise not.
Return Type: This method does not return any value
Code #1: Use of os.utime() method
# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint("Current access time:", os.stat(path).st_atime)print("Current modification time:", os.stat(path).st_mtime) # Access time in secondsatime = 200000000 # Modification time in secondsmtime = 100000000 # Set the access time and # modification time for the# above specified path# using os.utime() methodtup = (atime, mtime)os.utime(path, tup) print("\nAccess and modification time changed\n") # Print current access and modification timeprint("Current access time:", os.stat(path).st_atime)print("Current modification time:", os.stat(path).st_mtime) # Either we can specify times# or specify ns parameter.# It is an error to specify# tuples for both times and ns
Current access time (in seconds): 1568930018.710342
Current modification time (in seconds): 1568930018.610892
Access and modification time changed
Current access time (in seconds): 200000000.0
Current modification time (in seconds): 100000000.0
Code #2: If ns parameter is specified,
# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint("Current access time (in seconds):", os.stat(path).st_atime)print("Current modification time (in seconds):", os.stat(path).st_mtime) # Access time in nanosecondsatime_ns = 20000000012345 # Modification time in nanosecondsmtime_ns = 10000000012345 # Set the access time and # modification time in nanoseconds # for the above specified path# using os.utime() method# (ns is keyword only argument) tup = (atime_ns, mtime_ns)os.utime(path, ns = tup) print("\nAccess and modification time changed\n") # Print current access and modification timeprint("Current access time (in seconds):", os.stat(path).st_atime)print("Current modification time (in seconds):", os.stat(path).st_mtime) # Either we can specify times# or specify ns parameter.# It is an error to specify# tuples for both times and ns
Current access time (in seconds): 1568930018.710342
Current modification time (in seconds): 1568930018.610892
Access and modification time changed
Current access time (in seconds): 20000.000012345
Current modification time (in seconds): 10000.000012345
Code #3: If times parameter is None and ns parameter is unspecified
# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint("Current access time (in seconds):", os.stat(path).st_atime)print("Current modification time (in seconds):", os.stat(path).st_mtime) # Set the access time and # modification time in nanoseconds # for the above specified path# using os.utime() methodos.utime(path) print("\nAccess and modification time changed\n") # Print current access and modification timeprint("Current access time (in seconds):", os.stat(path).st_atime)print("Current modification time (in seconds):", os.stat(path).st_mtime) # If times is None and ns is unspecified,# then it will be equivalent to# specifying ns = (atime_ns, mtime_ns)# where member atime_ns and mtime_ns# are current time in nanoseconds
Current access time (in seconds): 20000.000012345
Current modification time (in seconds): 10000.000012345
Access and modification time changed
Current access time (in seconds): 1568930018.710342
Current modification time (in seconds): 1568930018.610892
Reference: https://docs.python.org/3/library/os.html#os.utime
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
|
[
{
"code": null,
"e": 23897,
"s": 23869,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 24116,
"s": 23897,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 24224,
"s": 24116,
"text": "os.utime() method of os module in Python is used to set the access and modified time of the specified path."
},
{
"code": null,
"e": 24309,
"s": 24224,
"text": "Syntax: os.utime(path, times = None, *, [ns, ]dir_fd = None, follow_symlinks = True)"
},
{
"code": null,
"e": 24948,
"s": 24309,
"text": "Parameter:path: A string or bytes object representing a valid file system path.times (optional): A 2-tuple of the form (atime, mtime) where each member is an integer or float value representing access time and modification time in seconds respectively.ns (optional): A 2-tuple of the form (atime_ns, mtime_ns) where each member is an integer or float value representing access time and modification time in nanoseconds respectively.dir_fd: A file descriptor referring to a directory. The default value of this parameter is None.follow_symlinks: A boolean value either True or False. If True method will follow symbolic link otherwise not."
},
{
"code": null,
"e": 24999,
"s": 24948,
"text": "Return Type: This method does not return any value"
},
{
"code": null,
"e": 25033,
"s": 24999,
"text": "Code #1: Use of os.utime() method"
},
{
"code": "# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint(\"Current access time:\", os.stat(path).st_atime)print(\"Current modification time:\", os.stat(path).st_mtime) # Access time in secondsatime = 200000000 # Modification time in secondsmtime = 100000000 # Set the access time and # modification time for the# above specified path# using os.utime() methodtup = (atime, mtime)os.utime(path, tup) print(\"\\nAccess and modification time changed\\n\") # Print current access and modification timeprint(\"Current access time:\", os.stat(path).st_atime)print(\"Current modification time:\", os.stat(path).st_mtime) # Either we can specify times# or specify ns parameter.# It is an error to specify# tuples for both times and ns",
"e": 25913,
"s": 25033,
"text": null
},
{
"code": null,
"e": 26161,
"s": 25913,
"text": "Current access time (in seconds): 1568930018.710342\nCurrent modification time (in seconds): 1568930018.610892\n\nAccess and modification time changed\n\nCurrent access time (in seconds): 200000000.0\nCurrent modification time (in seconds): 100000000.0\n"
},
{
"code": null,
"e": 26200,
"s": 26161,
"text": "Code #2: If ns parameter is specified,"
},
{
"code": "# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint(\"Current access time (in seconds):\", os.stat(path).st_atime)print(\"Current modification time (in seconds):\", os.stat(path).st_mtime) # Access time in nanosecondsatime_ns = 20000000012345 # Modification time in nanosecondsmtime_ns = 10000000012345 # Set the access time and # modification time in nanoseconds # for the above specified path# using os.utime() method# (ns is keyword only argument) tup = (atime_ns, mtime_ns)os.utime(path, ns = tup) print(\"\\nAccess and modification time changed\\n\") # Print current access and modification timeprint(\"Current access time (in seconds):\", os.stat(path).st_atime)print(\"Current modification time (in seconds):\", os.stat(path).st_mtime) # Either we can specify times# or specify ns parameter.# It is an error to specify# tuples for both times and ns",
"e": 27219,
"s": 26200,
"text": null
},
{
"code": null,
"e": 27475,
"s": 27219,
"text": "Current access time (in seconds): 1568930018.710342\nCurrent modification time (in seconds): 1568930018.610892\n\nAccess and modification time changed\n\nCurrent access time (in seconds): 20000.000012345\nCurrent modification time (in seconds): 10000.000012345\n"
},
{
"code": null,
"e": 27543,
"s": 27475,
"text": "Code #3: If times parameter is None and ns parameter is unspecified"
},
{
"code": "# Python program to explain os.utime() method # importing os module import os # Pathpath = '/home / ihritik / Documents / file.txt' # Print current access and modification time# of the above specified pathprint(\"Current access time (in seconds):\", os.stat(path).st_atime)print(\"Current modification time (in seconds):\", os.stat(path).st_mtime) # Set the access time and # modification time in nanoseconds # for the above specified path# using os.utime() methodos.utime(path) print(\"\\nAccess and modification time changed\\n\") # Print current access and modification timeprint(\"Current access time (in seconds):\", os.stat(path).st_atime)print(\"Current modification time (in seconds):\", os.stat(path).st_mtime) # If times is None and ns is unspecified,# then it will be equivalent to# specifying ns = (atime_ns, mtime_ns)# where member atime_ns and mtime_ns# are current time in nanoseconds ",
"e": 28448,
"s": 27543,
"text": null
},
{
"code": null,
"e": 28704,
"s": 28448,
"text": "Current access time (in seconds): 20000.000012345\nCurrent modification time (in seconds): 10000.000012345\n\nAccess and modification time changed\n\nCurrent access time (in seconds): 1568930018.710342\nCurrent modification time (in seconds): 1568930018.610892\n"
},
{
"code": null,
"e": 28766,
"s": 28704,
"text": "Reference: https://docs.python.org/3/library/os.html#os.utime"
},
{
"code": null,
"e": 28783,
"s": 28766,
"text": "python-os-module"
},
{
"code": null,
"e": 28798,
"s": 28783,
"text": "python-utility"
},
{
"code": null,
"e": 28805,
"s": 28798,
"text": "Python"
},
{
"code": null,
"e": 28903,
"s": 28805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28912,
"s": 28903,
"text": "Comments"
},
{
"code": null,
"e": 28925,
"s": 28912,
"text": "Old Comments"
},
{
"code": null,
"e": 28943,
"s": 28925,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28965,
"s": 28943,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28987,
"s": 28965,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29029,
"s": 28987,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29054,
"s": 29029,
"text": "sum() function in Python"
},
{
"code": null,
"e": 29084,
"s": 29054,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29116,
"s": 29084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29132,
"s": 29116,
"text": "Deque in Python"
},
{
"code": null,
"e": 29158,
"s": 29132,
"text": "Python String | replace()"
}
] |
Android: How to Upload an image on Firebase storage? - GeeksforGeeks
|
07 Dec, 2021
Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application.
This article explains how to build an Android application with the ability to select the image from the mobile gallery and upload images to Firebase Storage.
Here are the detailed steps:
Step 1. Create a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application.
Step 2. Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:implementation 'com.google.firebase:firebase-storage:19.1.0'
implementation 'com.google.firebase:firebase-storage:19.1.0'
Step 3. Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Two layouts: nesting linear layout inside relative layoutTwo buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloudAn image view in which image is shown chosen from the galleryHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <!--Linear Layout with horizontal orientation and other properties--> <LinearLayout android:id="@+id/layout_button" android:orientation="horizontal" android:layout_alignParentTop="true" android:weightSum="2" android:layout_width="match_parent" android:layout_height="wrap_content"> <!--Button for choosing image from gallery--> <Button android:id="@+id/btnChoose" android:text="Choose" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <!--Button for uploading image--> <Button android:id="@+id/btnUpload" android:text="Upload" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /></LinearLayout> <!--Image View for showing image chosen from gallery--> <ImageView android:id="@+id/imgView" android:layout_width="match_parent" android:layout_height="match_parent" /></RelativeLayout>
Two layouts: nesting linear layout inside relative layoutTwo buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloudAn image view in which image is shown chosen from the gallery
Two layouts: nesting linear layout inside relative layout
Two buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloud
one for selecting an image from gallery
other button is for uploading an image on firebase storage on the cloud
An image view in which image is shown chosen from the gallery
Here is complete code for activity_main.xml:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <!--Linear Layout with horizontal orientation and other properties--> <LinearLayout android:id="@+id/layout_button" android:orientation="horizontal" android:layout_alignParentTop="true" android:weightSum="2" android:layout_width="match_parent" android:layout_height="wrap_content"> <!--Button for choosing image from gallery--> <Button android:id="@+id/btnChoose" android:text="Choose" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> <!--Button for uploading image--> <Button android:id="@+id/btnUpload" android:text="Upload" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /></LinearLayout> <!--Image View for showing image chosen from gallery--> <ImageView android:id="@+id/imgView" android:layout_width="match_parent" android:layout_height="match_parent" /></RelativeLayout>
Step 4. Setting up MainActivity.java fileIn MainActivitySet listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction.When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery.startActivityForResult is used to receive the result, which is the selected image.To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons.Override the startActivityForResult method and write its implementation.Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there.MainActivity.javaMainActivity.javapackage com.geeksforgeeks.uploadimagetofirebase; import android.app.ProgressDialog;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.IOException;import java.util.UUID; public class MainActivity extends AppCompatActivity { // views for button private Button btnSelect, btnUpload; // view for image view private ImageView imageView; // Uri indicates, where the image will be picked from private Uri filePath; // request code private final int PICK_IMAGE_REQUEST = 22; // instance for firebase storage and StorageReference FirebaseStorage storage; StorageReference storageReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor("#0F9D58")); actionBar.setBackgroundDrawable(colorDrawable); // initialise views btnSelect = findViewById(R.id.btnChoose); btnUpload = findViewById(R.id.btnUpload); imageView = findViewById(R.id.imgView); // get the Firebase storage reference storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); // on pressing btnSelect SelectImage() is called btnSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectImage(); } }); // on pressing btnUpload uploadImage() is called btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadImage(); } }); } // Select Image method private void SelectImage() { // Defining Implicit Intent to mobile gallery Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult( Intent.createChooser( intent, "Select Image from here..."), PICK_IMAGE_REQUEST); } // Override onActivityResult method @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // checking request code and result code // if request code is PICK_IMAGE_REQUEST and // resultCode is RESULT_OK // then set image in the image view if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Get the Uri of data filePath = data.getData(); try { // Setting image on image view using Bitmap Bitmap bitmap = MediaStore .Images .Media .getBitmap( getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { // Log the exception e.printStackTrace(); } } } // UploadImage method private void uploadImage() { if (filePath != null) { // Code for showing progressDialog while uploading ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading..."); progressDialog.show(); // Defining the child of storageReference StorageReference ref = storageReference .child( "images/" + UUID.randomUUID().toString()); // adding listeners on upload // or failure of image ref.putFile(filePath) .addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess( UploadTask.TaskSnapshot taskSnapshot) { // Image uploaded successfully // Dismiss dialog progressDialog.dismiss(); Toast .makeText(MainActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT) .show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error, Image not uploaded progressDialog.dismiss(); Toast .makeText(MainActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } }) .addOnProgressListener( new OnProgressListener<UploadTask.TaskSnapshot>() { // Progress Listener for loading // percentage on the dialog box @Override public void onProgress( UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); progressDialog.setMessage( "Uploaded " + (int)progress + "%"); } }); } }}
Set listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction.
When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery.
startActivityForResult is used to receive the result, which is the selected image.
To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons.
Override the startActivityForResult method and write its implementation.
Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there.
MainActivity.java
package com.geeksforgeeks.uploadimagetofirebase; import android.app.ProgressDialog;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.IOException;import java.util.UUID; public class MainActivity extends AppCompatActivity { // views for button private Button btnSelect, btnUpload; // view for image view private ImageView imageView; // Uri indicates, where the image will be picked from private Uri filePath; // request code private final int PICK_IMAGE_REQUEST = 22; // instance for firebase storage and StorageReference FirebaseStorage storage; StorageReference storageReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor("#0F9D58")); actionBar.setBackgroundDrawable(colorDrawable); // initialise views btnSelect = findViewById(R.id.btnChoose); btnUpload = findViewById(R.id.btnUpload); imageView = findViewById(R.id.imgView); // get the Firebase storage reference storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); // on pressing btnSelect SelectImage() is called btnSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectImage(); } }); // on pressing btnUpload uploadImage() is called btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadImage(); } }); } // Select Image method private void SelectImage() { // Defining Implicit Intent to mobile gallery Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult( Intent.createChooser( intent, "Select Image from here..."), PICK_IMAGE_REQUEST); } // Override onActivityResult method @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // checking request code and result code // if request code is PICK_IMAGE_REQUEST and // resultCode is RESULT_OK // then set image in the image view if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Get the Uri of data filePath = data.getData(); try { // Setting image on image view using Bitmap Bitmap bitmap = MediaStore .Images .Media .getBitmap( getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { // Log the exception e.printStackTrace(); } } } // UploadImage method private void uploadImage() { if (filePath != null) { // Code for showing progressDialog while uploading ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle("Uploading..."); progressDialog.show(); // Defining the child of storageReference StorageReference ref = storageReference .child( "images/" + UUID.randomUUID().toString()); // adding listeners on upload // or failure of image ref.putFile(filePath) .addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess( UploadTask.TaskSnapshot taskSnapshot) { // Image uploaded successfully // Dismiss dialog progressDialog.dismiss(); Toast .makeText(MainActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT) .show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error, Image not uploaded progressDialog.dismiss(); Toast .makeText(MainActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT) .show(); } }) .addOnProgressListener( new OnProgressListener<UploadTask.TaskSnapshot>() { // Progress Listener for loading // percentage on the dialog box @Override public void onProgress( UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); progressDialog.setMessage( "Uploaded " + (int)progress + "%"); } }); } }}
Output:
Main ActivityMain Activity containing buttons for choosing and uploading image
Main Activity containing buttons for choosing and uploading image
Choose image from galleryMain Activity with image view having image chosen from gallery
Main Activity with image view having image chosen from gallery
The uploaded image on firebase console:registered usersWant a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes
arrow_drop_upSave
registered users
kalrap615
adnanirshad158
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Set in Java
Overriding in Java
Functional Interfaces in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 24905,
"s": 24877,
"text": "\n07 Dec, 2021"
},
{
"code": null,
"e": 25127,
"s": 24905,
"text": "Firebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides secure file uploads and downloads for Firebase application."
},
{
"code": null,
"e": 25285,
"s": 25127,
"text": "This article explains how to build an Android application with the ability to select the image from the mobile gallery and upload images to Firebase Storage."
},
{
"code": null,
"e": 25314,
"s": 25285,
"text": "Here are the detailed steps:"
},
{
"code": null,
"e": 25479,
"s": 25314,
"text": "Step 1. Create a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application."
},
{
"code": null,
"e": 25660,
"s": 25479,
"text": "Step 2. Add the firebase storage dependency in build.gradle (Module:app)file. Latest Dependency for firebase storage is:implementation 'com.google.firebase:firebase-storage:19.1.0'"
},
{
"code": null,
"e": 25721,
"s": 25660,
"text": "implementation 'com.google.firebase:firebase-storage:19.1.0'"
},
{
"code": null,
"e": 27448,
"s": 25721,
"text": "Step 3. Setting up the activity_main.xml layout fileThe activity_main.xml layout file consists of:Two layouts: nesting linear layout inside relative layoutTwo buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloudAn image view in which image is shown chosen from the galleryHere is complete code for activity_main.xml:activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"https://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <!--Linear Layout with horizontal orientation and other properties--> <LinearLayout android:id=\"@+id/layout_button\" android:orientation=\"horizontal\" android:layout_alignParentTop=\"true\" android:weightSum=\"2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!--Button for choosing image from gallery--> <Button android:id=\"@+id/btnChoose\" android:text=\"Choose\" android:layout_weight=\"1\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" /> <!--Button for uploading image--> <Button android:id=\"@+id/btnUpload\" android:text=\"Upload\" android:layout_weight=\"1\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" /></LinearLayout> <!--Image View for showing image chosen from gallery--> <ImageView android:id=\"@+id/imgView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /></RelativeLayout>"
},
{
"code": null,
"e": 27689,
"s": 27448,
"text": "Two layouts: nesting linear layout inside relative layoutTwo buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloudAn image view in which image is shown chosen from the gallery"
},
{
"code": null,
"e": 27747,
"s": 27689,
"text": "Two layouts: nesting linear layout inside relative layout"
},
{
"code": null,
"e": 27870,
"s": 27747,
"text": "Two buttons:one for selecting an image from galleryother button is for uploading an image on firebase storage on the cloud"
},
{
"code": null,
"e": 27910,
"s": 27870,
"text": "one for selecting an image from gallery"
},
{
"code": null,
"e": 27982,
"s": 27910,
"text": "other button is for uploading an image on firebase storage on the cloud"
},
{
"code": null,
"e": 28044,
"s": 27982,
"text": "An image view in which image is shown chosen from the gallery"
},
{
"code": null,
"e": 28089,
"s": 28044,
"text": "Here is complete code for activity_main.xml:"
},
{
"code": null,
"e": 28107,
"s": 28089,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"https://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <!--Linear Layout with horizontal orientation and other properties--> <LinearLayout android:id=\"@+id/layout_button\" android:orientation=\"horizontal\" android:layout_alignParentTop=\"true\" android:weightSum=\"2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <!--Button for choosing image from gallery--> <Button android:id=\"@+id/btnChoose\" android:text=\"Choose\" android:layout_weight=\"1\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" /> <!--Button for uploading image--> <Button android:id=\"@+id/btnUpload\" android:text=\"Upload\" android:layout_weight=\"1\" android:layout_width=\"0dp\" android:layout_height=\"wrap_content\" /></LinearLayout> <!--Image View for showing image chosen from gallery--> <ImageView android:id=\"@+id/imgView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /></RelativeLayout>",
"e": 29418,
"s": 28107,
"text": null
},
{
"code": null,
"e": 37642,
"s": 29418,
"text": "Step 4. Setting up MainActivity.java fileIn MainActivitySet listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction.When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery.startActivityForResult is used to receive the result, which is the selected image.To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons.Override the startActivityForResult method and write its implementation.Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there.MainActivity.javaMainActivity.javapackage com.geeksforgeeks.uploadimagetofirebase; import android.app.ProgressDialog;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.IOException;import java.util.UUID; public class MainActivity extends AppCompatActivity { // views for button private Button btnSelect, btnUpload; // view for image view private ImageView imageView; // Uri indicates, where the image will be picked from private Uri filePath; // request code private final int PICK_IMAGE_REQUEST = 22; // instance for firebase storage and StorageReference FirebaseStorage storage; StorageReference storageReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor(\"#0F9D58\")); actionBar.setBackgroundDrawable(colorDrawable); // initialise views btnSelect = findViewById(R.id.btnChoose); btnUpload = findViewById(R.id.btnUpload); imageView = findViewById(R.id.imgView); // get the Firebase storage reference storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); // on pressing btnSelect SelectImage() is called btnSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectImage(); } }); // on pressing btnUpload uploadImage() is called btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadImage(); } }); } // Select Image method private void SelectImage() { // Defining Implicit Intent to mobile gallery Intent intent = new Intent(); intent.setType(\"image/*\"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult( Intent.createChooser( intent, \"Select Image from here...\"), PICK_IMAGE_REQUEST); } // Override onActivityResult method @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // checking request code and result code // if request code is PICK_IMAGE_REQUEST and // resultCode is RESULT_OK // then set image in the image view if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Get the Uri of data filePath = data.getData(); try { // Setting image on image view using Bitmap Bitmap bitmap = MediaStore .Images .Media .getBitmap( getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { // Log the exception e.printStackTrace(); } } } // UploadImage method private void uploadImage() { if (filePath != null) { // Code for showing progressDialog while uploading ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle(\"Uploading...\"); progressDialog.show(); // Defining the child of storageReference StorageReference ref = storageReference .child( \"images/\" + UUID.randomUUID().toString()); // adding listeners on upload // or failure of image ref.putFile(filePath) .addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess( UploadTask.TaskSnapshot taskSnapshot) { // Image uploaded successfully // Dismiss dialog progressDialog.dismiss(); Toast .makeText(MainActivity.this, \"Image Uploaded!!\", Toast.LENGTH_SHORT) .show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error, Image not uploaded progressDialog.dismiss(); Toast .makeText(MainActivity.this, \"Failed \" + e.getMessage(), Toast.LENGTH_SHORT) .show(); } }) .addOnProgressListener( new OnProgressListener<UploadTask.TaskSnapshot>() { // Progress Listener for loading // percentage on the dialog box @Override public void onProgress( UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); progressDialog.setMessage( \"Uploaded \" + (int)progress + \"%\"); } }); } }}"
},
{
"code": null,
"e": 37921,
"s": 37642,
"text": "Set listeners on interaction of defined button views. On interaction, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase storage. setOnClickListener is used for that action on interaction."
},
{
"code": null,
"e": 38205,
"s": 37921,
"text": "When SelectImage method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to search through the device gallery to select the image from the gallery."
},
{
"code": null,
"e": 38288,
"s": 38205,
"text": "startActivityForResult is used to receive the result, which is the selected image."
},
{
"code": null,
"e": 38641,
"s": 38288,
"text": "To display this image, make use of a method called onActivityResult(). onActivityResult receives a request code, result code, and the data. Check in this method, if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, display the selected image in the ImageView below buttons."
},
{
"code": null,
"e": 38714,
"s": 38641,
"text": "Override the startActivityForResult method and write its implementation."
},
{
"code": null,
"e": 38973,
"s": 38714,
"text": "Also in uploadImage() method, Firebase storage reference is taken and putFile() function is used to upload the image to firebase storage with success and failure listeners. If an image is uploaded than success toast is there otherwise failure toast is there."
},
{
"code": null,
"e": 38991,
"s": 38973,
"text": "MainActivity.java"
},
{
"code": "package com.geeksforgeeks.uploadimagetofirebase; import android.app.ProgressDialog;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import java.io.IOException;import java.util.UUID; public class MainActivity extends AppCompatActivity { // views for button private Button btnSelect, btnUpload; // view for image view private ImageView imageView; // Uri indicates, where the image will be picked from private Uri filePath; // request code private final int PICK_IMAGE_REQUEST = 22; // instance for firebase storage and StorageReference FirebaseStorage storage; StorageReference storageReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar; actionBar = getSupportActionBar(); ColorDrawable colorDrawable = new ColorDrawable( Color.parseColor(\"#0F9D58\")); actionBar.setBackgroundDrawable(colorDrawable); // initialise views btnSelect = findViewById(R.id.btnChoose); btnUpload = findViewById(R.id.btnUpload); imageView = findViewById(R.id.imgView); // get the Firebase storage reference storage = FirebaseStorage.getInstance(); storageReference = storage.getReference(); // on pressing btnSelect SelectImage() is called btnSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SelectImage(); } }); // on pressing btnUpload uploadImage() is called btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadImage(); } }); } // Select Image method private void SelectImage() { // Defining Implicit Intent to mobile gallery Intent intent = new Intent(); intent.setType(\"image/*\"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult( Intent.createChooser( intent, \"Select Image from here...\"), PICK_IMAGE_REQUEST); } // Override onActivityResult method @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // checking request code and result code // if request code is PICK_IMAGE_REQUEST and // resultCode is RESULT_OK // then set image in the image view if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { // Get the Uri of data filePath = data.getData(); try { // Setting image on image view using Bitmap Bitmap bitmap = MediaStore .Images .Media .getBitmap( getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { // Log the exception e.printStackTrace(); } } } // UploadImage method private void uploadImage() { if (filePath != null) { // Code for showing progressDialog while uploading ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setTitle(\"Uploading...\"); progressDialog.show(); // Defining the child of storageReference StorageReference ref = storageReference .child( \"images/\" + UUID.randomUUID().toString()); // adding listeners on upload // or failure of image ref.putFile(filePath) .addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess( UploadTask.TaskSnapshot taskSnapshot) { // Image uploaded successfully // Dismiss dialog progressDialog.dismiss(); Toast .makeText(MainActivity.this, \"Image Uploaded!!\", Toast.LENGTH_SHORT) .show(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error, Image not uploaded progressDialog.dismiss(); Toast .makeText(MainActivity.this, \"Failed \" + e.getMessage(), Toast.LENGTH_SHORT) .show(); } }) .addOnProgressListener( new OnProgressListener<UploadTask.TaskSnapshot>() { // Progress Listener for loading // percentage on the dialog box @Override public void onProgress( UploadTask.TaskSnapshot taskSnapshot) { double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); progressDialog.setMessage( \"Uploaded \" + (int)progress + \"%\"); } }); } }}",
"e": 45800,
"s": 38991,
"text": null
},
{
"code": null,
"e": 45808,
"s": 45800,
"text": "Output:"
},
{
"code": null,
"e": 45887,
"s": 45808,
"text": "Main ActivityMain Activity containing buttons for choosing and uploading image"
},
{
"code": null,
"e": 45953,
"s": 45887,
"text": "Main Activity containing buttons for choosing and uploading image"
},
{
"code": null,
"e": 46041,
"s": 45953,
"text": "Choose image from galleryMain Activity with image view having image chosen from gallery"
},
{
"code": null,
"e": 46104,
"s": 46041,
"text": "Main Activity with image view having image chosen from gallery"
},
{
"code": null,
"e": 46395,
"s": 46104,
"text": "The uploaded image on firebase console:registered usersWant a more fast-paced & competitive environment to learn the fundamentals of Android?\nClick here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 46412,
"s": 46395,
"text": "registered users"
},
{
"code": null,
"e": 46422,
"s": 46412,
"text": "kalrap615"
},
{
"code": null,
"e": 46437,
"s": 46422,
"text": "adnanirshad158"
},
{
"code": null,
"e": 46445,
"s": 46437,
"text": "android"
},
{
"code": null,
"e": 46450,
"s": 46445,
"text": "Java"
},
{
"code": null,
"e": 46455,
"s": 46450,
"text": "Java"
},
{
"code": null,
"e": 46553,
"s": 46455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46562,
"s": 46553,
"text": "Comments"
},
{
"code": null,
"e": 46575,
"s": 46562,
"text": "Old Comments"
},
{
"code": null,
"e": 46594,
"s": 46575,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 46612,
"s": 46594,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 46632,
"s": 46612,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 46656,
"s": 46632,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 46675,
"s": 46656,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 46695,
"s": 46675,
"text": "Collections in Java"
},
{
"code": null,
"e": 46707,
"s": 46695,
"text": "Set in Java"
},
{
"code": null,
"e": 46726,
"s": 46707,
"text": "Overriding in Java"
},
{
"code": null,
"e": 46756,
"s": 46726,
"text": "Functional Interfaces in Java"
}
] |
How do you use a ‘for loop’ for accessing array elements in C#?
|
The ‘for loop’ executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The following is our for loop.
Live Demo
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100;
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
int a = n[2];
Console.WriteLine(a);
Console.ReadKey();
}
}
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
102
Now let’s say you need the third element. For that, use.
int a = n[1];
The above will give the third element i.e. 102.
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "The ‘for loop’ executes a sequence of statements multiple times and abbreviates the code that manages the loop variable."
},
{
"code": null,
"e": 1214,
"s": 1183,
"text": "The following is our for loop."
},
{
"code": null,
"e": 1225,
"s": 1214,
"text": " Live Demo"
},
{
"code": null,
"e": 1794,
"s": 1225,
"text": "using System;\nnamespace ArrayApplication {\n class MyArray {\n static void Main(string[] args) {\n int [] n = new int[10]; /* n is an array of 10 integers */\n int i,j;\n /* initialize elements of array n */\n for ( i = 0; i < 10; i++ ) {\n n[ i ] = i + 100;\n }\n /* output each array element's value */\n for (j = 0; j < 10; j++ ) {\n Console.WriteLine(\"Element[{0}] = {1}\", j, n[j]);\n }\n int a = n[2];\n Console.WriteLine(a);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 1968,
"s": 1794,
"text": "Element[0] = 100\nElement[1] = 101\nElement[2] = 102\nElement[3] = 103\nElement[4] = 104\nElement[5] = 105\nElement[6] = 106\nElement[7] = 107\nElement[8] = 108\nElement[9] = 109\n102"
},
{
"code": null,
"e": 2025,
"s": 1968,
"text": "Now let’s say you need the third element. For that, use."
},
{
"code": null,
"e": 2039,
"s": 2025,
"text": "int a = n[1];"
},
{
"code": null,
"e": 2087,
"s": 2039,
"text": "The above will give the third element i.e. 102."
}
] |
Process Dataset with 200 Million Rows using Vaex | by Satyam Kumar | Towards Data Science
|
Pandas is one of the most popular libraries used for data science case studies. It is one of the best tools for exploratory data analysis and data wrangling. Pandas works efficiently well with small or medium-size datasets which fit best into the memory. For out of core dataset or large dataset pandas is inefficient to perform operations. One needs to spend a lot of time performing exploratory data analysis for a large size dataset using a pandas data frame.
Here Vaex comes into rescue that has a similar API that of pandas and is very efficient to perform out of memory datasets.
Vaex is a high-performance Python library in replacement to pandas that uses expression system and memory mapping to allow developers to perform operations on out of memory or large-sized datasets on standard machines. It covers some of the pandas' API’s and is focused more on data exploration and visualization.
Vaex is not fully compatible with Pandas API, but most of the data wrangling and exploration functionality is also available with Vaex. Visualization of dataset features is done using histograms, density plots, and 3d volume rendering.
Vaex is very efficient compared to Pandas when compared to perform operations on a large-sized dataset. In the further article, we’ll see benchmark numbers for experiments for the wrangling of large-sized data with Vaex. Some of the key efficiency of Vaex are:
Capable to read about 1.2TB of data instantly on your machine.
Can easily handle and perform operations on over 1Billion rows on your laptop
Capable of speedup string processing 10–1000x compared to pandas.
Vaex can load a very large size dataset (almost 1.2TB) and has the capability to perform exploration and visualization on your machine. Instead of loading the entire data into memory, Vaex just memory maps the data and creates an expression system.
From Vaex Documentation:
Vaex uses memory mapping, zero memory copy policy, and lazy computations for best performance hence no memory is wasted. It actually refers to the same data every time you make any changes to the data frame, it just adds a new state to the expression.
I have generated an artificial dataset having 200 million rows and 4 columns (‘id’, ‘name’, ‘x’, ‘y’) with ‘timestamp’ as the index. The total size of the dataset is 12GB.
timestamp: index, 1s time frequency from [2014-09-01, 2020-12-31]id: intname: stringx: floaty: float
Some popular data explorations experiments are performed for 200 million rows dataset on a windows OS with 8GB of RAM:
Read Data
Data Shape
Data describe
Value Counts
Group by column and aggregation
10th percentile computation
Visualizing a column
Apply function
Adding a new column
Filter data frame
The experiment was designed in a way that follows best practices for each tool — this is using binary format HDF5 for Vaex. Need to convert the CSV file to HDF5 format so that Vaex can perform its best. Vaex required 33minutes to convert 2313 partitions of the CSV file to its HDF5 format.
Now to read the HDF5 data from disk:
df = vaex.open("200M_data_hdf5/analysis_*.hdf5")
Vaex requires 6 minutes to read the entire dataset.
To compute the number of rows in the dataset using Vaex requires no time (0 ns). The entire data has around 200 million rows.
To generate descriptive statistics including the central tendency, dispersion, and shape of a dataset’s distribution, excluding NaN values using .describe() function.
Vaex took around 15 minutes to compute the descriptive statistics of each column.
To compute the frequency distribution of the categorical column ‘name’ using the function .value_counts() in Vaex data frame.
Vaex took around 3.5 minutes to return with the frequency distribution of the ‘name’ column.
Similar to pandas API, Vaex also comes up with a function to compute grouping and aggregation. The below command groups the ‘name’ column and aggregates the mean of column ‘x’.
Vaex took around 2.5 minutes to compute the above grouping and aggregation command.
To compute grouping for the ‘id’ column and mean aggregation for two columns ‘x’ and ‘y’.
Vaex took around 11.5 minutes to compute the above grouping and aggregation command.
Vaex has percentile_approx function to compute an approximation of a given percentile.
Vaex took 46.8 secs to compute the 10th percentile of the ‘id’ column.
To plot a histogram of large-sized data is problematic as traditional tools for data analysis are not optimized to handle them.
Using plot1d function in Vaex to plot a histogram of numerical vector, it took 3.5mins to return with the plot.
Similar to Pandas API, Vaex has apply function to apply a function along an axis of the DataFrame. Function to return list vowels in name column:
Vaex took almost no time (132 ms), to process 200 million records of name column.
Vaex actually takes no time to add a column to the dataset, as it does not add the new column instantly, rather uses an expression system to generate just the expression of the new column.
To add a new column Vaex took nearly 251ms.
Similar to pandas API, Vaex has a similar concept of selection, to filter the data based on any given condition. Vaex does not instantly filter the data frame, instead generates an expression.
Vaex takes almost no time (273 ms), to apply the filter, and as observed from the above image, the shape of the data frame reduced from 200 million to 98 million.
In this article, we have generated 200 million records of time-series artificial data having 4 columns of the size of nearly 12GB. Using Pandas library it’s impossible to read the dataset and perform exploration and visualization on it.
Vaex data frame can easily read the data and perform the required exploration and visualization. The only requirement on the Vaex data frame, it works well with HDF5 data. So the CSV files need to convert to the required HDF5 format.
Also, most of the popular Pandas API is available in the Vaex library, hence it makes it the most useful library to work with a large-sized dataset.
[1] Vaex Documentation: https://vaex.readthedocs.io/en/latest/
Thank You for Reading
|
[
{
"code": null,
"e": 635,
"s": 172,
"text": "Pandas is one of the most popular libraries used for data science case studies. It is one of the best tools for exploratory data analysis and data wrangling. Pandas works efficiently well with small or medium-size datasets which fit best into the memory. For out of core dataset or large dataset pandas is inefficient to perform operations. One needs to spend a lot of time performing exploratory data analysis for a large size dataset using a pandas data frame."
},
{
"code": null,
"e": 758,
"s": 635,
"text": "Here Vaex comes into rescue that has a similar API that of pandas and is very efficient to perform out of memory datasets."
},
{
"code": null,
"e": 1072,
"s": 758,
"text": "Vaex is a high-performance Python library in replacement to pandas that uses expression system and memory mapping to allow developers to perform operations on out of memory or large-sized datasets on standard machines. It covers some of the pandas' API’s and is focused more on data exploration and visualization."
},
{
"code": null,
"e": 1308,
"s": 1072,
"text": "Vaex is not fully compatible with Pandas API, but most of the data wrangling and exploration functionality is also available with Vaex. Visualization of dataset features is done using histograms, density plots, and 3d volume rendering."
},
{
"code": null,
"e": 1569,
"s": 1308,
"text": "Vaex is very efficient compared to Pandas when compared to perform operations on a large-sized dataset. In the further article, we’ll see benchmark numbers for experiments for the wrangling of large-sized data with Vaex. Some of the key efficiency of Vaex are:"
},
{
"code": null,
"e": 1632,
"s": 1569,
"text": "Capable to read about 1.2TB of data instantly on your machine."
},
{
"code": null,
"e": 1710,
"s": 1632,
"text": "Can easily handle and perform operations on over 1Billion rows on your laptop"
},
{
"code": null,
"e": 1776,
"s": 1710,
"text": "Capable of speedup string processing 10–1000x compared to pandas."
},
{
"code": null,
"e": 2025,
"s": 1776,
"text": "Vaex can load a very large size dataset (almost 1.2TB) and has the capability to perform exploration and visualization on your machine. Instead of loading the entire data into memory, Vaex just memory maps the data and creates an expression system."
},
{
"code": null,
"e": 2050,
"s": 2025,
"text": "From Vaex Documentation:"
},
{
"code": null,
"e": 2302,
"s": 2050,
"text": "Vaex uses memory mapping, zero memory copy policy, and lazy computations for best performance hence no memory is wasted. It actually refers to the same data every time you make any changes to the data frame, it just adds a new state to the expression."
},
{
"code": null,
"e": 2474,
"s": 2302,
"text": "I have generated an artificial dataset having 200 million rows and 4 columns (‘id’, ‘name’, ‘x’, ‘y’) with ‘timestamp’ as the index. The total size of the dataset is 12GB."
},
{
"code": null,
"e": 2575,
"s": 2474,
"text": "timestamp: index, 1s time frequency from [2014-09-01, 2020-12-31]id: intname: stringx: floaty: float"
},
{
"code": null,
"e": 2694,
"s": 2575,
"text": "Some popular data explorations experiments are performed for 200 million rows dataset on a windows OS with 8GB of RAM:"
},
{
"code": null,
"e": 2704,
"s": 2694,
"text": "Read Data"
},
{
"code": null,
"e": 2715,
"s": 2704,
"text": "Data Shape"
},
{
"code": null,
"e": 2729,
"s": 2715,
"text": "Data describe"
},
{
"code": null,
"e": 2742,
"s": 2729,
"text": "Value Counts"
},
{
"code": null,
"e": 2774,
"s": 2742,
"text": "Group by column and aggregation"
},
{
"code": null,
"e": 2802,
"s": 2774,
"text": "10th percentile computation"
},
{
"code": null,
"e": 2823,
"s": 2802,
"text": "Visualizing a column"
},
{
"code": null,
"e": 2838,
"s": 2823,
"text": "Apply function"
},
{
"code": null,
"e": 2858,
"s": 2838,
"text": "Adding a new column"
},
{
"code": null,
"e": 2876,
"s": 2858,
"text": "Filter data frame"
},
{
"code": null,
"e": 3166,
"s": 2876,
"text": "The experiment was designed in a way that follows best practices for each tool — this is using binary format HDF5 for Vaex. Need to convert the CSV file to HDF5 format so that Vaex can perform its best. Vaex required 33minutes to convert 2313 partitions of the CSV file to its HDF5 format."
},
{
"code": null,
"e": 3203,
"s": 3166,
"text": "Now to read the HDF5 data from disk:"
},
{
"code": null,
"e": 3252,
"s": 3203,
"text": "df = vaex.open(\"200M_data_hdf5/analysis_*.hdf5\")"
},
{
"code": null,
"e": 3304,
"s": 3252,
"text": "Vaex requires 6 minutes to read the entire dataset."
},
{
"code": null,
"e": 3430,
"s": 3304,
"text": "To compute the number of rows in the dataset using Vaex requires no time (0 ns). The entire data has around 200 million rows."
},
{
"code": null,
"e": 3597,
"s": 3430,
"text": "To generate descriptive statistics including the central tendency, dispersion, and shape of a dataset’s distribution, excluding NaN values using .describe() function."
},
{
"code": null,
"e": 3679,
"s": 3597,
"text": "Vaex took around 15 minutes to compute the descriptive statistics of each column."
},
{
"code": null,
"e": 3805,
"s": 3679,
"text": "To compute the frequency distribution of the categorical column ‘name’ using the function .value_counts() in Vaex data frame."
},
{
"code": null,
"e": 3898,
"s": 3805,
"text": "Vaex took around 3.5 minutes to return with the frequency distribution of the ‘name’ column."
},
{
"code": null,
"e": 4075,
"s": 3898,
"text": "Similar to pandas API, Vaex also comes up with a function to compute grouping and aggregation. The below command groups the ‘name’ column and aggregates the mean of column ‘x’."
},
{
"code": null,
"e": 4159,
"s": 4075,
"text": "Vaex took around 2.5 minutes to compute the above grouping and aggregation command."
},
{
"code": null,
"e": 4249,
"s": 4159,
"text": "To compute grouping for the ‘id’ column and mean aggregation for two columns ‘x’ and ‘y’."
},
{
"code": null,
"e": 4334,
"s": 4249,
"text": "Vaex took around 11.5 minutes to compute the above grouping and aggregation command."
},
{
"code": null,
"e": 4421,
"s": 4334,
"text": "Vaex has percentile_approx function to compute an approximation of a given percentile."
},
{
"code": null,
"e": 4492,
"s": 4421,
"text": "Vaex took 46.8 secs to compute the 10th percentile of the ‘id’ column."
},
{
"code": null,
"e": 4620,
"s": 4492,
"text": "To plot a histogram of large-sized data is problematic as traditional tools for data analysis are not optimized to handle them."
},
{
"code": null,
"e": 4732,
"s": 4620,
"text": "Using plot1d function in Vaex to plot a histogram of numerical vector, it took 3.5mins to return with the plot."
},
{
"code": null,
"e": 4878,
"s": 4732,
"text": "Similar to Pandas API, Vaex has apply function to apply a function along an axis of the DataFrame. Function to return list vowels in name column:"
},
{
"code": null,
"e": 4960,
"s": 4878,
"text": "Vaex took almost no time (132 ms), to process 200 million records of name column."
},
{
"code": null,
"e": 5149,
"s": 4960,
"text": "Vaex actually takes no time to add a column to the dataset, as it does not add the new column instantly, rather uses an expression system to generate just the expression of the new column."
},
{
"code": null,
"e": 5193,
"s": 5149,
"text": "To add a new column Vaex took nearly 251ms."
},
{
"code": null,
"e": 5386,
"s": 5193,
"text": "Similar to pandas API, Vaex has a similar concept of selection, to filter the data based on any given condition. Vaex does not instantly filter the data frame, instead generates an expression."
},
{
"code": null,
"e": 5549,
"s": 5386,
"text": "Vaex takes almost no time (273 ms), to apply the filter, and as observed from the above image, the shape of the data frame reduced from 200 million to 98 million."
},
{
"code": null,
"e": 5786,
"s": 5549,
"text": "In this article, we have generated 200 million records of time-series artificial data having 4 columns of the size of nearly 12GB. Using Pandas library it’s impossible to read the dataset and perform exploration and visualization on it."
},
{
"code": null,
"e": 6020,
"s": 5786,
"text": "Vaex data frame can easily read the data and perform the required exploration and visualization. The only requirement on the Vaex data frame, it works well with HDF5 data. So the CSV files need to convert to the required HDF5 format."
},
{
"code": null,
"e": 6169,
"s": 6020,
"text": "Also, most of the popular Pandas API is available in the Vaex library, hence it makes it the most useful library to work with a large-sized dataset."
},
{
"code": null,
"e": 6232,
"s": 6169,
"text": "[1] Vaex Documentation: https://vaex.readthedocs.io/en/latest/"
}
] |
JqueryUI - Sortable
|
jQueryUI provides sortable() method to reorder elements in list or grid using the mouse. This method performs sortability action based upon an operation string passed as the first parameter.
The sortable () method can be used in two forms −
$(selector, context).sortable (options) Method
$(selector, context).sortable (options) Method
$(selector, context).sortable ("action", [params]) Method
$(selector, context).sortable ("action", [params]) Method
The sortable (options) method declares that an HTML element contains interchangeable elements. The options parameter is an object that specifies the behavior of the elements involved during reordering.
$(selector, context).sortable(options);
The following table lists the different options that can be used with this method −
This option specifies the element in which the new element created with options.helper will be inserted during the time of the move/drag. By default its value is parent.
Option - appendTo
This option specifies the element in which the new element created with options.helper will be inserted during the time of the move/drag. By default its value is parent.
This can be of type −
Selector − This indicates a selector specifying which element to append the helper to..
Selector − This indicates a selector specifying which element to append the helper to..
jQuery − This indicates a jQuery object containing the element to append the helper to.
jQuery − This indicates a jQuery object containing the element to append the helper to.
Element − An element in the Document Object Model (DOM) to append the helper to.
Element − An element in the Document Object Model (DOM) to append the helper to.
String − The string "parent" will cause the helper to be a sibling of the sortable item.
String − The string "parent" will cause the helper to be a sibling of the sortable item.
Syntax
$(".selector").sortable(
{ appendTo: document.body }
);
This option indicates an axis of movement ("x" is horizontal, "y" is vertical). By default its value is false.
Option - axis
This option indicates an axis of movement ("x" is horizontal, "y" is vertical). By default its value is false.
Syntax
$(".selector").sortable(
{ axis: "x" }
);
This option is used to prevent sorting of elements by clicking on any of the selector elements. By default its value is "input,textarea,button,select,option".
Option - cancel
This option is used to prevent sorting of elements by clicking on any of the selector elements. By default its value is "input,textarea,button,select,option".
Syntax
$(".selector").sortable(
{ cancel: "a,button" }
);
This option is a Selector that identifies another sortable element that can accept items from this sortable. This allows items from one list to be moved to other lists, a frequent and useful user interaction. If omitted, no other element is connected. This is a one-way relationship. By default its value is false.
Option - connectWith
This option is a Selector that identifies another sortable element that can accept items from this sortable. This allows items from one list to be moved to other lists, a frequent and useful user interaction. If omitted, no other element is connected. This is a one-way relationship. By default its value is false.
Syntax
$(".selector").sortable(
{ connectWith: "#identifier" }
);
This option indicates an element within which the displacement takes place. The element will be represented by a selector (only the first item in the list will be considered), a DOM element, or the string "parent" (parent element) or "window" (HTML page).
Option - containment
This option indicates an element within which the displacement takes place.
This can be of type −
Selector − This indicates a selector. The element will be represented by a selector (only the first item in the list will be considered)
Selector − This indicates a selector. The element will be represented by a selector (only the first item in the list will be considered)
Element − An DOM element to use as the container.
Element − An DOM element to use as the container.
String − The string identifying an element to use as the container. Possible values are parent (parent element), document or window (HTML page).
String − The string identifying an element to use as the container. Possible values are parent (parent element), document or window (HTML page).
Syntax
$(".selector").sortable(
{ containment: "parent" }
);
Specifies the cursor CSS property when the element moves. It represents the shape of the mouse pointer. By default its value is "auto".
Option - cursor
Specifies the cursor CSS property when the element moves. It represents the shape of the mouse pointer. By default its value is "auto". Possible values are −
"crosshair" (across)
"default" (an arrow)
"pointer" (hand)
"move" (two arrows cross)
"e-resize" (expand to the right)
"ne-resize" (expand up right)
"nw-resize" (expand up left)
"n-resize" (expand up)
"se-resize" (expand down right)
"sw-resize" (expand down left)
"s-resize" (expand down)
"auto" (default)
"w-resize" (expand left)
"text" (pointer to write text)
"wait" (hourglass)
"help" (help pointer)
Syntax
$(".selector").sortable(
{ cursor: "move" }
);
Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. By default its value is "false".
Option - cursorAt
Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. By default its value is "false".
Syntax
$(".selector").sortable(
{ cursorAt: { left: 5 } }
);
Delay, in milliseconds, after which the first movement of the mouse is taken into account. The displacement may begin after that time. By default its value is "0".
Option - delay
Delay, in milliseconds, after which the first movement of the mouse is taken into account. The displacement may begin after that time. By default its value is "0".
Syntax
$(".selector").sortable(
{ delay: 150 }
);
This option if set to true, disables the sortable functionality. By default its value is false.
Option - disabled
This option if set to true, disables the sortable functionality. By default its value is false.
Syntax
$(".selector").sortable(
{ disabled: true }
);
Number of pixels that the mouse must be moved before the sorting starts. If specified, sorting will not start until after mouse is dragged beyond distance. By default its value is "1".
Option - distance
Number of pixels that the mouse must be moved before the sorting starts. If specified, sorting will not start until after mouse is dragged beyond distance. By default its value is "1".
Syntax
$(".selector").sortable(
{ distance: 5 }
);
This option if set to false, then items from this sortable can't be dropped on an empty connect sortable. By default its value is true.
Option - dropOnEmpty
This option if set to false, then items from this sortable can't be dropped on an empty connect sortable. By default its value is true.
Syntax
$(".selector").sortable(
{ dropOnEmpty: false }
);
If this option if set to true forces the helper to have a size. By default its value is false.
Option - forceHelperSize
If this option if set to true forces the helper to have a size. By default its value is false.
Syntax
$(".selector").sortable(
{ forceHelperSize: true }
);
This option when set to true, takes into account the size of the placeholder when an item is moved. This option is only useful if options.placeholder is initialized. By default its value is false.
Option - forcePlaceholderSize
This option when set to true, takes into account the size of the placeholder when an item is moved. This option is only useful if options.placeholder is initialized. By default its value is false.
Syntax
$(".selector").sortable(
{ forcePlaceholderSize: true }
);
This option is an Array [x, y] indicating the number of pixels that the sorting element moves horizontally and vertically during displacement of the mouse. By default its value is false.
Option - grid
This option is an Array [x, y] indicating the number of pixels that the sorting element moves horizontally and vertically during displacement of the mouse. By default its value is false.
Syntax
$(".selector").sortable(
{ grid: [ 20, 10 ] }
);
If specified, restricts sort from starting unless the mousedown occurs on the specified element(s). By default its value is false.
Option - handle
If specified, restricts sort from starting unless the mousedown occurs on the specified element(s). By default its value is false.
Syntax
$(".selector").sortable(
{ handle: ".handle" }
);
Allows for a helper element to be used for dragging display. By default its value is original.
Option - helper
Allows for a helper element to be used for dragging display. By default its value is original. Possible values are −
String − If set to "clone", then the element will be cloned and the clone will be dragged.
String − If set to "clone", then the element will be cloned and the clone will be dragged.
Function − A function that will return a DOMElement to use while dragging.
Function − A function that will return a DOMElement to use while dragging.
Syntax
$(".selector").sortable(
{ helper: "clone" }
);
This option specifies which items inside the DOM element to be sorted. By default its value is > *.
Option - items
This option specifies which items inside the DOM element to be sorted. By default its value is > *
Syntax
$(".selector").sortable(
{ items: "> li" }
);
This option is used to define the opacity of the helper while sorting. By default its value is false.
Option - opacity
This option is used to define the opacity of the helper while sorting. By default its value is false.
Syntax
$(".selector").sortable(
{ opacity: 0.5 }
);
This option is used to class name that gets applied to the otherwise white space.By default its value is false.
Option - placeholder
Syntax
$(".selector").sortable(
{ addClasses: false }
);
This option decides whether the sortable items should revert to their new positions using a smooth animation. By default its value is false.
Option - revert
This option decides whether the sortable items should revert to their new positions using a smooth animation. By default its value is false.
Syntax
$(".selector").sortable(
{ revert: true }
);
This option is used to enable scrolling. If set to true the page scrolls when coming to an edge. By default its value is true.
Option - scroll
This option is used to enable scrolling. If set to true the page scrolls when coming to an edge. By default its value is true.
Syntax
$(".selector").sortable(
{ scroll: false }
);
This option indicates how many pixels the mouse must exit the visible area to cause scrolling. By default its value is 20. This option is used only with options.scroll set to true.
Option - scrollSensitivity
This option indicates how many pixels the mouse must exit the visible area to cause scrolling. By default its value is 20. This option is used only with options.scroll set to true.
Syntax
$(".selector").sortable(
{ scrollSensitivity: 10 }
);
This option indicates the scrolling speed of the display once the scrolling begins. By default its value is 20.
Option - scrollSpeed
This option indicates the scrolling speed of the display once the scrolling begins. By default its value is 20.
Syntax
$(".selector").sortable(
{ scrollSpeed: 40 }
);
This option is a String that specifies which mode to use for testing whether the item being moved is hovering over another item. By default its value is "intersect".
Option - tolerance
This option is a String that specifies which mode to use for testing whether the item being moved is hovering over another item. By default its value is "intersect".Possible values are −
intersect − The item overlaps the other item by at least 50%.
intersect − The item overlaps the other item by at least 50%.
pointer − The mouse pointer overlaps the other item.
pointer − The mouse pointer overlaps the other item.
Syntax
$(".selector").sortable(
{ tolerance: "pointer" }
);
This option represents z-index for element/helper while being sorted. By default its value is 1000.
Option - zIndex
This option represents Z-index for element/helper while being sorted. By default its value is 1000.
Syntax
$(".selector").sortable(
{ zIndex: 9999 }
);
The following section will show you a few working examples of drag functionality.
The following example demonstrates a simple example of sortable functionality, passing no parameters to the sortable() method.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-1 { list-style-type: none; margin: 0;
padding: 0; width: 25%; }
#sortable-1 li { margin: 0 3px 3px 3px; padding: 0.4em;
padding-left: 1.5em; font-size: 17px; height: 16px; }
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
</style>
<script>
$(function() {
$( "#sortable-1" ).sortable();
});
</script>
</head>
<body>
<ul id = "sortable-1">
<li class = "default">Product 1</li>
<li class = "default">Product 2</li>
<li class = "default">Product 3</li>
<li class = "default">Product 4</li>
<li class = "default">Product 5</li>
<li class = "default">Product 6</li>
<li class = "default">Product 7</li>
</ul>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
Product 1
Product 2
Product 3
Product 4
Product 5
Product 6
Product 7
Re-arrange the products above, use mouse to drag items.
The following example demonstrates the usage of three options (a) delay and (b) distance in the sort function of JqueryUI.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-2, #sortable-3 { list-style-type: none; margin: 0;
padding: 0; width: 25%; }
#sortable-2 li, #sortable-3 li { margin: 0 3px 3px 3px; padding: 0.4em;
padding-left: 1.5em; font-size: 17px; height: 16px; }
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
</style>
<script>
$(function() {
$( "#sortable-2" ).sortable({
delay:500
});
$( "#sortable-3" ).sortable({
distance:30
});
});
</script>
</head>
<body>
<h3>Delay by 500ms</h3>
<ul id = "sortable-2">
<li class = "default">Product 1</li>
<li class = "default">Product 2</li>
<li class = "default">Product 3</li>
<li class = "default">Product 4</li>
</ul>
<h3>Distance Delay by 30px</h3>
<ul id = "sortable-3">
<li class = "default">Product 1</li>
<li class = "default">Product 2</li>
<li class = "default">Product 3</li>
<li class = "default">Product 4</li>
</ul>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
Product 1
Product 2
Product 3
Product 4
Product 1
Product 2
Product 3
Product 4
Re-arrange the products above, use mouse to drag items. To prevent accidental sorting either by delay (time) or distance, we have set a number of milliseconds the element needs to be dragged before sorting starts with the delay option. We have also set a distance in pixels the element needs to be dragged before sorting starts with the distance option.
The following example demonstrates the usage of three option placeholder in the sort function of JqueryUI.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-4 { list-style-type: none; margin: 0;
padding: 0; width: 25%; }
#sortable-4 li { margin: 0 3px 3px 3px; padding: 0.4em;
padding-left: 1.5em; font-size: 17px; height: 16px; }
.highlight {
border: 1px solid red;
font-weight: bold;
font-size: 45px;
background-color: #333333;
}
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
</style>
<script>
$(function() {
$( "#sortable-4" ).sortable({
placeholder: "highlight"
});
});
</script>
</head>
<body>
<ul id = "sortable-4">
<li class = "default">Product 1</li>
<li class = "default">Product 2</li>
<li class = "default">Product 3</li>
<li class = "default">Product 4</li>
<li class = "default">Product 5</li>
<li class = "default">Product 6</li>
<li class = "default">Product 7</li>
</ul>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
Product 1
Product 2
Product 3
Product 4
Product 5
Product 6
Product 7
Try to drag items to rearrange them, while you're dragging items, the placeholder (we have used highlight class to style this space) will show up on an available place.
The following example demonstrates the usage of three options (a) connectWith and (b) dropOnEmpty in the sort function of JqueryUI.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-5, #sortable-6,#sortable-7 {
list-style-type: none; margin: 0; padding: 0;
width: 20%;float:left }
#sortable-5 li, #sortable-6 li,#sortable-7 li {
margin: 0 3px 3px 3px; padding: 0.4em;
padding-left: 1.5em; font-size: 17px; height: 16px; }
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
</style>
<script>
$(function() {
$( "#sortable-5, #sortable-6" ).sortable({
connectWith: "#sortable-5, #sortable-6"
});
$( "#sortable-7").sortable({
connectWith: "#sortable-5",
dropOnEmpty: false
});
});
</script>
</head>
<body>
<ul id = "sortable-5"><h3>List 1</h3>
<li class = "default">A</li>
<li class = "default">B</li>
<li class = "default">C</li>
<li class = "default">D</li>
</ul>
<ul id = "sortable-6"><h3>List 2</h3>
<li class = "default">a</li>
<li class = "default">b</li>
<li class = "default">c</li>
<li class = "default">d</li>
</ul>
<ul id = "sortable-7"><h3>List 3</h3>
<li class = "default">e</li>
<li class = "default">f</li>
<li class = "default">g</li>
<li class = "default">h</li>
</ul>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
A
B
C
D
a
b
c
d
e
f
g
h
Sort items from one List1 into another (List2) and vice versa, by passing a selector into the connectWith option. This is done by grouping all related lists with a CSS class, and then pass that class into the sortable function (i.e., connectWith: '#sortable-5, #sortable-6').
Try to drag the items under List 3 to the List 2 or List 1. As we have set dropOnEmpty option to false, it won't be possible to drop these items.
The sortable (action, params) method can perform an action on the sortable elements, such as to prevent displacement. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action.
$(selector, context).sortable ("action", [params]);
The following table lists the actions for this method −
This action cancels the current sort operation. This is most useful within handlers for the sort receive and sort stop events. This method does not accept any arguments.
Action - cancel()
Cancels the current sort operation. This is most useful within handlers for the sort receive and sort stop events. This method does not accept any arguments.
Syntax
$(".selector").sortable("cancel");
This action removes the sortability functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments.
Action - destroy()
This action removes the sortability functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments.
Syntax
$(".selector").sortable("destroy");
This action disables the sortability of any sortable elements in the wrapped set. The sortability of the elements isn’t removed and can be restored by calling the enable variant of this method. This method does not accept any arguments.
Action - disable()
This action disables the sortability of any sortable elements in the wrapped set. The sortability of the elements isn’t removed and can be restored by calling the enable variant of this method. This method does not accept any arguments.
Syntax
$(".selector").sortable("disable");
Re-enables sortability on any sortable elements in the wrapped set whose sortability has been disabled. Note that this method won’t add sortability to any non-sortable elements. This method does not accept any arguments.
Action - enable()
Re-enables sortability on any sortable elements in the wrapped set whose sortability has been disabled. Note that this method won’t add sortability to any non-sortable elements. This method does not accept any arguments.
Syntax
$(".selector").sortable("enable");
This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get.
Action - option( optionName )
This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get.
Syntax
var isDisabled = $( ".selector" ).sortable( "option", "disabled" );
Gets an object containing key/value pairs representing the current sortable options hash.. This method does not accept any arguments.
Action - option()
Gets an object containing key/value pairs representing the current sortable options hash.. This method does not accept any arguments.
Syntax
$(".selector").sortable("option");
This action sets the value of the sortable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option.
Action - option( optionName, value )
This action sets the value of the sortable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option.
Syntax
$(".selector").sortable("option", "disabled", true);
Sets one or more options for the sortable. Where options is a map of option-value pairs to set.
Action - option( options )
Sets one or more options for the sortable. Where options is a map of option-value pairs to set.
Syntax
$( ".selector" ).sortable( "option", { disabled: true } );
This action refreshes the list of items if necessary. This method does not accept any arguments. Calling this method will cause new items added to the sortable to be recognized.
Action - refresh()
This action refreshes the list of items if necessary. This method does not accept any arguments. Calling this method will cause new items added to the sortable to be recognized.
Syntax
$(".selector").sortable("refresh");
This method returns an array of the id values of the sortable elements in sorted order. This method takes Options as parameter, to customize the serialization or sorted order.
Action - toArray( options )
This method returns an array of the id values of the sortable elements in sorted order. This method takes Options as parameter, to customize the serialization or sorted order.
Syntax
var sortedIDs = $( ".selector" ).sortable( "toArray" );
This method returns a serialized query string (submittable via Ajax) formed from the sortable.
Action - serialize( options )
This method returns a serialized query string (submittable via Ajax) formed from the sortable. It works by default by looking at the id of each item in the format "setname_number", and it spits out a hash like "setname[]=number&setname[]=number".
Syntax
var sorted = $( ".selector" ).sortable( "serialize", { key: "sort" } );
This method is used mostly internally to refresh the cached information of the sortable. This method does not accept any arguments.
Action - refreshPositions()
This method is used mostly internally to refresh the cached information of the sortable. This method does not accept any arguments.
Syntax
$(".selector").sortable("refreshPositions");
This method returns a jQuery object containing the sortable element. This method does not accept any arguments.
Action - widget()
This method returns a jQuery object containing the sortable element. This method does not accept any arguments.
Syntax
$(".selector").sortable("widget");
Now let us see an example using the actions from the above table. The following example demonstrates the use of toArray( options ) method.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-8{ list-style-type: none; margin: 0;
padding: 0; width: 25%; float:left;}
#sortable-8 li{ margin: 0 3px 3px 3px; padding: 0.4em;
padding-left: 1.5em; font-size: 17px; height: 16px; }
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
</style>
<script>
$(function() {
$('#sortable-8').sortable({
update: function(event, ui) {
var productOrder = $(this).sortable('toArray').toString();
$("#sortable-9").text (productOrder);
}
});
});
</script>
</head>
<body>
<ul id = "sortable-8">
<li id = "1" class = "default">Product 1</li>
<li id = "2" class = "default">Product 2</li>
<li id = "3" class = "default">Product 3</li>
<li id = "4" class = "default">Product 4</li>
</ul>
<br>
<h3><span id = "sortable-9"></span></h3>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
Product 1
Product 2
Product 3
Product 4
Try sorting the items, the order of items is displayed at the bottom. Here we are calling $(this).sortable('toArray').toString(), which will give a string list of all the item id's, it might look like 1,2,3,4.
In addition to the sortable (options) method which we saw in the previous sections, JqueryUI provides event methods as which gets triggered for a particular event. These event methods are listed below −
This event is triggered on the sortable when a sort operation starts on connected sortable.
Event - activate(event, ui)
This event is triggered on the sortable when a sort operation starts on connected sortable. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
activate: function( event, ui ) {}
});
This event is triggered when the sort operation is about to end, with the helper and placeholder element reference still valid.
Event - beforeStop(event, ui)
This event is triggered when the sort operation is about to end, with the helper and placeholder element reference still valid. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
beforeStop: function( event, ui ) {}
});
This event is triggered when the sorted element changes position within the DOM.
Event - change(event, ui)
This event is triggered when the sorted element changes position within the DOM. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
change: function( event, ui ) {}
});
This event is triggered when the sortable is created.
Event - create(event, ui)
This event is triggered when the sortable is created. Where event is of type Event, and ui is of type Object. The ui object is empty but included for consistency with other events.
Syntax
$( ".selector" ).sortable({
create: function( event, ui ) {}
});
This event is triggered when a connected sort stops, propagated to the connected sortable.
Event - deactivate(event, ui)
This event is triggered when a connected sort stops, propagated to the connected sortable. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
deactivate: function( event, ui ) {}
});
This event is triggered when the sort item is moved away from a connected list.
Event - out(event, ui)
This event is triggered when the sort item is moved away from a connected list. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
out: function( event, ui ) {}
});
This event is triggered when a sort item moves into a connected list.
Event - over(event, ui)
This event is triggered when a sort item moves into a connected list. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
over: function( event, ui ) {}
});
This event is triggered when a connected list has received a sort item from another list.
Event - receive(event, ui)
This event is triggered when a connected list has received a sort item from another list. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
receive: function( event, ui ) {}
});
This event is triggered when the sort item is removed from a connected list and is dragged into another.
Event - remove(event, ui)
This event is triggered when the sort item is removed from a connected list and is dragged into another. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
remove: function( event, ui ) {}
});
This event is repeatedly triggered for mousemove events during a sort operation.
Event - sort(event, ui)
This event is repeatedly triggered for mousemove events during a sort operation. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
sort: function( event, ui ) {}
});
This event is triggered when a sort operation starts.
Event - start(event, ui)
This event is triggered when a sort operation starts. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
start: function( event, ui ) {}
});
This event is triggered when a sort operation has concluded.
Event - stop(event, ui)
This event is triggered when a sort operation has concluded. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
stop: function( event, ui ) {}
});
This event is triggered when a sort operation stops and the position of the item has been changed.
Event - update(event, ui)
This event is triggered when a sort operation stops and the position of the item has been changed. Where event is of type Event, and ui is of type Object. Possible values of ui are −
helper − A jQuery object representing the helper being sorted.
helper − A jQuery object representing the helper being sorted.
item − A jQuery object representing the current dragged element.
item − A jQuery object representing the current dragged element.
offset − The current absolute position of the helper represented as { top, left }..
offset − The current absolute position of the helper represented as { top, left }..
position − Current CSS position of the helper as { top, left } object.
position − Current CSS position of the helper as { top, left } object.
originalPosition − The original position of the element represented as { top, left }.
originalPosition − The original position of the element represented as { top, left }.
sender − The sortable that the item comes from if moving from one sortable to another.
sender − The sortable that the item comes from if moving from one sortable to another.
placeholder − The jQuery object representing the element being used as a placeholder.
placeholder − The jQuery object representing the element being used as a placeholder.
Syntax
$( ".selector" ).sortable({
update: function( event, ui ) {}
});
The following example demonstrates the event method usage during drop functionality. This example demonstrates the use of events receive, start and stop.
<!DOCTYPE html>
<html>
<head>
<title>jQuery UI Sortable - Example</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#sortable-10, #sortable-11 { list-style-type: none;
margin: 0; padding: 0; width: 80%; }
#sortable-10 li, #sortable-11 li { margin: 0 3px 3px 3px;
padding: 0.4em; padding-left: 1.5em;
font-size: 17px; height: 16px; }
.highlight {
border: 1px solid #000000;
font-weight: bold;
font-size: 45px;
background-color: #cedc98;
}
.default {
background: #cedc98;
border: 1px solid #DDDDDD;
color: #333333;
}
.wrap {
display: table-row-group;
}
.wrap1 {
float:left;
width: 100px;
}
</style>
<script>
$(function() {
$( "#sortable-10" ).sortable({
start: function (event, ui) {
$("span#result").html ($("span#result").html ()
+ "<b>start</b><br>");
},
receive : function (event, ui) {
$("span#result").html ($("span#result").html ()
+ ", receive");
},
stop: function (event, ui) {
$("span#result").html ($("span#result").html ()
+ "<b>stop</b><br>");
}
});
$( "#sortable-11" ).sortable({
connectWith : "#sortable-10, #sortable-11"
});
});
</script>
</head>
<body>
<div class = "wrap">
<div class = "wrap1">
<h3>List 1</h3>
<ul id = "sortable-10">
<li class = "default">A</li>
<li class = "default">B</li>
<li class = "default">C</li>
<li class = "default">D</li>
</ul>
</div>
<div class = "wrap1">
<h3>List 2</h3>
<ul id = "sortable-11">
<li class = "default">a</li>
<li class = "default">b</li>
<li class = "default">c</li>
<li class = "default">d</li>
</ul>
</div>
</div>
<hr />
<span id = result></span>
</body>
</html>
Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −
A
B
C
D
a
b
c
d
Try sorting the items in List 1, you will see the message getting displayed at the start and stop of event. Now drop items from List 2 to List 1, again a message gets displayed on the receive event.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2455,
"s": 2264,
"text": "jQueryUI provides sortable() method to reorder elements in list or grid using the mouse. This method performs sortability action based upon an operation string passed as the first parameter."
},
{
"code": null,
"e": 2505,
"s": 2455,
"text": "The sortable () method can be used in two forms −"
},
{
"code": null,
"e": 2552,
"s": 2505,
"text": "$(selector, context).sortable (options) Method"
},
{
"code": null,
"e": 2599,
"s": 2552,
"text": "$(selector, context).sortable (options) Method"
},
{
"code": null,
"e": 2657,
"s": 2599,
"text": "$(selector, context).sortable (\"action\", [params]) Method"
},
{
"code": null,
"e": 2715,
"s": 2657,
"text": "$(selector, context).sortable (\"action\", [params]) Method"
},
{
"code": null,
"e": 2917,
"s": 2715,
"text": "The sortable (options) method declares that an HTML element contains interchangeable elements. The options parameter is an object that specifies the behavior of the elements involved during reordering."
},
{
"code": null,
"e": 2958,
"s": 2917,
"text": "$(selector, context).sortable(options);\n"
},
{
"code": null,
"e": 3042,
"s": 2958,
"text": "The following table lists the different options that can be used with this method −"
},
{
"code": null,
"e": 3212,
"s": 3042,
"text": "This option specifies the element in which the new element created with options.helper will be inserted during the time of the move/drag. By default its value is parent."
},
{
"code": null,
"e": 3230,
"s": 3212,
"text": "Option - appendTo"
},
{
"code": null,
"e": 3400,
"s": 3230,
"text": "This option specifies the element in which the new element created with options.helper will be inserted during the time of the move/drag. By default its value is parent."
},
{
"code": null,
"e": 3422,
"s": 3400,
"text": "This can be of type −"
},
{
"code": null,
"e": 3510,
"s": 3422,
"text": "Selector − This indicates a selector specifying which element to append the helper to.."
},
{
"code": null,
"e": 3598,
"s": 3510,
"text": "Selector − This indicates a selector specifying which element to append the helper to.."
},
{
"code": null,
"e": 3686,
"s": 3598,
"text": "jQuery − This indicates a jQuery object containing the element to append the helper to."
},
{
"code": null,
"e": 3774,
"s": 3686,
"text": "jQuery − This indicates a jQuery object containing the element to append the helper to."
},
{
"code": null,
"e": 3855,
"s": 3774,
"text": "Element − An element in the Document Object Model (DOM) to append the helper to."
},
{
"code": null,
"e": 3936,
"s": 3855,
"text": "Element − An element in the Document Object Model (DOM) to append the helper to."
},
{
"code": null,
"e": 4026,
"s": 3936,
"text": "String − The string \"parent\" will cause the helper to be a sibling of the sortable item."
},
{
"code": null,
"e": 4116,
"s": 4026,
"text": "String − The string \"parent\" will cause the helper to be a sibling of the sortable item."
},
{
"code": null,
"e": 4123,
"s": 4116,
"text": "Syntax"
},
{
"code": null,
"e": 4183,
"s": 4123,
"text": "$(\".selector\").sortable(\n { appendTo: document.body }\n);\n"
},
{
"code": null,
"e": 4294,
"s": 4183,
"text": "This option indicates an axis of movement (\"x\" is horizontal, \"y\" is vertical). By default its value is false."
},
{
"code": null,
"e": 4308,
"s": 4294,
"text": "Option - axis"
},
{
"code": null,
"e": 4419,
"s": 4308,
"text": "This option indicates an axis of movement (\"x\" is horizontal, \"y\" is vertical). By default its value is false."
},
{
"code": null,
"e": 4426,
"s": 4419,
"text": "Syntax"
},
{
"code": null,
"e": 4472,
"s": 4426,
"text": "$(\".selector\").sortable(\n { axis: \"x\" }\n);\n"
},
{
"code": null,
"e": 4631,
"s": 4472,
"text": "This option is used to prevent sorting of elements by clicking on any of the selector elements. By default its value is \"input,textarea,button,select,option\"."
},
{
"code": null,
"e": 4647,
"s": 4631,
"text": "Option - cancel"
},
{
"code": null,
"e": 4806,
"s": 4647,
"text": "This option is used to prevent sorting of elements by clicking on any of the selector elements. By default its value is \"input,textarea,button,select,option\"."
},
{
"code": null,
"e": 4813,
"s": 4806,
"text": "Syntax"
},
{
"code": null,
"e": 4868,
"s": 4813,
"text": "$(\".selector\").sortable(\n { cancel: \"a,button\" }\n);\n"
},
{
"code": null,
"e": 5184,
"s": 4868,
"text": "This option is a Selector that identifies another sortable element that can accept items from this sortable. This allows items from one list to be moved to other lists, a frequent and useful user interaction. If omitted, no other element is connected. This is a one-way relationship. By default its value is false."
},
{
"code": null,
"e": 5205,
"s": 5184,
"text": "Option - connectWith"
},
{
"code": null,
"e": 5521,
"s": 5205,
"text": "This option is a Selector that identifies another sortable element that can accept items from this sortable. This allows items from one list to be moved to other lists, a frequent and useful user interaction. If omitted, no other element is connected. This is a one-way relationship. By default its value is false."
},
{
"code": null,
"e": 5528,
"s": 5521,
"text": "Syntax"
},
{
"code": null,
"e": 5591,
"s": 5528,
"text": "$(\".selector\").sortable(\n { connectWith: \"#identifier\" }\n);\n"
},
{
"code": null,
"e": 5847,
"s": 5591,
"text": "This option indicates an element within which the displacement takes place. The element will be represented by a selector (only the first item in the list will be considered), a DOM element, or the string \"parent\" (parent element) or \"window\" (HTML page)."
},
{
"code": null,
"e": 5868,
"s": 5847,
"text": "Option - containment"
},
{
"code": null,
"e": 5944,
"s": 5868,
"text": "This option indicates an element within which the displacement takes place."
},
{
"code": null,
"e": 5966,
"s": 5944,
"text": "This can be of type −"
},
{
"code": null,
"e": 6103,
"s": 5966,
"text": "Selector − This indicates a selector. The element will be represented by a selector (only the first item in the list will be considered)"
},
{
"code": null,
"e": 6240,
"s": 6103,
"text": "Selector − This indicates a selector. The element will be represented by a selector (only the first item in the list will be considered)"
},
{
"code": null,
"e": 6290,
"s": 6240,
"text": "Element − An DOM element to use as the container."
},
{
"code": null,
"e": 6340,
"s": 6290,
"text": "Element − An DOM element to use as the container."
},
{
"code": null,
"e": 6486,
"s": 6340,
"text": "String − The string identifying an element to use as the container. Possible values are parent (parent element), document or window (HTML page)."
},
{
"code": null,
"e": 6632,
"s": 6486,
"text": "String − The string identifying an element to use as the container. Possible values are parent (parent element), document or window (HTML page)."
},
{
"code": null,
"e": 6639,
"s": 6632,
"text": "Syntax"
},
{
"code": null,
"e": 6697,
"s": 6639,
"text": "$(\".selector\").sortable(\n { containment: \"parent\" }\n);\n"
},
{
"code": null,
"e": 6833,
"s": 6697,
"text": "Specifies the cursor CSS property when the element moves. It represents the shape of the mouse pointer. By default its value is \"auto\"."
},
{
"code": null,
"e": 6849,
"s": 6833,
"text": "Option - cursor"
},
{
"code": null,
"e": 7007,
"s": 6849,
"text": "Specifies the cursor CSS property when the element moves. It represents the shape of the mouse pointer. By default its value is \"auto\". Possible values are −"
},
{
"code": null,
"e": 7028,
"s": 7007,
"text": "\"crosshair\" (across)"
},
{
"code": null,
"e": 7049,
"s": 7028,
"text": "\"default\" (an arrow)"
},
{
"code": null,
"e": 7066,
"s": 7049,
"text": "\"pointer\" (hand)"
},
{
"code": null,
"e": 7092,
"s": 7066,
"text": "\"move\" (two arrows cross)"
},
{
"code": null,
"e": 7125,
"s": 7092,
"text": "\"e-resize\" (expand to the right)"
},
{
"code": null,
"e": 7155,
"s": 7125,
"text": "\"ne-resize\" (expand up right)"
},
{
"code": null,
"e": 7184,
"s": 7155,
"text": "\"nw-resize\" (expand up left)"
},
{
"code": null,
"e": 7207,
"s": 7184,
"text": "\"n-resize\" (expand up)"
},
{
"code": null,
"e": 7239,
"s": 7207,
"text": "\"se-resize\" (expand down right)"
},
{
"code": null,
"e": 7270,
"s": 7239,
"text": "\"sw-resize\" (expand down left)"
},
{
"code": null,
"e": 7295,
"s": 7270,
"text": "\"s-resize\" (expand down)"
},
{
"code": null,
"e": 7312,
"s": 7295,
"text": "\"auto\" (default)"
},
{
"code": null,
"e": 7337,
"s": 7312,
"text": "\"w-resize\" (expand left)"
},
{
"code": null,
"e": 7368,
"s": 7337,
"text": "\"text\" (pointer to write text)"
},
{
"code": null,
"e": 7387,
"s": 7368,
"text": "\"wait\" (hourglass)"
},
{
"code": null,
"e": 7409,
"s": 7387,
"text": "\"help\" (help pointer)"
},
{
"code": null,
"e": 7416,
"s": 7409,
"text": "Syntax"
},
{
"code": null,
"e": 7467,
"s": 7416,
"text": "$(\".selector\").sortable(\n { cursor: \"move\" }\n);\n"
},
{
"code": null,
"e": 7674,
"s": 7467,
"text": "Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. By default its value is \"false\"."
},
{
"code": null,
"e": 7692,
"s": 7674,
"text": "Option - cursorAt"
},
{
"code": null,
"e": 7899,
"s": 7692,
"text": "Sets the offset of the dragging helper relative to the mouse cursor. Coordinates can be given as a hash using a combination of one or two keys: { top, left, right, bottom }. By default its value is \"false\"."
},
{
"code": null,
"e": 7906,
"s": 7899,
"text": "Syntax"
},
{
"code": null,
"e": 7964,
"s": 7906,
"text": "$(\".selector\").sortable(\n { cursorAt: { left: 5 } }\n);\n"
},
{
"code": null,
"e": 8128,
"s": 7964,
"text": "Delay, in milliseconds, after which the first movement of the mouse is taken into account. The displacement may begin after that time. By default its value is \"0\"."
},
{
"code": null,
"e": 8143,
"s": 8128,
"text": "Option - delay"
},
{
"code": null,
"e": 8307,
"s": 8143,
"text": "Delay, in milliseconds, after which the first movement of the mouse is taken into account. The displacement may begin after that time. By default its value is \"0\"."
},
{
"code": null,
"e": 8314,
"s": 8307,
"text": "Syntax"
},
{
"code": null,
"e": 8361,
"s": 8314,
"text": "$(\".selector\").sortable(\n { delay: 150 }\n);\n"
},
{
"code": null,
"e": 8457,
"s": 8361,
"text": "This option if set to true, disables the sortable functionality. By default its value is false."
},
{
"code": null,
"e": 8475,
"s": 8457,
"text": "Option - disabled"
},
{
"code": null,
"e": 8571,
"s": 8475,
"text": "This option if set to true, disables the sortable functionality. By default its value is false."
},
{
"code": null,
"e": 8578,
"s": 8571,
"text": "Syntax"
},
{
"code": null,
"e": 8629,
"s": 8578,
"text": "$(\".selector\").sortable(\n { disabled: true }\n);\n"
},
{
"code": null,
"e": 8814,
"s": 8629,
"text": "Number of pixels that the mouse must be moved before the sorting starts. If specified, sorting will not start until after mouse is dragged beyond distance. By default its value is \"1\"."
},
{
"code": null,
"e": 8832,
"s": 8814,
"text": "Option - distance"
},
{
"code": null,
"e": 9017,
"s": 8832,
"text": "Number of pixels that the mouse must be moved before the sorting starts. If specified, sorting will not start until after mouse is dragged beyond distance. By default its value is \"1\"."
},
{
"code": null,
"e": 9024,
"s": 9017,
"text": "Syntax"
},
{
"code": null,
"e": 9072,
"s": 9024,
"text": "$(\".selector\").sortable(\n { distance: 5 }\n);\n"
},
{
"code": null,
"e": 9208,
"s": 9072,
"text": "This option if set to false, then items from this sortable can't be dropped on an empty connect sortable. By default its value is true."
},
{
"code": null,
"e": 9229,
"s": 9208,
"text": "Option - dropOnEmpty"
},
{
"code": null,
"e": 9365,
"s": 9229,
"text": "This option if set to false, then items from this sortable can't be dropped on an empty connect sortable. By default its value is true."
},
{
"code": null,
"e": 9372,
"s": 9365,
"text": "Syntax"
},
{
"code": null,
"e": 9427,
"s": 9372,
"text": "$(\".selector\").sortable(\n { dropOnEmpty: false }\n);\n"
},
{
"code": null,
"e": 9522,
"s": 9427,
"text": "If this option if set to true forces the helper to have a size. By default its value is false."
},
{
"code": null,
"e": 9547,
"s": 9522,
"text": "Option - forceHelperSize"
},
{
"code": null,
"e": 9642,
"s": 9547,
"text": "If this option if set to true forces the helper to have a size. By default its value is false."
},
{
"code": null,
"e": 9649,
"s": 9642,
"text": "Syntax"
},
{
"code": null,
"e": 9707,
"s": 9649,
"text": "$(\".selector\").sortable(\n { forceHelperSize: true }\n);\n"
},
{
"code": null,
"e": 9904,
"s": 9707,
"text": "This option when set to true, takes into account the size of the placeholder when an item is moved. This option is only useful if options.placeholder is initialized. By default its value is false."
},
{
"code": null,
"e": 9934,
"s": 9904,
"text": "Option - forcePlaceholderSize"
},
{
"code": null,
"e": 10131,
"s": 9934,
"text": "This option when set to true, takes into account the size of the placeholder when an item is moved. This option is only useful if options.placeholder is initialized. By default its value is false."
},
{
"code": null,
"e": 10138,
"s": 10131,
"text": "Syntax"
},
{
"code": null,
"e": 10201,
"s": 10138,
"text": "$(\".selector\").sortable(\n { forcePlaceholderSize: true }\n);\n"
},
{
"code": null,
"e": 10388,
"s": 10201,
"text": "This option is an Array [x, y] indicating the number of pixels that the sorting element moves horizontally and vertically during displacement of the mouse. By default its value is false."
},
{
"code": null,
"e": 10402,
"s": 10388,
"text": "Option - grid"
},
{
"code": null,
"e": 10589,
"s": 10402,
"text": "This option is an Array [x, y] indicating the number of pixels that the sorting element moves horizontally and vertically during displacement of the mouse. By default its value is false."
},
{
"code": null,
"e": 10596,
"s": 10589,
"text": "Syntax"
},
{
"code": null,
"e": 10649,
"s": 10596,
"text": "$(\".selector\").sortable(\n { grid: [ 20, 10 ] }\n);\n"
},
{
"code": null,
"e": 10780,
"s": 10649,
"text": "If specified, restricts sort from starting unless the mousedown occurs on the specified element(s). By default its value is false."
},
{
"code": null,
"e": 10796,
"s": 10780,
"text": "Option - handle"
},
{
"code": null,
"e": 10927,
"s": 10796,
"text": "If specified, restricts sort from starting unless the mousedown occurs on the specified element(s). By default its value is false."
},
{
"code": null,
"e": 10934,
"s": 10927,
"text": "Syntax"
},
{
"code": null,
"e": 10988,
"s": 10934,
"text": "$(\".selector\").sortable(\n { handle: \".handle\" }\n);\n"
},
{
"code": null,
"e": 11083,
"s": 10988,
"text": "Allows for a helper element to be used for dragging display. By default its value is original."
},
{
"code": null,
"e": 11099,
"s": 11083,
"text": "Option - helper"
},
{
"code": null,
"e": 11216,
"s": 11099,
"text": "Allows for a helper element to be used for dragging display. By default its value is original. Possible values are −"
},
{
"code": null,
"e": 11308,
"s": 11216,
"text": "String − If set to \"clone\", then the element will be cloned and the clone will be dragged."
},
{
"code": null,
"e": 11400,
"s": 11308,
"text": "String − If set to \"clone\", then the element will be cloned and the clone will be dragged."
},
{
"code": null,
"e": 11476,
"s": 11400,
"text": "Function − A function that will return a DOMElement to use while dragging."
},
{
"code": null,
"e": 11552,
"s": 11476,
"text": "Function − A function that will return a DOMElement to use while dragging."
},
{
"code": null,
"e": 11559,
"s": 11552,
"text": "Syntax"
},
{
"code": null,
"e": 11611,
"s": 11559,
"text": "$(\".selector\").sortable(\n { helper: \"clone\" }\n);\n"
},
{
"code": null,
"e": 11711,
"s": 11611,
"text": "This option specifies which items inside the DOM element to be sorted. By default its value is > *."
},
{
"code": null,
"e": 11726,
"s": 11711,
"text": "Option - items"
},
{
"code": null,
"e": 11825,
"s": 11726,
"text": "This option specifies which items inside the DOM element to be sorted. By default its value is > *"
},
{
"code": null,
"e": 11832,
"s": 11825,
"text": "Syntax"
},
{
"code": null,
"e": 11882,
"s": 11832,
"text": "$(\".selector\").sortable(\n { items: \"> li\" }\n);\n"
},
{
"code": null,
"e": 11984,
"s": 11882,
"text": "This option is used to define the opacity of the helper while sorting. By default its value is false."
},
{
"code": null,
"e": 12001,
"s": 11984,
"text": "Option - opacity"
},
{
"code": null,
"e": 12103,
"s": 12001,
"text": "This option is used to define the opacity of the helper while sorting. By default its value is false."
},
{
"code": null,
"e": 12110,
"s": 12103,
"text": "Syntax"
},
{
"code": null,
"e": 12159,
"s": 12110,
"text": "$(\".selector\").sortable(\n { opacity: 0.5 }\n);\n"
},
{
"code": null,
"e": 12271,
"s": 12159,
"text": "This option is used to class name that gets applied to the otherwise white space.By default its value is false."
},
{
"code": null,
"e": 12292,
"s": 12271,
"text": "Option - placeholder"
},
{
"code": null,
"e": 12299,
"s": 12292,
"text": "Syntax"
},
{
"code": null,
"e": 12353,
"s": 12299,
"text": "$(\".selector\").sortable(\n { addClasses: false }\n);\n"
},
{
"code": null,
"e": 12494,
"s": 12353,
"text": "This option decides whether the sortable items should revert to their new positions using a smooth animation. By default its value is false."
},
{
"code": null,
"e": 12510,
"s": 12494,
"text": "Option - revert"
},
{
"code": null,
"e": 12651,
"s": 12510,
"text": "This option decides whether the sortable items should revert to their new positions using a smooth animation. By default its value is false."
},
{
"code": null,
"e": 12658,
"s": 12651,
"text": "Syntax"
},
{
"code": null,
"e": 12707,
"s": 12658,
"text": "$(\".selector\").sortable(\n { revert: true }\n);\n"
},
{
"code": null,
"e": 12834,
"s": 12707,
"text": "This option is used to enable scrolling. If set to true the page scrolls when coming to an edge. By default its value is true."
},
{
"code": null,
"e": 12850,
"s": 12834,
"text": "Option - scroll"
},
{
"code": null,
"e": 12977,
"s": 12850,
"text": "This option is used to enable scrolling. If set to true the page scrolls when coming to an edge. By default its value is true."
},
{
"code": null,
"e": 12984,
"s": 12977,
"text": "Syntax"
},
{
"code": null,
"e": 13034,
"s": 12984,
"text": "$(\".selector\").sortable(\n { scroll: false }\n);\n"
},
{
"code": null,
"e": 13215,
"s": 13034,
"text": "This option indicates how many pixels the mouse must exit the visible area to cause scrolling. By default its value is 20. This option is used only with options.scroll set to true."
},
{
"code": null,
"e": 13242,
"s": 13215,
"text": "Option - scrollSensitivity"
},
{
"code": null,
"e": 13423,
"s": 13242,
"text": "This option indicates how many pixels the mouse must exit the visible area to cause scrolling. By default its value is 20. This option is used only with options.scroll set to true."
},
{
"code": null,
"e": 13430,
"s": 13423,
"text": "Syntax"
},
{
"code": null,
"e": 13488,
"s": 13430,
"text": "$(\".selector\").sortable(\n { scrollSensitivity: 10 }\n);\n"
},
{
"code": null,
"e": 13600,
"s": 13488,
"text": "This option indicates the scrolling speed of the display once the scrolling begins. By default its value is 20."
},
{
"code": null,
"e": 13621,
"s": 13600,
"text": "Option - scrollSpeed"
},
{
"code": null,
"e": 13733,
"s": 13621,
"text": "This option indicates the scrolling speed of the display once the scrolling begins. By default its value is 20."
},
{
"code": null,
"e": 13740,
"s": 13733,
"text": "Syntax"
},
{
"code": null,
"e": 13792,
"s": 13740,
"text": "$(\".selector\").sortable(\n { scrollSpeed: 40 }\n);\n"
},
{
"code": null,
"e": 13958,
"s": 13792,
"text": "This option is a String that specifies which mode to use for testing whether the item being moved is hovering over another item. By default its value is \"intersect\"."
},
{
"code": null,
"e": 13977,
"s": 13958,
"text": "Option - tolerance"
},
{
"code": null,
"e": 14164,
"s": 13977,
"text": "This option is a String that specifies which mode to use for testing whether the item being moved is hovering over another item. By default its value is \"intersect\".Possible values are −"
},
{
"code": null,
"e": 14226,
"s": 14164,
"text": "intersect − The item overlaps the other item by at least 50%."
},
{
"code": null,
"e": 14288,
"s": 14226,
"text": "intersect − The item overlaps the other item by at least 50%."
},
{
"code": null,
"e": 14341,
"s": 14288,
"text": "pointer − The mouse pointer overlaps the other item."
},
{
"code": null,
"e": 14394,
"s": 14341,
"text": "pointer − The mouse pointer overlaps the other item."
},
{
"code": null,
"e": 14401,
"s": 14394,
"text": "Syntax"
},
{
"code": null,
"e": 14458,
"s": 14401,
"text": "$(\".selector\").sortable(\n { tolerance: \"pointer\" }\n);\n"
},
{
"code": null,
"e": 14558,
"s": 14458,
"text": "This option represents z-index for element/helper while being sorted. By default its value is 1000."
},
{
"code": null,
"e": 14574,
"s": 14558,
"text": "Option - zIndex"
},
{
"code": null,
"e": 14674,
"s": 14574,
"text": "This option represents Z-index for element/helper while being sorted. By default its value is 1000."
},
{
"code": null,
"e": 14681,
"s": 14674,
"text": "Syntax"
},
{
"code": null,
"e": 14730,
"s": 14681,
"text": "$(\".selector\").sortable(\n { zIndex: 9999 }\n);\n"
},
{
"code": null,
"e": 14812,
"s": 14730,
"text": "The following section will show you a few working examples of drag functionality."
},
{
"code": null,
"e": 14939,
"s": 14812,
"text": "The following example demonstrates a simple example of sortable functionality, passing no parameters to the sortable() method."
},
{
"code": null,
"e": 16212,
"s": 14939,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #sortable-1 { list-style-type: none; margin: 0; \n padding: 0; width: 25%; }\n #sortable-1 li { margin: 0 3px 3px 3px; padding: 0.4em; \n padding-left: 1.5em; font-size: 17px; height: 16px; }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#sortable-1\" ).sortable();\n });\n </script>\n </head>\n \n <body>\n <ul id = \"sortable-1\">\n <li class = \"default\">Product 1</li>\n <li class = \"default\">Product 2</li>\n <li class = \"default\">Product 3</li>\n <li class = \"default\">Product 4</li>\n <li class = \"default\">Product 5</li>\n <li class = \"default\">Product 6</li>\n <li class = \"default\">Product 7</li>\n </ul>\n </body>\n</html>"
},
{
"code": null,
"e": 16405,
"s": 16212,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 16415,
"s": 16405,
"text": "Product 1"
},
{
"code": null,
"e": 16425,
"s": 16415,
"text": "Product 2"
},
{
"code": null,
"e": 16435,
"s": 16425,
"text": "Product 3"
},
{
"code": null,
"e": 16445,
"s": 16435,
"text": "Product 4"
},
{
"code": null,
"e": 16455,
"s": 16445,
"text": "Product 5"
},
{
"code": null,
"e": 16465,
"s": 16455,
"text": "Product 6"
},
{
"code": null,
"e": 16475,
"s": 16465,
"text": "Product 7"
},
{
"code": null,
"e": 16531,
"s": 16475,
"text": "Re-arrange the products above, use mouse to drag items."
},
{
"code": null,
"e": 16654,
"s": 16531,
"text": "The following example demonstrates the usage of three options (a) delay and (b) distance in the sort function of JqueryUI."
},
{
"code": null,
"e": 18236,
"s": 16654,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #sortable-2, #sortable-3 { list-style-type: none; margin: 0; \n padding: 0; width: 25%; }\n #sortable-2 li, #sortable-3 li { margin: 0 3px 3px 3px; padding: 0.4em; \n padding-left: 1.5em; font-size: 17px; height: 16px; }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#sortable-2\" ).sortable({\n delay:500\n });\n $( \"#sortable-3\" ).sortable({\n distance:30\n });\n });\n </script>\n </head>\n \n <body>\n <h3>Delay by 500ms</h3>\n <ul id = \"sortable-2\">\n <li class = \"default\">Product 1</li>\n <li class = \"default\">Product 2</li>\n <li class = \"default\">Product 3</li>\n <li class = \"default\">Product 4</li>\n </ul>\n <h3>Distance Delay by 30px</h3>\n <ul id = \"sortable-3\">\n <li class = \"default\">Product 1</li>\n <li class = \"default\">Product 2</li>\n <li class = \"default\">Product 3</li>\n <li class = \"default\">Product 4</li>\n </ul>\n </body>\n</html>"
},
{
"code": null,
"e": 18429,
"s": 18236,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 18439,
"s": 18429,
"text": "Product 1"
},
{
"code": null,
"e": 18449,
"s": 18439,
"text": "Product 2"
},
{
"code": null,
"e": 18459,
"s": 18449,
"text": "Product 3"
},
{
"code": null,
"e": 18469,
"s": 18459,
"text": "Product 4"
},
{
"code": null,
"e": 18479,
"s": 18469,
"text": "Product 1"
},
{
"code": null,
"e": 18489,
"s": 18479,
"text": "Product 2"
},
{
"code": null,
"e": 18499,
"s": 18489,
"text": "Product 3"
},
{
"code": null,
"e": 18509,
"s": 18499,
"text": "Product 4"
},
{
"code": null,
"e": 18863,
"s": 18509,
"text": "Re-arrange the products above, use mouse to drag items. To prevent accidental sorting either by delay (time) or distance, we have set a number of milliseconds the element needs to be dragged before sorting starts with the delay option. We have also set a distance in pixels the element needs to be dragged before sorting starts with the distance option."
},
{
"code": null,
"e": 18970,
"s": 18863,
"text": "The following example demonstrates the usage of three option placeholder in the sort function of JqueryUI."
},
{
"code": null,
"e": 20459,
"s": 18970,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n\n <style>\n #sortable-4 { list-style-type: none; margin: 0; \n padding: 0; width: 25%; }\n #sortable-4 li { margin: 0 3px 3px 3px; padding: 0.4em; \n padding-left: 1.5em; font-size: 17px; height: 16px; }\n .highlight {\n border: 1px solid red;\n font-weight: bold;\n font-size: 45px;\n background-color: #333333;\n }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#sortable-4\" ).sortable({\n placeholder: \"highlight\"\n });\n });\n </script>\n </head>\n \n <body>\n <ul id = \"sortable-4\">\n <li class = \"default\">Product 1</li>\n <li class = \"default\">Product 2</li>\n <li class = \"default\">Product 3</li>\n <li class = \"default\">Product 4</li>\n <li class = \"default\">Product 5</li>\n <li class = \"default\">Product 6</li>\n <li class = \"default\">Product 7</li>\n </ul>\n </body>\n</html>"
},
{
"code": null,
"e": 20652,
"s": 20459,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 20662,
"s": 20652,
"text": "Product 1"
},
{
"code": null,
"e": 20672,
"s": 20662,
"text": "Product 2"
},
{
"code": null,
"e": 20682,
"s": 20672,
"text": "Product 3"
},
{
"code": null,
"e": 20692,
"s": 20682,
"text": "Product 4"
},
{
"code": null,
"e": 20702,
"s": 20692,
"text": "Product 5"
},
{
"code": null,
"e": 20712,
"s": 20702,
"text": "Product 6"
},
{
"code": null,
"e": 20722,
"s": 20712,
"text": "Product 7"
},
{
"code": null,
"e": 20891,
"s": 20722,
"text": "Try to drag items to rearrange them, while you're dragging items, the placeholder (we have used highlight class to style this space) will show up on an available place."
},
{
"code": null,
"e": 21023,
"s": 20891,
"text": "The following example demonstrates the usage of three options (a) connectWith and (b) dropOnEmpty in the sort function of JqueryUI."
},
{
"code": null,
"e": 22865,
"s": 21023,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #sortable-5, #sortable-6,#sortable-7 { \n list-style-type: none; margin: 0; padding: 0;\n width: 20%;float:left }\n #sortable-5 li, #sortable-6 li,#sortable-7 li { \n margin: 0 3px 3px 3px; padding: 0.4em; \n padding-left: 1.5em; font-size: 17px; height: 16px; }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#sortable-5, #sortable-6\" ).sortable({\n connectWith: \"#sortable-5, #sortable-6\"\n });\n $( \"#sortable-7\").sortable({\n connectWith: \"#sortable-5\",\n dropOnEmpty: false\n });\n });\n </script>\n </head>\n \n <body>\n <ul id = \"sortable-5\"><h3>List 1</h3>\n <li class = \"default\">A</li>\n <li class = \"default\">B</li>\n <li class = \"default\">C</li>\n <li class = \"default\">D</li>\n </ul>\n <ul id = \"sortable-6\"><h3>List 2</h3>\n <li class = \"default\">a</li>\n <li class = \"default\">b</li>\n <li class = \"default\">c</li>\n <li class = \"default\">d</li>\n </ul>\n <ul id = \"sortable-7\"><h3>List 3</h3>\n <li class = \"default\">e</li>\n <li class = \"default\">f</li>\n <li class = \"default\">g</li>\n <li class = \"default\">h</li>\n </ul>\n </body>\n</html>"
},
{
"code": null,
"e": 23058,
"s": 22865,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 23060,
"s": 23058,
"text": "A"
},
{
"code": null,
"e": 23062,
"s": 23060,
"text": "B"
},
{
"code": null,
"e": 23064,
"s": 23062,
"text": "C"
},
{
"code": null,
"e": 23066,
"s": 23064,
"text": "D"
},
{
"code": null,
"e": 23068,
"s": 23066,
"text": "a"
},
{
"code": null,
"e": 23070,
"s": 23068,
"text": "b"
},
{
"code": null,
"e": 23072,
"s": 23070,
"text": "c"
},
{
"code": null,
"e": 23074,
"s": 23072,
"text": "d"
},
{
"code": null,
"e": 23076,
"s": 23074,
"text": "e"
},
{
"code": null,
"e": 23078,
"s": 23076,
"text": "f"
},
{
"code": null,
"e": 23080,
"s": 23078,
"text": "g"
},
{
"code": null,
"e": 23082,
"s": 23080,
"text": "h"
},
{
"code": null,
"e": 23358,
"s": 23082,
"text": "Sort items from one List1 into another (List2) and vice versa, by passing a selector into the connectWith option. This is done by grouping all related lists with a CSS class, and then pass that class into the sortable function (i.e., connectWith: '#sortable-5, #sortable-6')."
},
{
"code": null,
"e": 23504,
"s": 23358,
"text": "Try to drag the items under List 3 to the List 2 or List 1. As we have set dropOnEmpty option to false, it won't be possible to drop these items."
},
{
"code": null,
"e": 23758,
"s": 23504,
"text": "The sortable (action, params) method can perform an action on the sortable elements, such as to prevent displacement. The action is specified as a string in the first argument and optionally, one or more params can be provided based on the given action."
},
{
"code": null,
"e": 23811,
"s": 23758,
"text": "$(selector, context).sortable (\"action\", [params]);\n"
},
{
"code": null,
"e": 23867,
"s": 23811,
"text": "The following table lists the actions for this method −"
},
{
"code": null,
"e": 24037,
"s": 23867,
"text": "This action cancels the current sort operation. This is most useful within handlers for the sort receive and sort stop events. This method does not accept any arguments."
},
{
"code": null,
"e": 24055,
"s": 24037,
"text": "Action - cancel()"
},
{
"code": null,
"e": 24213,
"s": 24055,
"text": "Cancels the current sort operation. This is most useful within handlers for the sort receive and sort stop events. This method does not accept any arguments."
},
{
"code": null,
"e": 24220,
"s": 24213,
"text": "Syntax"
},
{
"code": null,
"e": 24256,
"s": 24220,
"text": "$(\".selector\").sortable(\"cancel\");\n"
},
{
"code": null,
"e": 24418,
"s": 24256,
"text": "This action removes the sortability functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments."
},
{
"code": null,
"e": 24437,
"s": 24418,
"text": "Action - destroy()"
},
{
"code": null,
"e": 24599,
"s": 24437,
"text": "This action removes the sortability functionality completely. This will return the element back to its pre-init state. This method does not accept any arguments."
},
{
"code": null,
"e": 24606,
"s": 24599,
"text": "Syntax"
},
{
"code": null,
"e": 24643,
"s": 24606,
"text": "$(\".selector\").sortable(\"destroy\");\n"
},
{
"code": null,
"e": 24880,
"s": 24643,
"text": "This action disables the sortability of any sortable elements in the wrapped set. The sortability of the elements isn’t removed and can be restored by calling the enable variant of this method. This method does not accept any arguments."
},
{
"code": null,
"e": 24899,
"s": 24880,
"text": "Action - disable()"
},
{
"code": null,
"e": 25136,
"s": 24899,
"text": "This action disables the sortability of any sortable elements in the wrapped set. The sortability of the elements isn’t removed and can be restored by calling the enable variant of this method. This method does not accept any arguments."
},
{
"code": null,
"e": 25143,
"s": 25136,
"text": "Syntax"
},
{
"code": null,
"e": 25180,
"s": 25143,
"text": "$(\".selector\").sortable(\"disable\");\n"
},
{
"code": null,
"e": 25401,
"s": 25180,
"text": "Re-enables sortability on any sortable elements in the wrapped set whose sortability has been disabled. Note that this method won’t add sortability to any non-sortable elements. This method does not accept any arguments."
},
{
"code": null,
"e": 25419,
"s": 25401,
"text": "Action - enable()"
},
{
"code": null,
"e": 25640,
"s": 25419,
"text": "Re-enables sortability on any sortable elements in the wrapped set whose sortability has been disabled. Note that this method won’t add sortability to any non-sortable elements. This method does not accept any arguments."
},
{
"code": null,
"e": 25647,
"s": 25640,
"text": "Syntax"
},
{
"code": null,
"e": 25683,
"s": 25647,
"text": "$(\".selector\").sortable(\"enable\");\n"
},
{
"code": null,
"e": 25813,
"s": 25683,
"text": "This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get."
},
{
"code": null,
"e": 25843,
"s": 25813,
"text": "Action - option( optionName )"
},
{
"code": null,
"e": 25973,
"s": 25843,
"text": "This action gets the value currently associated with the specified optionName. Where optionName is the name of the option to get."
},
{
"code": null,
"e": 25980,
"s": 25973,
"text": "Syntax"
},
{
"code": null,
"e": 26049,
"s": 25980,
"text": "var isDisabled = $( \".selector\" ).sortable( \"option\", \"disabled\" );\n"
},
{
"code": null,
"e": 26183,
"s": 26049,
"text": "Gets an object containing key/value pairs representing the current sortable options hash.. This method does not accept any arguments."
},
{
"code": null,
"e": 26201,
"s": 26183,
"text": "Action - option()"
},
{
"code": null,
"e": 26335,
"s": 26201,
"text": "Gets an object containing key/value pairs representing the current sortable options hash.. This method does not accept any arguments."
},
{
"code": null,
"e": 26342,
"s": 26335,
"text": "Syntax"
},
{
"code": null,
"e": 26378,
"s": 26342,
"text": "$(\".selector\").sortable(\"option\");\n"
},
{
"code": null,
"e": 26567,
"s": 26378,
"text": "This action sets the value of the sortable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option."
},
{
"code": null,
"e": 26604,
"s": 26567,
"text": "Action - option( optionName, value )"
},
{
"code": null,
"e": 26793,
"s": 26604,
"text": "This action sets the value of the sortable option associated with the specified optionName. Where optionName is the name of the option to set and value is the value to set for the option."
},
{
"code": null,
"e": 26800,
"s": 26793,
"text": "Syntax"
},
{
"code": null,
"e": 26854,
"s": 26800,
"text": "$(\".selector\").sortable(\"option\", \"disabled\", true);\n"
},
{
"code": null,
"e": 26950,
"s": 26854,
"text": "Sets one or more options for the sortable. Where options is a map of option-value pairs to set."
},
{
"code": null,
"e": 26977,
"s": 26950,
"text": "Action - option( options )"
},
{
"code": null,
"e": 27073,
"s": 26977,
"text": "Sets one or more options for the sortable. Where options is a map of option-value pairs to set."
},
{
"code": null,
"e": 27080,
"s": 27073,
"text": "Syntax"
},
{
"code": null,
"e": 27140,
"s": 27080,
"text": "$( \".selector\" ).sortable( \"option\", { disabled: true } );\n"
},
{
"code": null,
"e": 27318,
"s": 27140,
"text": "This action refreshes the list of items if necessary. This method does not accept any arguments. Calling this method will cause new items added to the sortable to be recognized."
},
{
"code": null,
"e": 27337,
"s": 27318,
"text": "Action - refresh()"
},
{
"code": null,
"e": 27516,
"s": 27337,
"text": "This action refreshes the list of items if necessary. This method does not accept any arguments. Calling this method will cause new items added to the sortable to be recognized."
},
{
"code": null,
"e": 27523,
"s": 27516,
"text": "Syntax"
},
{
"code": null,
"e": 27560,
"s": 27523,
"text": "$(\".selector\").sortable(\"refresh\");\n"
},
{
"code": null,
"e": 27736,
"s": 27560,
"text": "This method returns an array of the id values of the sortable elements in sorted order. This method takes Options as parameter, to customize the serialization or sorted order."
},
{
"code": null,
"e": 27764,
"s": 27736,
"text": "Action - toArray( options )"
},
{
"code": null,
"e": 27940,
"s": 27764,
"text": "This method returns an array of the id values of the sortable elements in sorted order. This method takes Options as parameter, to customize the serialization or sorted order."
},
{
"code": null,
"e": 27947,
"s": 27940,
"text": "Syntax"
},
{
"code": null,
"e": 28004,
"s": 27947,
"text": "var sortedIDs = $( \".selector\" ).sortable( \"toArray\" );\n"
},
{
"code": null,
"e": 28099,
"s": 28004,
"text": "This method returns a serialized query string (submittable via Ajax) formed from the sortable."
},
{
"code": null,
"e": 28129,
"s": 28099,
"text": "Action - serialize( options )"
},
{
"code": null,
"e": 28376,
"s": 28129,
"text": "This method returns a serialized query string (submittable via Ajax) formed from the sortable. It works by default by looking at the id of each item in the format \"setname_number\", and it spits out a hash like \"setname[]=number&setname[]=number\"."
},
{
"code": null,
"e": 28383,
"s": 28376,
"text": "Syntax"
},
{
"code": null,
"e": 28456,
"s": 28383,
"text": "var sorted = $( \".selector\" ).sortable( \"serialize\", { key: \"sort\" } );\n"
},
{
"code": null,
"e": 28588,
"s": 28456,
"text": "This method is used mostly internally to refresh the cached information of the sortable. This method does not accept any arguments."
},
{
"code": null,
"e": 28616,
"s": 28588,
"text": "Action - refreshPositions()"
},
{
"code": null,
"e": 28748,
"s": 28616,
"text": "This method is used mostly internally to refresh the cached information of the sortable. This method does not accept any arguments."
},
{
"code": null,
"e": 28755,
"s": 28748,
"text": "Syntax"
},
{
"code": null,
"e": 28801,
"s": 28755,
"text": "$(\".selector\").sortable(\"refreshPositions\");\n"
},
{
"code": null,
"e": 28913,
"s": 28801,
"text": "This method returns a jQuery object containing the sortable element. This method does not accept any arguments."
},
{
"code": null,
"e": 28931,
"s": 28913,
"text": "Action - widget()"
},
{
"code": null,
"e": 29043,
"s": 28931,
"text": "This method returns a jQuery object containing the sortable element. This method does not accept any arguments."
},
{
"code": null,
"e": 29050,
"s": 29043,
"text": "Syntax"
},
{
"code": null,
"e": 29086,
"s": 29050,
"text": "$(\".selector\").sortable(\"widget\");\n"
},
{
"code": null,
"e": 29225,
"s": 29086,
"text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of toArray( options ) method."
},
{
"code": null,
"e": 30669,
"s": 29225,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #sortable-8{ list-style-type: none; margin: 0; \n padding: 0; width: 25%; float:left;}\n #sortable-8 li{ margin: 0 3px 3px 3px; padding: 0.4em; \n padding-left: 1.5em; font-size: 17px; height: 16px; }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $('#sortable-8').sortable({\n update: function(event, ui) {\n var productOrder = $(this).sortable('toArray').toString();\n $(\"#sortable-9\").text (productOrder);\n }\n });\n });\n </script>\n </head>\n \n <body>\n <ul id = \"sortable-8\">\n <li id = \"1\" class = \"default\">Product 1</li>\n <li id = \"2\" class = \"default\">Product 2</li>\n <li id = \"3\" class = \"default\">Product 3</li>\n <li id = \"4\" class = \"default\">Product 4</li>\n </ul>\n <br>\n <h3><span id = \"sortable-9\"></span></h3>\n </body>\n</html>"
},
{
"code": null,
"e": 30862,
"s": 30669,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 30872,
"s": 30862,
"text": "Product 1"
},
{
"code": null,
"e": 30882,
"s": 30872,
"text": "Product 2"
},
{
"code": null,
"e": 30892,
"s": 30882,
"text": "Product 3"
},
{
"code": null,
"e": 30902,
"s": 30892,
"text": "Product 4"
},
{
"code": null,
"e": 31112,
"s": 30902,
"text": "Try sorting the items, the order of items is displayed at the bottom. Here we are calling $(this).sortable('toArray').toString(), which will give a string list of all the item id's, it might look like 1,2,3,4."
},
{
"code": null,
"e": 31315,
"s": 31112,
"text": "In addition to the sortable (options) method which we saw in the previous sections, JqueryUI provides event methods as which gets triggered for a particular event. These event methods are listed below −"
},
{
"code": null,
"e": 31407,
"s": 31315,
"text": "This event is triggered on the sortable when a sort operation starts on connected sortable."
},
{
"code": null,
"e": 31435,
"s": 31407,
"text": "Event - activate(event, ui)"
},
{
"code": null,
"e": 31611,
"s": 31435,
"text": "This event is triggered on the sortable when a sort operation starts on connected sortable. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 31674,
"s": 31611,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 31737,
"s": 31674,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 31802,
"s": 31737,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 31867,
"s": 31802,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 31951,
"s": 31867,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 32035,
"s": 31951,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 32106,
"s": 32035,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 32177,
"s": 32106,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 32263,
"s": 32177,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 32349,
"s": 32263,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 32436,
"s": 32349,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 32523,
"s": 32436,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 32609,
"s": 32523,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 32695,
"s": 32609,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 32702,
"s": 32695,
"text": "Syntax"
},
{
"code": null,
"e": 32773,
"s": 32702,
"text": "$( \".selector\" ).sortable({\n activate: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 32901,
"s": 32773,
"text": "This event is triggered when the sort operation is about to end, with the helper and placeholder element reference still valid."
},
{
"code": null,
"e": 32931,
"s": 32901,
"text": "Event - beforeStop(event, ui)"
},
{
"code": null,
"e": 33143,
"s": 32931,
"text": "This event is triggered when the sort operation is about to end, with the helper and placeholder element reference still valid. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 33206,
"s": 33143,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 33269,
"s": 33206,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 33334,
"s": 33269,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 33399,
"s": 33334,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 33483,
"s": 33399,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 33567,
"s": 33483,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 33638,
"s": 33567,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 33709,
"s": 33638,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 33795,
"s": 33709,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 33881,
"s": 33795,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 33968,
"s": 33881,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 34055,
"s": 33968,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 34141,
"s": 34055,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 34227,
"s": 34141,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 34234,
"s": 34227,
"text": "Syntax"
},
{
"code": null,
"e": 34307,
"s": 34234,
"text": "$( \".selector\" ).sortable({\n beforeStop: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 34388,
"s": 34307,
"text": "This event is triggered when the sorted element changes position within the DOM."
},
{
"code": null,
"e": 34414,
"s": 34388,
"text": "Event - change(event, ui)"
},
{
"code": null,
"e": 34579,
"s": 34414,
"text": "This event is triggered when the sorted element changes position within the DOM. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 34642,
"s": 34579,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 34705,
"s": 34642,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 34770,
"s": 34705,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 34835,
"s": 34770,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 34919,
"s": 34835,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 35003,
"s": 34919,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 35074,
"s": 35003,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 35145,
"s": 35074,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 35231,
"s": 35145,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 35317,
"s": 35231,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 35404,
"s": 35317,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 35491,
"s": 35404,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 35577,
"s": 35491,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 35663,
"s": 35577,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 35670,
"s": 35663,
"text": "Syntax"
},
{
"code": null,
"e": 35739,
"s": 35670,
"text": "$( \".selector\" ).sortable({\n change: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 35793,
"s": 35739,
"text": "This event is triggered when the sortable is created."
},
{
"code": null,
"e": 35819,
"s": 35793,
"text": "Event - create(event, ui)"
},
{
"code": null,
"e": 36000,
"s": 35819,
"text": "This event is triggered when the sortable is created. Where event is of type Event, and ui is of type Object. The ui object is empty but included for consistency with other events."
},
{
"code": null,
"e": 36007,
"s": 36000,
"text": "Syntax"
},
{
"code": null,
"e": 36076,
"s": 36007,
"text": "$( \".selector\" ).sortable({\n create: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 36167,
"s": 36076,
"text": "This event is triggered when a connected sort stops, propagated to the connected sortable."
},
{
"code": null,
"e": 36197,
"s": 36167,
"text": "Event - deactivate(event, ui)"
},
{
"code": null,
"e": 36372,
"s": 36197,
"text": "This event is triggered when a connected sort stops, propagated to the connected sortable. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 36435,
"s": 36372,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 36498,
"s": 36435,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 36563,
"s": 36498,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 36628,
"s": 36563,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 36712,
"s": 36628,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 36796,
"s": 36712,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 36867,
"s": 36796,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 36938,
"s": 36867,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 37024,
"s": 36938,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 37110,
"s": 37024,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 37197,
"s": 37110,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 37284,
"s": 37197,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 37370,
"s": 37284,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 37456,
"s": 37370,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 37463,
"s": 37456,
"text": "Syntax"
},
{
"code": null,
"e": 37536,
"s": 37463,
"text": "$( \".selector\" ).sortable({\n deactivate: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 37616,
"s": 37536,
"text": "This event is triggered when the sort item is moved away from a connected list."
},
{
"code": null,
"e": 37639,
"s": 37616,
"text": "Event - out(event, ui)"
},
{
"code": null,
"e": 37803,
"s": 37639,
"text": "This event is triggered when the sort item is moved away from a connected list. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 37866,
"s": 37803,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 37929,
"s": 37866,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 37994,
"s": 37929,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 38059,
"s": 37994,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 38143,
"s": 38059,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 38227,
"s": 38143,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 38298,
"s": 38227,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 38369,
"s": 38298,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 38455,
"s": 38369,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 38541,
"s": 38455,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 38628,
"s": 38541,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 38715,
"s": 38628,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 38801,
"s": 38715,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 38887,
"s": 38801,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 38894,
"s": 38887,
"text": "Syntax"
},
{
"code": null,
"e": 38960,
"s": 38894,
"text": "$( \".selector\" ).sortable({\n out: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 39030,
"s": 38960,
"text": "This event is triggered when a sort item moves into a connected list."
},
{
"code": null,
"e": 39054,
"s": 39030,
"text": "Event - over(event, ui)"
},
{
"code": null,
"e": 39208,
"s": 39054,
"text": "This event is triggered when a sort item moves into a connected list. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 39271,
"s": 39208,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 39334,
"s": 39271,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 39399,
"s": 39334,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 39464,
"s": 39399,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 39548,
"s": 39464,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 39632,
"s": 39548,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 39703,
"s": 39632,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 39774,
"s": 39703,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 39860,
"s": 39774,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 39946,
"s": 39860,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 40033,
"s": 39946,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 40120,
"s": 40033,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 40206,
"s": 40120,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 40292,
"s": 40206,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 40299,
"s": 40292,
"text": "Syntax"
},
{
"code": null,
"e": 40366,
"s": 40299,
"text": "$( \".selector\" ).sortable({\n over: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 40456,
"s": 40366,
"text": "This event is triggered when a connected list has received a sort item from another list."
},
{
"code": null,
"e": 40483,
"s": 40456,
"text": "Event - receive(event, ui)"
},
{
"code": null,
"e": 40657,
"s": 40483,
"text": "This event is triggered when a connected list has received a sort item from another list. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 40720,
"s": 40657,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 40783,
"s": 40720,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 40848,
"s": 40783,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 40913,
"s": 40848,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 40997,
"s": 40913,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 41081,
"s": 40997,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 41152,
"s": 41081,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 41223,
"s": 41152,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 41309,
"s": 41223,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 41395,
"s": 41309,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 41482,
"s": 41395,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 41569,
"s": 41482,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 41655,
"s": 41569,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 41741,
"s": 41655,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 41748,
"s": 41741,
"text": "Syntax"
},
{
"code": null,
"e": 41818,
"s": 41748,
"text": "$( \".selector\" ).sortable({\n receive: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 41923,
"s": 41818,
"text": "This event is triggered when the sort item is removed from a connected list and is dragged into another."
},
{
"code": null,
"e": 41949,
"s": 41923,
"text": "Event - remove(event, ui)"
},
{
"code": null,
"e": 42138,
"s": 41949,
"text": "This event is triggered when the sort item is removed from a connected list and is dragged into another. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 42201,
"s": 42138,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 42264,
"s": 42201,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 42329,
"s": 42264,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 42394,
"s": 42329,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 42478,
"s": 42394,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 42562,
"s": 42478,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 42633,
"s": 42562,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 42704,
"s": 42633,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 42790,
"s": 42704,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 42876,
"s": 42790,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 42963,
"s": 42876,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 43050,
"s": 42963,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 43136,
"s": 43050,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 43222,
"s": 43136,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 43229,
"s": 43222,
"text": "Syntax"
},
{
"code": null,
"e": 43298,
"s": 43229,
"text": "$( \".selector\" ).sortable({\n remove: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 43379,
"s": 43298,
"text": "This event is repeatedly triggered for mousemove events during a sort operation."
},
{
"code": null,
"e": 43403,
"s": 43379,
"text": "Event - sort(event, ui)"
},
{
"code": null,
"e": 43568,
"s": 43403,
"text": "This event is repeatedly triggered for mousemove events during a sort operation. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 43631,
"s": 43568,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 43694,
"s": 43631,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 43759,
"s": 43694,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 43824,
"s": 43759,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 43908,
"s": 43824,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 43992,
"s": 43908,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 44063,
"s": 43992,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 44134,
"s": 44063,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 44220,
"s": 44134,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 44306,
"s": 44220,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 44393,
"s": 44306,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 44480,
"s": 44393,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 44566,
"s": 44480,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 44652,
"s": 44566,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 44659,
"s": 44652,
"text": "Syntax"
},
{
"code": null,
"e": 44726,
"s": 44659,
"text": "$( \".selector\" ).sortable({\n sort: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 44780,
"s": 44726,
"text": "This event is triggered when a sort operation starts."
},
{
"code": null,
"e": 44805,
"s": 44780,
"text": "Event - start(event, ui)"
},
{
"code": null,
"e": 44943,
"s": 44805,
"text": "This event is triggered when a sort operation starts. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 45006,
"s": 44943,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 45069,
"s": 45006,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 45134,
"s": 45069,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 45199,
"s": 45134,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 45283,
"s": 45199,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 45367,
"s": 45283,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 45438,
"s": 45367,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 45509,
"s": 45438,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 45595,
"s": 45509,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 45681,
"s": 45595,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 45768,
"s": 45681,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 45855,
"s": 45768,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 45941,
"s": 45855,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 46027,
"s": 45941,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 46034,
"s": 46027,
"text": "Syntax"
},
{
"code": null,
"e": 46102,
"s": 46034,
"text": "$( \".selector\" ).sortable({\n start: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 46163,
"s": 46102,
"text": "This event is triggered when a sort operation has concluded."
},
{
"code": null,
"e": 46187,
"s": 46163,
"text": "Event - stop(event, ui)"
},
{
"code": null,
"e": 46332,
"s": 46187,
"text": "This event is triggered when a sort operation has concluded. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 46395,
"s": 46332,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 46458,
"s": 46395,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 46523,
"s": 46458,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 46588,
"s": 46523,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 46672,
"s": 46588,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 46756,
"s": 46672,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 46827,
"s": 46756,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 46898,
"s": 46827,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 46984,
"s": 46898,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 47070,
"s": 46984,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 47157,
"s": 47070,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 47244,
"s": 47157,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 47330,
"s": 47244,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 47416,
"s": 47330,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 47423,
"s": 47416,
"text": "Syntax"
},
{
"code": null,
"e": 47490,
"s": 47423,
"text": "$( \".selector\" ).sortable({\n stop: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 47589,
"s": 47490,
"text": "This event is triggered when a sort operation stops and the position of the item has been changed."
},
{
"code": null,
"e": 47615,
"s": 47589,
"text": "Event - update(event, ui)"
},
{
"code": null,
"e": 47798,
"s": 47615,
"text": "This event is triggered when a sort operation stops and the position of the item has been changed. Where event is of type Event, and ui is of type Object. Possible values of ui are −"
},
{
"code": null,
"e": 47861,
"s": 47798,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 47924,
"s": 47861,
"text": "helper − A jQuery object representing the helper being sorted."
},
{
"code": null,
"e": 47989,
"s": 47924,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 48054,
"s": 47989,
"text": "item − A jQuery object representing the current dragged element."
},
{
"code": null,
"e": 48138,
"s": 48054,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 48222,
"s": 48138,
"text": "offset − The current absolute position of the helper represented as { top, left }.."
},
{
"code": null,
"e": 48293,
"s": 48222,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 48364,
"s": 48293,
"text": "position − Current CSS position of the helper as { top, left } object."
},
{
"code": null,
"e": 48450,
"s": 48364,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 48536,
"s": 48450,
"text": "originalPosition − The original position of the element represented as { top, left }."
},
{
"code": null,
"e": 48623,
"s": 48536,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 48710,
"s": 48623,
"text": "sender − The sortable that the item comes from if moving from one sortable to another."
},
{
"code": null,
"e": 48796,
"s": 48710,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 48882,
"s": 48796,
"text": "placeholder − The jQuery object representing the element being used as a placeholder."
},
{
"code": null,
"e": 48889,
"s": 48882,
"text": "Syntax"
},
{
"code": null,
"e": 48958,
"s": 48889,
"text": "$( \".selector\" ).sortable({\n update: function( event, ui ) {}\n});\n"
},
{
"code": null,
"e": 49112,
"s": 48958,
"text": "The following example demonstrates the event method usage during drop functionality. This example demonstrates the use of events receive, start and stop."
},
{
"code": null,
"e": 51729,
"s": 49112,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery UI Sortable - Example</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #sortable-10, #sortable-11 { list-style-type: none; \n margin: 0; padding: 0; width: 80%; }\n #sortable-10 li, #sortable-11 li { margin: 0 3px 3px 3px; \n padding: 0.4em; padding-left: 1.5em; \n font-size: 17px; height: 16px; }\n .highlight {\n border: 1px solid #000000;\n font-weight: bold;\n font-size: 45px;\n background-color: #cedc98;\n }\n .default {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n .wrap {\n display: table-row-group;\n }\n .wrap1 {\n float:left;\n width: 100px;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#sortable-10\" ).sortable({\n start: function (event, ui) {\n $(\"span#result\").html ($(\"span#result\").html () \n + \"<b>start</b><br>\");\n },\n receive : function (event, ui) {\n $(\"span#result\").html ($(\"span#result\").html () \n + \", receive\");\n },\n stop: function (event, ui) {\n $(\"span#result\").html ($(\"span#result\").html () \n + \"<b>stop</b><br>\");\n }\n });\n $( \"#sortable-11\" ).sortable({\n connectWith : \"#sortable-10, #sortable-11\"\n });\n });\n </script>\n </head>\n \n <body>\n <div class = \"wrap\">\n <div class = \"wrap1\"> \n <h3>List 1</h3>\n <ul id = \"sortable-10\">\n <li class = \"default\">A</li>\n <li class = \"default\">B</li>\n <li class = \"default\">C</li>\n <li class = \"default\">D</li>\n </ul>\n </div>\n <div class = \"wrap1\">\n <h3>List 2</h3> \n <ul id = \"sortable-11\">\n <li class = \"default\">a</li>\n <li class = \"default\">b</li>\n <li class = \"default\">c</li>\n <li class = \"default\">d</li>\n </ul>\n </div>\n </div>\n <hr />\n <span id = result></span>\n </body>\n</html>"
},
{
"code": null,
"e": 51922,
"s": 51729,
"text": "Let us save the above code in an HTML file sortexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −"
},
{
"code": null,
"e": 51924,
"s": 51922,
"text": "A"
},
{
"code": null,
"e": 51926,
"s": 51924,
"text": "B"
},
{
"code": null,
"e": 51928,
"s": 51926,
"text": "C"
},
{
"code": null,
"e": 51930,
"s": 51928,
"text": "D"
},
{
"code": null,
"e": 51932,
"s": 51930,
"text": "a"
},
{
"code": null,
"e": 51934,
"s": 51932,
"text": "b"
},
{
"code": null,
"e": 51936,
"s": 51934,
"text": "c"
},
{
"code": null,
"e": 51938,
"s": 51936,
"text": "d"
},
{
"code": null,
"e": 52137,
"s": 51938,
"text": "Try sorting the items in List 1, you will see the message getting displayed at the start and stop of event. Now drop items from List 2 to List 1, again a message gets displayed on the receive event."
},
{
"code": null,
"e": 52144,
"s": 52137,
"text": " Print"
},
{
"code": null,
"e": 52155,
"s": 52144,
"text": " Add Notes"
}
] |
File Upload Example in Python
|
To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
The result of this code is the following form −
Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.
Here is the script save_file.py to handle file upload −
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
|
[
{
"code": null,
"e": 1214,
"s": 1062,
"text": "To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a \"Browse\" button."
},
{
"code": null,
"e": 1445,
"s": 1214,
"text": "<html>\n<body>\n <form enctype = \"multipart/form-data\" action = \"save_file.py\" method = \"post\">\n <p>File: <input type = \"file\" name = \"filename\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 1493,
"s": 1445,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 1629,
"s": 1493,
"text": "Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server."
},
{
"code": null,
"e": 1685,
"s": 1629,
"text": "Here is the script save_file.py to handle file upload −"
},
{
"code": null,
"e": 2259,
"s": 1685,
"text": "#!/usr/bin/python\nimport cgi, os\nimport cgitb; cgitb.enable()\nform = cgi.FieldStorage()\n# Get filename here.\nfileitem = form['filename']\n# Test if the file was uploaded\nif fileitem.filename:\n # strip leading path from file name to avoid\n # directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('/tmp/' + fn, 'wb').write(fileitem.file.read())\n message = 'The file \"' + fn + '\" was uploaded successfully'\nelse:\n message = 'No file was uploaded'\nprint \"\"\"\\\nContent-Type: text/html\\n\n<html>\n<body>\n <p>%s</p>\n</body>\n</html>\n\"\"\" % (message,)"
},
{
"code": null,
"e": 2444,
"s": 2259,
"text": "If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine."
},
{
"code": null,
"e": 2505,
"s": 2444,
"text": "fn = os.path.basename(fileitem.filename.replace(\"\\\\\", \"/\" ))"
}
] |
Tryit Editor v3.7
|
Tryit: HTML table header spans 2 columns
|
[] |
A Better Way to Handle Missing Values in your Dataset: Using IterativeImputer (PART I) | by Gifari Hoque | Towards Data Science
|
IntroductionReasoning with MissingnessHow does it work?- Univariate Imputation- Multivariate ImputationIterative Imputer- How to be the “Chosen One”- The Process Behind the IterationsGetting Started- The Problem with Single Imputation MethodsHow Single Imputation vs. Iterative Imputation can Affect the Distribution of Your DatasetConclusion- References- Final Words
Introduction
Reasoning with Missingness
How does it work?- Univariate Imputation- Multivariate Imputation
Iterative Imputer- How to be the “Chosen One”- The Process Behind the Iterations
Getting Started- The Problem with Single Imputation Methods
How Single Imputation vs. Iterative Imputation can Affect the Distribution of Your Dataset
Conclusion- References- Final Words
Missing data is a major problem when it comes to making profitable business decisions, solving health problems, better understanding a population, etc. Not only is missing data a problem for humans, but it’s also a big problem for the machine we feed the dataset to.
Here’s a hypothetical situation: imagine your boss handing you a book with a number of pages missing every few pages. And now imagine that you HAVE to read the book and give your analysis for each chapter, and a final analysis for the whole book no matter what or you’ll get fired. Now, this may not be surprising for some of you, as some of you may have bosses that actually make you do similar things like this, but how exactly would you handle this situation? Without asking any questions, you accept the task and carry on. I know, now you’re thinking, “I’ll just search this book up online,” and you do. You search everywhere, only to find out that this book doesn’t exist anywhere else, except on your desk right beside you.
You’re only left with one choice, and so, you start to read. You come across the first missing page as you see a torn page in the middle of the book. The book jumps from page number 14 to page number 17. You shrug it off and continue on with the book while also making assumptions about what could’ve possibly happened on pages 15–16. You continue on reading the book and you encounter more missing pages, except now, the book jumps from page 38 to page 45. You can’t believe your eyes, as you start to read page 45. The story is no longer adding up...
You eventually reach the near end of the book and you find out that the ending is not actually the ending. That’s right, a few more pages missing in the end. Having “finished” the book, you look back at the analyses you’ve made for each chapter to try to make a conclusion of your own for the book.
Your dataset is like a story that you give your machine learning model to read, and each row is like a chapter. If your dataset has missing values, your model won’t be able to fully understand what’s going on and may make false predictions.
There are several ways of handling missing data including, but not limited to: ignoring the missing data, removing the row/column depending on the mass of missingness in the row/column, replacement with a single digit (0, 1, any other number, mean, median), grouped replacement, etc.
Having a better understanding of the reasoning for the missingness of your data can help you determine what type of imputation method you can use. In general, there are three types of missing data1:
Missing Completely At Random (MCAR): The values in your dataset are missing completely at random. This is when there is no clear reasoning as to why a certain value in your dataset is missing. An example of this is if a surveyee forgets to answer a question on a voluntary survey. Handling this situation is relatively simple, we can replace the missing data with a mean/median replacement — the data missing is recoverable.
Missing At Random (MAR): The values in your dataset are missing at random. This is when we can determine some correlation to why the data value may be missing. An example of this is if a certain question in a survey is blank for multiple surveyees of the same gender. A way in which we can handle this situation is by using other features to do a grouped mean/median replacement— the data missing is still recoverable.
Missing Not At Random (MNAR): The values in your dataset are not missing at random. This is when we can see a clear pattern to the missing values. An example of this is if a certain question category in a survey is left blank by surveyees because of the question itself, as it may be a sensitive question to the surveyee (the missingness depends on the missing data) — the data missing will be hard to recover unless further research is done. Unlike the other two types of missing data, MNAR is nonignorable.
Before I get into the fun stuff, I’ll have to do a bit more explaining so grab a cup of coffee or a scoop of pre-workout (or two 😏) or whatever you’re into because it’s time to focus.
Let’s start with the basics.
Missing data can cause research or experiments to be biased, can make data analysis more gruesome, and can reduce the quality of your hypothesis testing and results. It’s always better to do more research to reduce your data biases than just say “whatever” and continue on to your analysis. In my opinion, this defeats the purpose of why you first started your experimentation. In the end, not only will your results have bad quality, you may even end up misleading others. That’s why we see a lot of “myths” today. It’s one thing to create a “clickbait” title, but creating a clickbait title and spewing myths is on a completely different level.
Now let’s say you can’t do any more research because it’s out of your power to be able to do so. What can you do about the data that’s missing in your dataset? You can remove some parts of your data which may cause bias, but what if you don’t have much data to work with so you can’t afford to remove data? That’s when you find other means and look into imputing values to replace missing data.
What is imputation? As defined in Wikipedia,
In statistics, imputation is the process of replacing missing data with substituted values.
As stated earlier, we can replace (impute) missing values using several different approaches. The approaches boil down to two different categories of imputation algorithms: univariate imputation and multivariate imputation2.
Single imputation methods are known as univariate imputation. As stated in scikit-learn’s documentation:
One type of imputation algorithm is univariate, which imputes values in the i-th feature dimension using only non-missing values in that feature dimension.
This means that univariate imputation methods only use the non-missing values in a chosen feature (chosen by you), and impute the missing values in the same feature using either a constant that you provide or by using a statistical measurement (mean/median/mode) of that chosen feature.
For example, in Python, a simple one-liner would do the justice:
>>> data['chosenFeature'].fillna(data['chosenFeature'].mean(), inplace = True)"""Where `data` is your dataset and `chosenFeature` is the column that you choose to replace the missing NaN values for by using the current mean of the non-missing values in the column."""
You can also use scikit-learn’s SimpleImputer class to impute missing values. To learn more about this class, click here.
Multiple imputations can be used in cases where the data are MCAR, MAR, and even when the data are MNAR. Multiple imputation methods are known as multivariate imputation.
Multivariate imputation algorithms use the entire set of available feature dimensions to estimate the missing values.
Basically, the purpose of multivariate imputation is to use other features (columns) in the dataset to predict the missing value(s) in the current feature.
You may be thinking “Well Gifari, you’re telling me that multiple imputation algorithms use other columns, but how does the algorithm know which feature to choose first to impute values on if we have multiple features (columns) with missing values?” Hold your horses there, Billy (no offense to all the Billy’s out there), that’s a very good question, and I’ll get into that in the next chapter where I’ll talk about how you can be the chosen one.
Single imputation methods, as you may have guessed, don’t take uncertainty into account. Single imputation methods don’t care about “what ifs”; it has just one goal: to get rid of missing values. This is when we use multiple imputation methods, where not only are we getting rid of missing values, we’re also considering the “what ifs”.
Although the methodology of multiple imputations may sound difficult to implement, this is the 21st century, where our lives are the most technologically advanced it’s ever been. If you’re reading this from the 22nd, hopefully Medium started supporting superscripts of letters and subscripts by then, and thank you for taking the time to read this article, but I don’t think you should be here. I’m pretty sure there’re more advanced imputation methods in your century and thereon.
There are several statistical packages available which allow you to easily perform multiple imputations. For example, if you’re programming in R, then you have the MICE (Multivariate Imputation by Chained Equations) or the missForest packages readily available for your use. If you’re programming in Python, you have scikit-learn’s IterativeImputer package, which was originally inspired by the MICE package in R.
Iterative Imputer is a multivariate imputing strategy that models a column with the missing values (target variable) as a function of other features (predictor variables) in a round-robin fashion and uses that estimate for imputation. The source code can be found on GitHub by clicking here.
NOTE: This estimator is still experimental for now: the predictions and the API might change without any deprecation cycle. To use it, you need to explicitly import enable_iterative_imputer:
>>> # explicitly require this experimental feature>>> from sklearn.experimental import enable_iterative_imputer # noqa>>> # now you can import normally from sklearn.impute>>> from sklearn.impute import IterativeImputer
There are a number of parameters that you can see in IterativeImputer’s documentations. It requires no parameter inputs as the default parameters are already set for you, meaning that, after you finish importing necessary packages, you can simply introduce an Iterative Imputer by running:
imp = IterativeImputer()
The “current feature” is chosen based on the imputation_order given where the default order is “ascending.” This means that the feature chosen first will be the feature containing the least missing values. After imputing all missing values in the chosen feature, the feature no longer contains missing values, so it is no longer the feature with the least missing values, hence the imputer will move onto the next feature with the least missing values.
The other orders are:
“descending”: features with most missing values to fewest
“roman”: left features to right features
“arabic”: right features to left features
“random”: a random order for each round
Now that you know how to be the “Chosen One”, let’s understand the process behind the iterations.
Iterative Imputer initially initializes the missing values with the value passed for initial_strategy, where the initial strategy is the “mean” for each feature. The imputer then uses an estimator (where the default estimator used is Bayesian Ridge) at each step of the round-robin imputation. At each step, a feature column is chosen as the target variable y and the other feature columns are treated as predictor variables X. The missing values are then predicted for each feature. This process is repeated for at most “max_iter” number of times, where the default is 10 times (rounds). The reason why I say “at most” and not “exactly” is because early stopping is enabled due to the default parameterization of sample_posterior=False.
The stopping criterion is met once max(abs(X_t-X_{t-1}))/max(abs(X[known_vals])) < tol, where X_t is X at iteration t.
This essentially means that for a single missing value, there are at most max_iter number of predictions and the iterations stop once the difference between the previous iteration prediction and current iteration prediction for a value is smaller than the given tol value (default = 1e-3).
You can mess around with several other parameters, so be sure to try them out on your own dataset! Now enough of this nerdy stuff, let’s see some action.
Now that you have somewhat of an understanding of IterativeImputer, let me introduce you to two different datasets that I’ll be using as examples:
PIMA Indians Diabetes Database: For the first example, I’m going to be using the diabetes dataset which can be found on Kaggle by clicking here. You can also view my notebook on Kaggle which can be used hand in hand along with this example. You can view/edit the notebook by clicking here.
The notebook focuses more on different imputation methods as well as what I call “hybrid methods” for imputing missing values. In the end, it compares the accuracy scores of multiple models training on the different datasets derived from the different imputation methods. It’s a lengthy notebook, but I was very interested in this project. It was created as a machine learning and iterative imputer tutorial.
Stock Market Data: For the second example, I’ll be using Iterative Imputer on the stock market data. Unfortunately, this example will have to have its own article due to the amount of information. I don’t want to spoil this yet as I found this very interesting. I’ve also made a notebook for this example on Kaggle after writing this article which uses functions to simplify the process which I’ll be going over in the second article. You can play along with the notebook by clicking here.
Click here to read the second article. I would really like it if you check it out after finishing reading this one!
I lied when I said I was done with the nerdy stuff. I can’t help it sometimes. How about a little pre-game before proceeding into my first example?
When you impute a single digit to missing values within a feature, depending on how much of your data is missing in the certain feature, you increase the likelihood of causing your data to have more kurtosis. Kurtosis is the measurement of the “tailedness” of the distribution. Like skewness, kurtosis is another measurement used to describe the shape of the data distribution. For simplicity, when one thinks of how “symmetrical” the distribution is, they usually think about the skewness of the data. When one thinks about how “curvy” or “pointy” the distribution is, they usually think about the kurtosis of the data. Here is a visual example of the differences in skewness/kurtosis of a distribution that I’ve coded (weird flex but ok):
The kurtosis of any univariate normal distribution is three (when not using Fisher’s definition)3. To learn more about skewness and kurtosis, click here.
Now you’re ready to head to the party.
For my first example, I’ll be using the PIMA Indians Diabetes Database which can be found on Kaggle, for free. The dataset contains several missing values throughout the dataset (which are masked by zeros). My updated dataset replaces the zeros with NaNs. In particular, I’ll only be working with two features that had the most missing values: “SkinThickness” and “Insulin”. More specifically, out of the 768 rows in this dataset, “SkinThickness” had 227 missing values, and “Insulin” had 374 missing values. Isn’t that crazy.
Note: You don’t need to know the importance of these two features for this example.
I’ve created a notebook on Kaggle which can be used hand in hand with this article. The notebook dives more into different imputation methods including what I like to call, “hybrid methods”. The notebook was created as a machine learning and iterative imputer tutorial, and you can view/edit the notebook by clicking here.
Let’s now look at the distribution of these two features:
The skewness and kurtosis for these two distributions are as follows:
Skewness for “SkinThickness”: 0.690619
Skewness for “Insulin”: 2.166464
Kurtosis for “SkinThickness”: 2.935491
Kurtosis for “Insulin”: 6.370522
Let’s now see how our distribution plot, skewness, and kurtosis change after doing a mean-imputation to our missing values. Without even thinking, we can imagine our distribution plots for both features having more kurtosis because we’re imputing a single value 227 times for “SkinThickness” and a single different value 374 times for “Insulin” (when we only have 768 rows to work with).
Note: The mean for “SkinThickness” is 29.153420 and the mean for “Insulin” is 155.548223.This is for our dataset with NaNs.
The skewness and kurtosis for these two distributions are as follows:
Skewness for “SkinThickness”: 0.837608
Skewness for “Insulin”: 3.380019
Kurtosis for “SkinThickness”: 5.430987
Kurtosis for “Insulin”: 16.232455
Without a surprise, we see S̶O̶M̶E̶ A DRASTIC rise in kurtosis, especially for “Insulin”.
Let’s now use IterativeImputer to impute the missing values for these two features in our dataset containing NaNs. I’ll be using RandomForestRegressor() as the estimator for IterativeImputer.
# Introduce IterativeImputer with an estimator>>> imp = IterativeImputer(estimator=RandomForestRegressor())# Fit to the dataset containing missing values>>> imp.fit(ndf)# Transform the dataset containing missing values>>> df = pd.DataFrame(imp.transform(ndf), columns = ndf.columns)"""Where `ndf` is the dataset containing missing values"""
Let’s now look at the distribution for the two features after imputations.
The skewness and kurtosis for these two distributions are as follows:
Skewness for “SkinThickness”: 0.679155
Skewness for “Insulin”: 2.052863
Kurtosis for “SkinThickness”: 3.039844
Kurtosis for “Insulin”: 6.778861
We can see that the kurtosis for both features isn’t as crazy as they were when we imputed the mean of the two features to their corresponding missing values. Not only that, we can see that the skewness and kurtosis levels for both features stayed relatively similar to the levels in which the dataset containing NaNs had.
In general, the multivariate approach is preferred over the univariate approach, but I personally think this depends on your own needs and goals for your project. In this article, we saw the difference between a mean-imputation and iterative imputation using the PIMA Indians Diabetes Database. In the second article, you will be able to see how another way of using IterativeImputer by using the stock market data.
I do hope that reading this article was worth your time. This was my first article written on Medium, but as far as I can see, it won’t be my last. I highly encourage you to check out the second part of this article by clicking on the link below. I hope you can make use of IterativeImputer, and I hope that you find at least one of my two examples to be useful.
gifari.medium.com
Feel free to check out my notebook which I’ve written on Kaggle for where I go more in depth on IterativeImputer on the PIMA Indians Diabetes Database.
www.kaggle.com
[1]: Wikipedia. Missing Data (click to go back)
[2]: Scikit-learn. Imputation of Missing Values (click to go back)
[3]: Wikipedia. Kurtosis (click to go back)
If you notice any errors in my article, please do leave a comment and reach out to me so I can get it fixed ASAP! I don’t want to mislead anyone or teach anyone the wrong. To me, any criticism is positive criticism, that’s one of the best ways I learn. I’m also always open to tips and suggestions.
If you enjoyed reading this article, follow me on Medium and Kaggle where I’ll be posting more content from time to time. Also, feel free to connect with me on LinkedIn. If you think I deserve a coffee for my work, please do buy me one! Any support helps me keep going.
As always, thanks again for stopping by.
|
[
{
"code": null,
"e": 540,
"s": 172,
"text": "IntroductionReasoning with MissingnessHow does it work?- Univariate Imputation- Multivariate ImputationIterative Imputer- How to be the “Chosen One”- The Process Behind the IterationsGetting Started- The Problem with Single Imputation MethodsHow Single Imputation vs. Iterative Imputation can Affect the Distribution of Your DatasetConclusion- References- Final Words"
},
{
"code": null,
"e": 553,
"s": 540,
"text": "Introduction"
},
{
"code": null,
"e": 580,
"s": 553,
"text": "Reasoning with Missingness"
},
{
"code": null,
"e": 646,
"s": 580,
"text": "How does it work?- Univariate Imputation- Multivariate Imputation"
},
{
"code": null,
"e": 727,
"s": 646,
"text": "Iterative Imputer- How to be the “Chosen One”- The Process Behind the Iterations"
},
{
"code": null,
"e": 787,
"s": 727,
"text": "Getting Started- The Problem with Single Imputation Methods"
},
{
"code": null,
"e": 878,
"s": 787,
"text": "How Single Imputation vs. Iterative Imputation can Affect the Distribution of Your Dataset"
},
{
"code": null,
"e": 914,
"s": 878,
"text": "Conclusion- References- Final Words"
},
{
"code": null,
"e": 1181,
"s": 914,
"text": "Missing data is a major problem when it comes to making profitable business decisions, solving health problems, better understanding a population, etc. Not only is missing data a problem for humans, but it’s also a big problem for the machine we feed the dataset to."
},
{
"code": null,
"e": 1911,
"s": 1181,
"text": "Here’s a hypothetical situation: imagine your boss handing you a book with a number of pages missing every few pages. And now imagine that you HAVE to read the book and give your analysis for each chapter, and a final analysis for the whole book no matter what or you’ll get fired. Now, this may not be surprising for some of you, as some of you may have bosses that actually make you do similar things like this, but how exactly would you handle this situation? Without asking any questions, you accept the task and carry on. I know, now you’re thinking, “I’ll just search this book up online,” and you do. You search everywhere, only to find out that this book doesn’t exist anywhere else, except on your desk right beside you."
},
{
"code": null,
"e": 2464,
"s": 1911,
"text": "You’re only left with one choice, and so, you start to read. You come across the first missing page as you see a torn page in the middle of the book. The book jumps from page number 14 to page number 17. You shrug it off and continue on with the book while also making assumptions about what could’ve possibly happened on pages 15–16. You continue on reading the book and you encounter more missing pages, except now, the book jumps from page 38 to page 45. You can’t believe your eyes, as you start to read page 45. The story is no longer adding up..."
},
{
"code": null,
"e": 2763,
"s": 2464,
"text": "You eventually reach the near end of the book and you find out that the ending is not actually the ending. That’s right, a few more pages missing in the end. Having “finished” the book, you look back at the analyses you’ve made for each chapter to try to make a conclusion of your own for the book."
},
{
"code": null,
"e": 3004,
"s": 2763,
"text": "Your dataset is like a story that you give your machine learning model to read, and each row is like a chapter. If your dataset has missing values, your model won’t be able to fully understand what’s going on and may make false predictions."
},
{
"code": null,
"e": 3288,
"s": 3004,
"text": "There are several ways of handling missing data including, but not limited to: ignoring the missing data, removing the row/column depending on the mass of missingness in the row/column, replacement with a single digit (0, 1, any other number, mean, median), grouped replacement, etc."
},
{
"code": null,
"e": 3487,
"s": 3288,
"text": "Having a better understanding of the reasoning for the missingness of your data can help you determine what type of imputation method you can use. In general, there are three types of missing data1:"
},
{
"code": null,
"e": 3912,
"s": 3487,
"text": "Missing Completely At Random (MCAR): The values in your dataset are missing completely at random. This is when there is no clear reasoning as to why a certain value in your dataset is missing. An example of this is if a surveyee forgets to answer a question on a voluntary survey. Handling this situation is relatively simple, we can replace the missing data with a mean/median replacement — the data missing is recoverable."
},
{
"code": null,
"e": 4331,
"s": 3912,
"text": "Missing At Random (MAR): The values in your dataset are missing at random. This is when we can determine some correlation to why the data value may be missing. An example of this is if a certain question in a survey is blank for multiple surveyees of the same gender. A way in which we can handle this situation is by using other features to do a grouped mean/median replacement— the data missing is still recoverable."
},
{
"code": null,
"e": 4840,
"s": 4331,
"text": "Missing Not At Random (MNAR): The values in your dataset are not missing at random. This is when we can see a clear pattern to the missing values. An example of this is if a certain question category in a survey is left blank by surveyees because of the question itself, as it may be a sensitive question to the surveyee (the missingness depends on the missing data) — the data missing will be hard to recover unless further research is done. Unlike the other two types of missing data, MNAR is nonignorable."
},
{
"code": null,
"e": 5024,
"s": 4840,
"text": "Before I get into the fun stuff, I’ll have to do a bit more explaining so grab a cup of coffee or a scoop of pre-workout (or two 😏) or whatever you’re into because it’s time to focus."
},
{
"code": null,
"e": 5053,
"s": 5024,
"text": "Let’s start with the basics."
},
{
"code": null,
"e": 5700,
"s": 5053,
"text": "Missing data can cause research or experiments to be biased, can make data analysis more gruesome, and can reduce the quality of your hypothesis testing and results. It’s always better to do more research to reduce your data biases than just say “whatever” and continue on to your analysis. In my opinion, this defeats the purpose of why you first started your experimentation. In the end, not only will your results have bad quality, you may even end up misleading others. That’s why we see a lot of “myths” today. It’s one thing to create a “clickbait” title, but creating a clickbait title and spewing myths is on a completely different level."
},
{
"code": null,
"e": 6095,
"s": 5700,
"text": "Now let’s say you can’t do any more research because it’s out of your power to be able to do so. What can you do about the data that’s missing in your dataset? You can remove some parts of your data which may cause bias, but what if you don’t have much data to work with so you can’t afford to remove data? That’s when you find other means and look into imputing values to replace missing data."
},
{
"code": null,
"e": 6140,
"s": 6095,
"text": "What is imputation? As defined in Wikipedia,"
},
{
"code": null,
"e": 6232,
"s": 6140,
"text": "In statistics, imputation is the process of replacing missing data with substituted values."
},
{
"code": null,
"e": 6457,
"s": 6232,
"text": "As stated earlier, we can replace (impute) missing values using several different approaches. The approaches boil down to two different categories of imputation algorithms: univariate imputation and multivariate imputation2."
},
{
"code": null,
"e": 6562,
"s": 6457,
"text": "Single imputation methods are known as univariate imputation. As stated in scikit-learn’s documentation:"
},
{
"code": null,
"e": 6718,
"s": 6562,
"text": "One type of imputation algorithm is univariate, which imputes values in the i-th feature dimension using only non-missing values in that feature dimension."
},
{
"code": null,
"e": 7005,
"s": 6718,
"text": "This means that univariate imputation methods only use the non-missing values in a chosen feature (chosen by you), and impute the missing values in the same feature using either a constant that you provide or by using a statistical measurement (mean/median/mode) of that chosen feature."
},
{
"code": null,
"e": 7070,
"s": 7005,
"text": "For example, in Python, a simple one-liner would do the justice:"
},
{
"code": null,
"e": 7338,
"s": 7070,
"text": ">>> data['chosenFeature'].fillna(data['chosenFeature'].mean(), inplace = True)\"\"\"Where `data` is your dataset and `chosenFeature` is the column that you choose to replace the missing NaN values for by using the current mean of the non-missing values in the column.\"\"\""
},
{
"code": null,
"e": 7460,
"s": 7338,
"text": "You can also use scikit-learn’s SimpleImputer class to impute missing values. To learn more about this class, click here."
},
{
"code": null,
"e": 7631,
"s": 7460,
"text": "Multiple imputations can be used in cases where the data are MCAR, MAR, and even when the data are MNAR. Multiple imputation methods are known as multivariate imputation."
},
{
"code": null,
"e": 7749,
"s": 7631,
"text": "Multivariate imputation algorithms use the entire set of available feature dimensions to estimate the missing values."
},
{
"code": null,
"e": 7905,
"s": 7749,
"text": "Basically, the purpose of multivariate imputation is to use other features (columns) in the dataset to predict the missing value(s) in the current feature."
},
{
"code": null,
"e": 8353,
"s": 7905,
"text": "You may be thinking “Well Gifari, you’re telling me that multiple imputation algorithms use other columns, but how does the algorithm know which feature to choose first to impute values on if we have multiple features (columns) with missing values?” Hold your horses there, Billy (no offense to all the Billy’s out there), that’s a very good question, and I’ll get into that in the next chapter where I’ll talk about how you can be the chosen one."
},
{
"code": null,
"e": 8690,
"s": 8353,
"text": "Single imputation methods, as you may have guessed, don’t take uncertainty into account. Single imputation methods don’t care about “what ifs”; it has just one goal: to get rid of missing values. This is when we use multiple imputation methods, where not only are we getting rid of missing values, we’re also considering the “what ifs”."
},
{
"code": null,
"e": 9172,
"s": 8690,
"text": "Although the methodology of multiple imputations may sound difficult to implement, this is the 21st century, where our lives are the most technologically advanced it’s ever been. If you’re reading this from the 22nd, hopefully Medium started supporting superscripts of letters and subscripts by then, and thank you for taking the time to read this article, but I don’t think you should be here. I’m pretty sure there’re more advanced imputation methods in your century and thereon."
},
{
"code": null,
"e": 9586,
"s": 9172,
"text": "There are several statistical packages available which allow you to easily perform multiple imputations. For example, if you’re programming in R, then you have the MICE (Multivariate Imputation by Chained Equations) or the missForest packages readily available for your use. If you’re programming in Python, you have scikit-learn’s IterativeImputer package, which was originally inspired by the MICE package in R."
},
{
"code": null,
"e": 9878,
"s": 9586,
"text": "Iterative Imputer is a multivariate imputing strategy that models a column with the missing values (target variable) as a function of other features (predictor variables) in a round-robin fashion and uses that estimate for imputation. The source code can be found on GitHub by clicking here."
},
{
"code": null,
"e": 10069,
"s": 9878,
"text": "NOTE: This estimator is still experimental for now: the predictions and the API might change without any deprecation cycle. To use it, you need to explicitly import enable_iterative_imputer:"
},
{
"code": null,
"e": 10288,
"s": 10069,
"text": ">>> # explicitly require this experimental feature>>> from sklearn.experimental import enable_iterative_imputer # noqa>>> # now you can import normally from sklearn.impute>>> from sklearn.impute import IterativeImputer"
},
{
"code": null,
"e": 10578,
"s": 10288,
"text": "There are a number of parameters that you can see in IterativeImputer’s documentations. It requires no parameter inputs as the default parameters are already set for you, meaning that, after you finish importing necessary packages, you can simply introduce an Iterative Imputer by running:"
},
{
"code": null,
"e": 10603,
"s": 10578,
"text": "imp = IterativeImputer()"
},
{
"code": null,
"e": 11056,
"s": 10603,
"text": "The “current feature” is chosen based on the imputation_order given where the default order is “ascending.” This means that the feature chosen first will be the feature containing the least missing values. After imputing all missing values in the chosen feature, the feature no longer contains missing values, so it is no longer the feature with the least missing values, hence the imputer will move onto the next feature with the least missing values."
},
{
"code": null,
"e": 11078,
"s": 11056,
"text": "The other orders are:"
},
{
"code": null,
"e": 11136,
"s": 11078,
"text": "“descending”: features with most missing values to fewest"
},
{
"code": null,
"e": 11177,
"s": 11136,
"text": "“roman”: left features to right features"
},
{
"code": null,
"e": 11219,
"s": 11177,
"text": "“arabic”: right features to left features"
},
{
"code": null,
"e": 11259,
"s": 11219,
"text": "“random”: a random order for each round"
},
{
"code": null,
"e": 11357,
"s": 11259,
"text": "Now that you know how to be the “Chosen One”, let’s understand the process behind the iterations."
},
{
"code": null,
"e": 12095,
"s": 11357,
"text": "Iterative Imputer initially initializes the missing values with the value passed for initial_strategy, where the initial strategy is the “mean” for each feature. The imputer then uses an estimator (where the default estimator used is Bayesian Ridge) at each step of the round-robin imputation. At each step, a feature column is chosen as the target variable y and the other feature columns are treated as predictor variables X. The missing values are then predicted for each feature. This process is repeated for at most “max_iter” number of times, where the default is 10 times (rounds). The reason why I say “at most” and not “exactly” is because early stopping is enabled due to the default parameterization of sample_posterior=False."
},
{
"code": null,
"e": 12214,
"s": 12095,
"text": "The stopping criterion is met once max(abs(X_t-X_{t-1}))/max(abs(X[known_vals])) < tol, where X_t is X at iteration t."
},
{
"code": null,
"e": 12504,
"s": 12214,
"text": "This essentially means that for a single missing value, there are at most max_iter number of predictions and the iterations stop once the difference between the previous iteration prediction and current iteration prediction for a value is smaller than the given tol value (default = 1e-3)."
},
{
"code": null,
"e": 12658,
"s": 12504,
"text": "You can mess around with several other parameters, so be sure to try them out on your own dataset! Now enough of this nerdy stuff, let’s see some action."
},
{
"code": null,
"e": 12805,
"s": 12658,
"text": "Now that you have somewhat of an understanding of IterativeImputer, let me introduce you to two different datasets that I’ll be using as examples:"
},
{
"code": null,
"e": 13095,
"s": 12805,
"text": "PIMA Indians Diabetes Database: For the first example, I’m going to be using the diabetes dataset which can be found on Kaggle by clicking here. You can also view my notebook on Kaggle which can be used hand in hand along with this example. You can view/edit the notebook by clicking here."
},
{
"code": null,
"e": 13504,
"s": 13095,
"text": "The notebook focuses more on different imputation methods as well as what I call “hybrid methods” for imputing missing values. In the end, it compares the accuracy scores of multiple models training on the different datasets derived from the different imputation methods. It’s a lengthy notebook, but I was very interested in this project. It was created as a machine learning and iterative imputer tutorial."
},
{
"code": null,
"e": 13994,
"s": 13504,
"text": "Stock Market Data: For the second example, I’ll be using Iterative Imputer on the stock market data. Unfortunately, this example will have to have its own article due to the amount of information. I don’t want to spoil this yet as I found this very interesting. I’ve also made a notebook for this example on Kaggle after writing this article which uses functions to simplify the process which I’ll be going over in the second article. You can play along with the notebook by clicking here."
},
{
"code": null,
"e": 14110,
"s": 13994,
"text": "Click here to read the second article. I would really like it if you check it out after finishing reading this one!"
},
{
"code": null,
"e": 14258,
"s": 14110,
"text": "I lied when I said I was done with the nerdy stuff. I can’t help it sometimes. How about a little pre-game before proceeding into my first example?"
},
{
"code": null,
"e": 14999,
"s": 14258,
"text": "When you impute a single digit to missing values within a feature, depending on how much of your data is missing in the certain feature, you increase the likelihood of causing your data to have more kurtosis. Kurtosis is the measurement of the “tailedness” of the distribution. Like skewness, kurtosis is another measurement used to describe the shape of the data distribution. For simplicity, when one thinks of how “symmetrical” the distribution is, they usually think about the skewness of the data. When one thinks about how “curvy” or “pointy” the distribution is, they usually think about the kurtosis of the data. Here is a visual example of the differences in skewness/kurtosis of a distribution that I’ve coded (weird flex but ok):"
},
{
"code": null,
"e": 15153,
"s": 14999,
"text": "The kurtosis of any univariate normal distribution is three (when not using Fisher’s definition)3. To learn more about skewness and kurtosis, click here."
},
{
"code": null,
"e": 15192,
"s": 15153,
"text": "Now you’re ready to head to the party."
},
{
"code": null,
"e": 15719,
"s": 15192,
"text": "For my first example, I’ll be using the PIMA Indians Diabetes Database which can be found on Kaggle, for free. The dataset contains several missing values throughout the dataset (which are masked by zeros). My updated dataset replaces the zeros with NaNs. In particular, I’ll only be working with two features that had the most missing values: “SkinThickness” and “Insulin”. More specifically, out of the 768 rows in this dataset, “SkinThickness” had 227 missing values, and “Insulin” had 374 missing values. Isn’t that crazy."
},
{
"code": null,
"e": 15803,
"s": 15719,
"text": "Note: You don’t need to know the importance of these two features for this example."
},
{
"code": null,
"e": 16126,
"s": 15803,
"text": "I’ve created a notebook on Kaggle which can be used hand in hand with this article. The notebook dives more into different imputation methods including what I like to call, “hybrid methods”. The notebook was created as a machine learning and iterative imputer tutorial, and you can view/edit the notebook by clicking here."
},
{
"code": null,
"e": 16184,
"s": 16126,
"text": "Let’s now look at the distribution of these two features:"
},
{
"code": null,
"e": 16254,
"s": 16184,
"text": "The skewness and kurtosis for these two distributions are as follows:"
},
{
"code": null,
"e": 16293,
"s": 16254,
"text": "Skewness for “SkinThickness”: 0.690619"
},
{
"code": null,
"e": 16326,
"s": 16293,
"text": "Skewness for “Insulin”: 2.166464"
},
{
"code": null,
"e": 16365,
"s": 16326,
"text": "Kurtosis for “SkinThickness”: 2.935491"
},
{
"code": null,
"e": 16398,
"s": 16365,
"text": "Kurtosis for “Insulin”: 6.370522"
},
{
"code": null,
"e": 16786,
"s": 16398,
"text": "Let’s now see how our distribution plot, skewness, and kurtosis change after doing a mean-imputation to our missing values. Without even thinking, we can imagine our distribution plots for both features having more kurtosis because we’re imputing a single value 227 times for “SkinThickness” and a single different value 374 times for “Insulin” (when we only have 768 rows to work with)."
},
{
"code": null,
"e": 16910,
"s": 16786,
"text": "Note: The mean for “SkinThickness” is 29.153420 and the mean for “Insulin” is 155.548223.This is for our dataset with NaNs."
},
{
"code": null,
"e": 16980,
"s": 16910,
"text": "The skewness and kurtosis for these two distributions are as follows:"
},
{
"code": null,
"e": 17019,
"s": 16980,
"text": "Skewness for “SkinThickness”: 0.837608"
},
{
"code": null,
"e": 17052,
"s": 17019,
"text": "Skewness for “Insulin”: 3.380019"
},
{
"code": null,
"e": 17091,
"s": 17052,
"text": "Kurtosis for “SkinThickness”: 5.430987"
},
{
"code": null,
"e": 17125,
"s": 17091,
"text": "Kurtosis for “Insulin”: 16.232455"
},
{
"code": null,
"e": 17215,
"s": 17125,
"text": "Without a surprise, we see S̶O̶M̶E̶ A DRASTIC rise in kurtosis, especially for “Insulin”."
},
{
"code": null,
"e": 17407,
"s": 17215,
"text": "Let’s now use IterativeImputer to impute the missing values for these two features in our dataset containing NaNs. I’ll be using RandomForestRegressor() as the estimator for IterativeImputer."
},
{
"code": null,
"e": 17748,
"s": 17407,
"text": "# Introduce IterativeImputer with an estimator>>> imp = IterativeImputer(estimator=RandomForestRegressor())# Fit to the dataset containing missing values>>> imp.fit(ndf)# Transform the dataset containing missing values>>> df = pd.DataFrame(imp.transform(ndf), columns = ndf.columns)\"\"\"Where `ndf` is the dataset containing missing values\"\"\""
},
{
"code": null,
"e": 17823,
"s": 17748,
"text": "Let’s now look at the distribution for the two features after imputations."
},
{
"code": null,
"e": 17893,
"s": 17823,
"text": "The skewness and kurtosis for these two distributions are as follows:"
},
{
"code": null,
"e": 17932,
"s": 17893,
"text": "Skewness for “SkinThickness”: 0.679155"
},
{
"code": null,
"e": 17965,
"s": 17932,
"text": "Skewness for “Insulin”: 2.052863"
},
{
"code": null,
"e": 18004,
"s": 17965,
"text": "Kurtosis for “SkinThickness”: 3.039844"
},
{
"code": null,
"e": 18037,
"s": 18004,
"text": "Kurtosis for “Insulin”: 6.778861"
},
{
"code": null,
"e": 18360,
"s": 18037,
"text": "We can see that the kurtosis for both features isn’t as crazy as they were when we imputed the mean of the two features to their corresponding missing values. Not only that, we can see that the skewness and kurtosis levels for both features stayed relatively similar to the levels in which the dataset containing NaNs had."
},
{
"code": null,
"e": 18776,
"s": 18360,
"text": "In general, the multivariate approach is preferred over the univariate approach, but I personally think this depends on your own needs and goals for your project. In this article, we saw the difference between a mean-imputation and iterative imputation using the PIMA Indians Diabetes Database. In the second article, you will be able to see how another way of using IterativeImputer by using the stock market data."
},
{
"code": null,
"e": 19139,
"s": 18776,
"text": "I do hope that reading this article was worth your time. This was my first article written on Medium, but as far as I can see, it won’t be my last. I highly encourage you to check out the second part of this article by clicking on the link below. I hope you can make use of IterativeImputer, and I hope that you find at least one of my two examples to be useful."
},
{
"code": null,
"e": 19157,
"s": 19139,
"text": "gifari.medium.com"
},
{
"code": null,
"e": 19309,
"s": 19157,
"text": "Feel free to check out my notebook which I’ve written on Kaggle for where I go more in depth on IterativeImputer on the PIMA Indians Diabetes Database."
},
{
"code": null,
"e": 19324,
"s": 19309,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 19372,
"s": 19324,
"text": "[1]: Wikipedia. Missing Data (click to go back)"
},
{
"code": null,
"e": 19439,
"s": 19372,
"text": "[2]: Scikit-learn. Imputation of Missing Values (click to go back)"
},
{
"code": null,
"e": 19483,
"s": 19439,
"text": "[3]: Wikipedia. Kurtosis (click to go back)"
},
{
"code": null,
"e": 19782,
"s": 19483,
"text": "If you notice any errors in my article, please do leave a comment and reach out to me so I can get it fixed ASAP! I don’t want to mislead anyone or teach anyone the wrong. To me, any criticism is positive criticism, that’s one of the best ways I learn. I’m also always open to tips and suggestions."
},
{
"code": null,
"e": 20052,
"s": 19782,
"text": "If you enjoyed reading this article, follow me on Medium and Kaggle where I’ll be posting more content from time to time. Also, feel free to connect with me on LinkedIn. If you think I deserve a coffee for my work, please do buy me one! Any support helps me keep going."
}
] |
Data Preprocessing with Python Pandas — Part 3 Normalisation | by Angelica Lo Duca | Towards Data Science
|
This tutorial explains how to preprocess data using the Pandas library. Preprocessing is the process of doing a pre-analysis of data, in order to transform them into a standard and normalised format. Preprocessing involves the following aspects:
missing values
data formatting
data normalisation
data standardisation
data binning
In this tutorial we deal only with normalisation. In my previous tutorials I dealt with missing values and data formatting.
Data Normalisation involves adjusting values measured on different scales to a common scale. When dealing with dataframes, data normalization permits to adjust values referred to different columns to a common scale. This operation is strongly recommended when the columns of a dataframe are considered as input features of a machine learning algorithm, because it permits to give all the features the same weight.
Normalization applies only to columns containing numeric values. Five methods of normalization exist:
single feature scaling
min max
z-score
log scaling
clipping
In the remainder of the tutorial, we apply each method to a single column. However, if you wanted to use each column of the dataset as input features of a machine learning algorithm, you should apply the same normalisation method to all the columns.
In this tutorial, we use the pandas library to perform normalization. As an alternative, you could use the preprocessing methods of the scikit-learn libray. A little note for readers: if you wanted to learn how to use the preprocessing package of scikit-learn, please drop me a message or a comment to this post :)
You can download the source code of this tutorial as a Jupyter notebook from my Github Data Science Repository.
As example dataset, in this tutorial we consider the dataset provided by the Italian Protezione Civile, related to the number of COVID-19 cases registered since the beginning of the COVID-19 pandemic. The dataset is updated daily and can be downloaded from this link.
First of all, we need to import the Python pandas library and read the dataset through the read_csv() function. Then we can drop all the columns with NaN values. This is done through dropna() function.
import pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv')df.dropna(axis=1,inplace=True)df.head(10)
Single Feature Scaling converts every value of a column into a number between 0 and 1. The new value is calculated as the current value divided by the max value of the column. For example, if we consider the column tamponi, we can apply the single feature scaling by applying to the column the function max(), whic calculates the maximum value of the column:
df['tamponi'] = df['tamponi']/df['tamponi'].max()
Similarly to Single Feature Scaling, Min Max converts every value of a column into a number between 0 and 1. The new value is calculated as the difference between the current value and the min value, divided by the range of the column values. For example, we can apply the min max method to the column totale_casi.
df['totale_casi'] = (df['totale_casi'] - df['totale_casi'].min())/(df['totale_casi'].max() - df['totale_casi'].min())
Z-Score converts every value of a column into a number around 0. Typical values obtained by a z-score transformation range from -3 and 3. The new value is calculated as the difference between the current value and the average value, divided by the standard deviation. The average value of a column can be obtained through the mean() function, while the standard deviation through the std() function. For example, we can calculate the z-score of the column deceduti.
df['deceduti'] = (df['deceduti']-df['deceduti'].mean())/df['deceduti'].std()
Now we can calculate the minimum and maximum value obtained by the z-score transformation:
df['deceduti'].min()
which gives the following output:
-0.4329770144818199
and:
df['deceduti'].max()
which gives the following output:
5.945028962275545
Log Scaling involves the conversion of a column to the logarithmic scale. If we want to use the natural logarithm, we can use the log() function of the numpy library. For example, we can apply log scaling to the column dimessi_guariti. We must deal with log(0) because it does not exist. We use the lambda operator to select the single rows of the column.
import numpy as npdf['dimessi_guariti'] = df['dimessi_guariti'].apply(lambda x: np.log(x) if x != 0 else 0)
which gives the following output:
0 0.0000001 0.0000002 0.0000003 0.0000004 0.000000 ... 5812 9.8463885813 10.7942965814 9.4740885815 8.3728615816 10.922389Name: dimessi_guariti, Length: 5817, dtype: float64
Clipping involves the capping of all values below or above a certain value. Clipping is useful when a column contains some outliers. We can set a maximum vmax and a minimum value vmin and set all outliers greater than the maximum value to vmax and all the outliers lower than the minimum value to vmin. For example, we can consider the column ricoverati_con_sintomi and we can set vmax = 10000 and vmin = 10.
vmax = 10000vmin = 10df['ricoverati_con_sintomi'] = df['ricoverati_con_sintomi'].apply(lambda x: vmax if x > vmax else vmin if x < vmin else x)
In this tutorial, I have shown you the different techniques used to perform data normalisation: single feature scaling: min max, z-score, log scaling, clipping. Thus, the question is: what is the best technique? Actually, there is not a technique better than the others, the choice of a method rather than another depends on what we want as output. Thus:
if you want an output between 0 and 1, you should use single feature scaling or min max
if you want an output around 0, which includes also negative values, you should use z-score
if your data contain many outliers, you can use clipping
if you want to change the scale of your data, you can use the log scaling.
If you would like to learn about the other aspects of data preprocessing, such as data binning and data standardisation, stay tuned...
If you wanted to be updated on my research and other activities, you can follow me on Twitter, Youtube and Github.
|
[
{
"code": null,
"e": 418,
"s": 172,
"text": "This tutorial explains how to preprocess data using the Pandas library. Preprocessing is the process of doing a pre-analysis of data, in order to transform them into a standard and normalised format. Preprocessing involves the following aspects:"
},
{
"code": null,
"e": 433,
"s": 418,
"text": "missing values"
},
{
"code": null,
"e": 449,
"s": 433,
"text": "data formatting"
},
{
"code": null,
"e": 468,
"s": 449,
"text": "data normalisation"
},
{
"code": null,
"e": 489,
"s": 468,
"text": "data standardisation"
},
{
"code": null,
"e": 502,
"s": 489,
"text": "data binning"
},
{
"code": null,
"e": 626,
"s": 502,
"text": "In this tutorial we deal only with normalisation. In my previous tutorials I dealt with missing values and data formatting."
},
{
"code": null,
"e": 1040,
"s": 626,
"text": "Data Normalisation involves adjusting values measured on different scales to a common scale. When dealing with dataframes, data normalization permits to adjust values referred to different columns to a common scale. This operation is strongly recommended when the columns of a dataframe are considered as input features of a machine learning algorithm, because it permits to give all the features the same weight."
},
{
"code": null,
"e": 1142,
"s": 1040,
"text": "Normalization applies only to columns containing numeric values. Five methods of normalization exist:"
},
{
"code": null,
"e": 1165,
"s": 1142,
"text": "single feature scaling"
},
{
"code": null,
"e": 1173,
"s": 1165,
"text": "min max"
},
{
"code": null,
"e": 1181,
"s": 1173,
"text": "z-score"
},
{
"code": null,
"e": 1193,
"s": 1181,
"text": "log scaling"
},
{
"code": null,
"e": 1202,
"s": 1193,
"text": "clipping"
},
{
"code": null,
"e": 1452,
"s": 1202,
"text": "In the remainder of the tutorial, we apply each method to a single column. However, if you wanted to use each column of the dataset as input features of a machine learning algorithm, you should apply the same normalisation method to all the columns."
},
{
"code": null,
"e": 1767,
"s": 1452,
"text": "In this tutorial, we use the pandas library to perform normalization. As an alternative, you could use the preprocessing methods of the scikit-learn libray. A little note for readers: if you wanted to learn how to use the preprocessing package of scikit-learn, please drop me a message or a comment to this post :)"
},
{
"code": null,
"e": 1879,
"s": 1767,
"text": "You can download the source code of this tutorial as a Jupyter notebook from my Github Data Science Repository."
},
{
"code": null,
"e": 2147,
"s": 1879,
"text": "As example dataset, in this tutorial we consider the dataset provided by the Italian Protezione Civile, related to the number of COVID-19 cases registered since the beginning of the COVID-19 pandemic. The dataset is updated daily and can be downloaded from this link."
},
{
"code": null,
"e": 2349,
"s": 2147,
"text": "First of all, we need to import the Python pandas library and read the dataset through the read_csv() function. Then we can drop all the columns with NaN values. This is done through dropna() function."
},
{
"code": null,
"e": 2528,
"s": 2349,
"text": "import pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv')df.dropna(axis=1,inplace=True)df.head(10)"
},
{
"code": null,
"e": 2887,
"s": 2528,
"text": "Single Feature Scaling converts every value of a column into a number between 0 and 1. The new value is calculated as the current value divided by the max value of the column. For example, if we consider the column tamponi, we can apply the single feature scaling by applying to the column the function max(), whic calculates the maximum value of the column:"
},
{
"code": null,
"e": 2937,
"s": 2887,
"text": "df['tamponi'] = df['tamponi']/df['tamponi'].max()"
},
{
"code": null,
"e": 3252,
"s": 2937,
"text": "Similarly to Single Feature Scaling, Min Max converts every value of a column into a number between 0 and 1. The new value is calculated as the difference between the current value and the min value, divided by the range of the column values. For example, we can apply the min max method to the column totale_casi."
},
{
"code": null,
"e": 3370,
"s": 3252,
"text": "df['totale_casi'] = (df['totale_casi'] - df['totale_casi'].min())/(df['totale_casi'].max() - df['totale_casi'].min())"
},
{
"code": null,
"e": 3836,
"s": 3370,
"text": "Z-Score converts every value of a column into a number around 0. Typical values obtained by a z-score transformation range from -3 and 3. The new value is calculated as the difference between the current value and the average value, divided by the standard deviation. The average value of a column can be obtained through the mean() function, while the standard deviation through the std() function. For example, we can calculate the z-score of the column deceduti."
},
{
"code": null,
"e": 3913,
"s": 3836,
"text": "df['deceduti'] = (df['deceduti']-df['deceduti'].mean())/df['deceduti'].std()"
},
{
"code": null,
"e": 4004,
"s": 3913,
"text": "Now we can calculate the minimum and maximum value obtained by the z-score transformation:"
},
{
"code": null,
"e": 4025,
"s": 4004,
"text": "df['deceduti'].min()"
},
{
"code": null,
"e": 4059,
"s": 4025,
"text": "which gives the following output:"
},
{
"code": null,
"e": 4079,
"s": 4059,
"text": "-0.4329770144818199"
},
{
"code": null,
"e": 4084,
"s": 4079,
"text": "and:"
},
{
"code": null,
"e": 4105,
"s": 4084,
"text": "df['deceduti'].max()"
},
{
"code": null,
"e": 4139,
"s": 4105,
"text": "which gives the following output:"
},
{
"code": null,
"e": 4157,
"s": 4139,
"text": "5.945028962275545"
},
{
"code": null,
"e": 4513,
"s": 4157,
"text": "Log Scaling involves the conversion of a column to the logarithmic scale. If we want to use the natural logarithm, we can use the log() function of the numpy library. For example, we can apply log scaling to the column dimessi_guariti. We must deal with log(0) because it does not exist. We use the lambda operator to select the single rows of the column."
},
{
"code": null,
"e": 4621,
"s": 4513,
"text": "import numpy as npdf['dimessi_guariti'] = df['dimessi_guariti'].apply(lambda x: np.log(x) if x != 0 else 0)"
},
{
"code": null,
"e": 4655,
"s": 4621,
"text": "which gives the following output:"
},
{
"code": null,
"e": 4894,
"s": 4655,
"text": "0 0.0000001 0.0000002 0.0000003 0.0000004 0.000000 ... 5812 9.8463885813 10.7942965814 9.4740885815 8.3728615816 10.922389Name: dimessi_guariti, Length: 5817, dtype: float64"
},
{
"code": null,
"e": 5303,
"s": 4894,
"text": "Clipping involves the capping of all values below or above a certain value. Clipping is useful when a column contains some outliers. We can set a maximum vmax and a minimum value vmin and set all outliers greater than the maximum value to vmax and all the outliers lower than the minimum value to vmin. For example, we can consider the column ricoverati_con_sintomi and we can set vmax = 10000 and vmin = 10."
},
{
"code": null,
"e": 5447,
"s": 5303,
"text": "vmax = 10000vmin = 10df['ricoverati_con_sintomi'] = df['ricoverati_con_sintomi'].apply(lambda x: vmax if x > vmax else vmin if x < vmin else x)"
},
{
"code": null,
"e": 5802,
"s": 5447,
"text": "In this tutorial, I have shown you the different techniques used to perform data normalisation: single feature scaling: min max, z-score, log scaling, clipping. Thus, the question is: what is the best technique? Actually, there is not a technique better than the others, the choice of a method rather than another depends on what we want as output. Thus:"
},
{
"code": null,
"e": 5890,
"s": 5802,
"text": "if you want an output between 0 and 1, you should use single feature scaling or min max"
},
{
"code": null,
"e": 5982,
"s": 5890,
"text": "if you want an output around 0, which includes also negative values, you should use z-score"
},
{
"code": null,
"e": 6039,
"s": 5982,
"text": "if your data contain many outliers, you can use clipping"
},
{
"code": null,
"e": 6114,
"s": 6039,
"text": "if you want to change the scale of your data, you can use the log scaling."
},
{
"code": null,
"e": 6249,
"s": 6114,
"text": "If you would like to learn about the other aspects of data preprocessing, such as data binning and data standardisation, stay tuned..."
}
] |
How can we MySQL LOAD DATA INFILE statement with ‘FIELDS TERMINATED BY’ option to import data from text file into MySQL table?
|
‘FIELDS TERMINATED BY’ option should be used when the text file which we want to import into MySQL table is having the values which are separated by a comma(,) or maybe with any other separator like a colon(:), semicolon(;) etc. It can be understood with the help of the following example −
Suppose we are having the following data, separated by a semicolon(;), in the text file ‘A.txt’ which we want to import into a MySQL file −
100;Ram;IND;15000
120;Mohan;IND;18000
Now with the help of the following query by using the option ‘FIELDS SEPARATED BY ‘we can import the data into MySQL table −
mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee12_tbl FIELDS TERMINATED BY ';';
Query OK, 2 rows affected (0.04 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0
mysql> Select * from employee12_tbl;
+------+----------------+----------+--------+
| Id | Name | Country | Salary |
+------+----------------+----------+--------+
| 100 | Ram | IND | 15000 |
| 120 | Mohan | IND | 18000 |
+------+----------------+----------+--------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1353,
"s": 1062,
"text": "‘FIELDS TERMINATED BY’ option should be used when the text file which we want to import into MySQL table is having the values which are separated by a comma(,) or maybe with any other separator like a colon(:), semicolon(;) etc. It can be understood with the help of the following example −"
},
{
"code": null,
"e": 1493,
"s": 1353,
"text": "Suppose we are having the following data, separated by a semicolon(;), in the text file ‘A.txt’ which we want to import into a MySQL file −"
},
{
"code": null,
"e": 1531,
"s": 1493,
"text": "100;Ram;IND;15000\n120;Mohan;IND;18000"
},
{
"code": null,
"e": 1656,
"s": 1531,
"text": "Now with the help of the following query by using the option ‘FIELDS SEPARATED BY ‘we can import the data into MySQL table −"
},
{
"code": null,
"e": 2170,
"s": 1656,
"text": "mysql> LOAD DATA LOCAL INFILE 'd:\\A.txt' INTO table employee12_tbl FIELDS TERMINATED BY ';';\nQuery OK, 2 rows affected (0.04 sec)\nRecords: 2 Deleted: 0 Skipped: 0 Warnings: 0\n\nmysql> Select * from employee12_tbl;\n+------+----------------+----------+--------+\n| Id | Name | Country | Salary |\n+------+----------------+----------+--------+\n| 100 | Ram | IND | 15000 |\n| 120 | Mohan | IND | 18000 |\n+------+----------------+----------+--------+\n2 rows in set (0.00 sec)"
}
] |
Angular 2 - Components
|
Components are a logical piece of code for Angular JS application. A Component consists of the following −
Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.
Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.
Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript.
Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript.
Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.
Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.
Let’s now go to the app.component.ts file and create our first Angular component.
Let’s add the following code to the file and look at each aspect in detail.
The class decorator. The class is defined in TypeScript. The class normally has the following syntax in TypeScript.
class classname {
Propertyname: PropertyType = Value
}
Classname − This is the name to be given to the class.
Classname − This is the name to be given to the class.
Propertyname − This is the name to be given to the property.
Propertyname − This is the name to be given to the property.
PropertyType − Since TypeScript is strongly typed, you need to give a type to the property.
PropertyType − Since TypeScript is strongly typed, you need to give a type to the property.
Value − This is the value to be given to the property.
Value − This is the value to be given to the property.
export class AppComponent {
appTitle: string = 'Welcome';
}
In the example, the following things need to be noted −
We are defining a class called AppComponent.
We are defining a class called AppComponent.
The export keyword is used so that the component can be used in other modules in the Angular JS application.
The export keyword is used so that the component can be used in other modules in the Angular JS application.
appTitle is the name of the property.
appTitle is the name of the property.
The property is given the type of string.
The property is given the type of string.
The property is given a value of ‘Welcome’.
The property is given a value of ‘Welcome’.
This is the view which needs to be rendered in the application.
Template: '
<HTML code>
class properties
'
HTML Code − This is the HTML code which needs to be rendered in the application.
HTML Code − This is the HTML code which needs to be rendered in the application.
Class properties − These are the properties of the class which can be referenced in the template.
Class properties − These are the properties of the class which can be referenced in the template.
template: '
<div>
<h1>{{appTitle}}</h1>
<div>To Tutorials Point</div>
</div>
'
In the example, the following things need to be noted −
We are defining the HTML code which will be rendered in our application
We are defining the HTML code which will be rendered in our application
We are also referencing the appTitle property from our class.
We are also referencing the appTitle property from our class.
This is used to decorate Angular JS class with additional information.
Let’s take a look at the completed code with our class, template, and metadata.
import { Component } from '@angular/core';
@Component ({
selector: 'my-app',
template: ` <div>
<h1>{{appTitle}}</h1>
<div>To Tutorials Point</div>
</div> `,
})
export class AppComponent {
appTitle: string = 'Welcome';
}
In the above example, the following things need to be noted −
We are using the import keyword to import the ‘Component’ decorator from the angular/core module.
We are using the import keyword to import the ‘Component’ decorator from the angular/core module.
We are then using the decorator to define a component.
We are then using the decorator to define a component.
The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page.
The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page.
Now, let’s go to our index.html file in our code.
Let’s make sure that the body tag now contains a reference to our custom tag in the component. Thus in the above case, we need to make sure that the body tag contains the following code −
<body>
<my-app></my-app>
</body>
Now if we go to the browser and see the output, we will see that the output is rendered as it is in the component.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2404,
"s": 2297,
"text": "Components are a logical piece of code for Angular JS application. A Component consists of the following −"
},
{
"code": null,
"e": 2589,
"s": 2404,
"text": "Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives."
},
{
"code": null,
"e": 2774,
"s": 2589,
"text": "Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives."
},
{
"code": null,
"e": 2958,
"s": 2774,
"text": "Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript."
},
{
"code": null,
"e": 3142,
"s": 2958,
"text": "Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript."
},
{
"code": null,
"e": 3240,
"s": 3142,
"text": "Metadata − This has the extra data defined for the Angular class. It is defined with a decorator."
},
{
"code": null,
"e": 3338,
"s": 3240,
"text": "Metadata − This has the extra data defined for the Angular class. It is defined with a decorator."
},
{
"code": null,
"e": 3420,
"s": 3338,
"text": "Let’s now go to the app.component.ts file and create our first Angular component."
},
{
"code": null,
"e": 3496,
"s": 3420,
"text": "Let’s add the following code to the file and look at each aspect in detail."
},
{
"code": null,
"e": 3612,
"s": 3496,
"text": "The class decorator. The class is defined in TypeScript. The class normally has the following syntax in TypeScript."
},
{
"code": null,
"e": 3671,
"s": 3612,
"text": "class classname {\n Propertyname: PropertyType = Value\n}\n"
},
{
"code": null,
"e": 3726,
"s": 3671,
"text": "Classname − This is the name to be given to the class."
},
{
"code": null,
"e": 3781,
"s": 3726,
"text": "Classname − This is the name to be given to the class."
},
{
"code": null,
"e": 3842,
"s": 3781,
"text": "Propertyname − This is the name to be given to the property."
},
{
"code": null,
"e": 3903,
"s": 3842,
"text": "Propertyname − This is the name to be given to the property."
},
{
"code": null,
"e": 3995,
"s": 3903,
"text": "PropertyType − Since TypeScript is strongly typed, you need to give a type to the property."
},
{
"code": null,
"e": 4087,
"s": 3995,
"text": "PropertyType − Since TypeScript is strongly typed, you need to give a type to the property."
},
{
"code": null,
"e": 4142,
"s": 4087,
"text": "Value − This is the value to be given to the property."
},
{
"code": null,
"e": 4197,
"s": 4142,
"text": "Value − This is the value to be given to the property."
},
{
"code": null,
"e": 4260,
"s": 4197,
"text": "export class AppComponent {\n appTitle: string = 'Welcome';\n}"
},
{
"code": null,
"e": 4316,
"s": 4260,
"text": "In the example, the following things need to be noted −"
},
{
"code": null,
"e": 4361,
"s": 4316,
"text": "We are defining a class called AppComponent."
},
{
"code": null,
"e": 4406,
"s": 4361,
"text": "We are defining a class called AppComponent."
},
{
"code": null,
"e": 4515,
"s": 4406,
"text": "The export keyword is used so that the component can be used in other modules in the Angular JS application."
},
{
"code": null,
"e": 4624,
"s": 4515,
"text": "The export keyword is used so that the component can be used in other modules in the Angular JS application."
},
{
"code": null,
"e": 4662,
"s": 4624,
"text": "appTitle is the name of the property."
},
{
"code": null,
"e": 4700,
"s": 4662,
"text": "appTitle is the name of the property."
},
{
"code": null,
"e": 4742,
"s": 4700,
"text": "The property is given the type of string."
},
{
"code": null,
"e": 4784,
"s": 4742,
"text": "The property is given the type of string."
},
{
"code": null,
"e": 4828,
"s": 4784,
"text": "The property is given a value of ‘Welcome’."
},
{
"code": null,
"e": 4872,
"s": 4828,
"text": "The property is given a value of ‘Welcome’."
},
{
"code": null,
"e": 4936,
"s": 4872,
"text": "This is the view which needs to be rendered in the application."
},
{
"code": null,
"e": 4986,
"s": 4936,
"text": "Template: '\n <HTML code>\n class properties\n'\n"
},
{
"code": null,
"e": 5067,
"s": 4986,
"text": "HTML Code − This is the HTML code which needs to be rendered in the application."
},
{
"code": null,
"e": 5148,
"s": 5067,
"text": "HTML Code − This is the HTML code which needs to be rendered in the application."
},
{
"code": null,
"e": 5246,
"s": 5148,
"text": "Class properties − These are the properties of the class which can be referenced in the template."
},
{
"code": null,
"e": 5344,
"s": 5246,
"text": "Class properties − These are the properties of the class which can be referenced in the template."
},
{
"code": null,
"e": 5441,
"s": 5344,
"text": "template: '\n <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div>\n'"
},
{
"code": null,
"e": 5497,
"s": 5441,
"text": "In the example, the following things need to be noted −"
},
{
"code": null,
"e": 5569,
"s": 5497,
"text": "We are defining the HTML code which will be rendered in our application"
},
{
"code": null,
"e": 5641,
"s": 5569,
"text": "We are defining the HTML code which will be rendered in our application"
},
{
"code": null,
"e": 5703,
"s": 5641,
"text": "We are also referencing the appTitle property from our class."
},
{
"code": null,
"e": 5765,
"s": 5703,
"text": "We are also referencing the appTitle property from our class."
},
{
"code": null,
"e": 5836,
"s": 5765,
"text": "This is used to decorate Angular JS class with additional information."
},
{
"code": null,
"e": 5916,
"s": 5836,
"text": "Let’s take a look at the completed code with our class, template, and metadata."
},
{
"code": null,
"e": 6162,
"s": 5916,
"text": "import { Component } from '@angular/core';\n\n@Component ({\n selector: 'my-app',\n template: ` <div>\n <h1>{{appTitle}}</h1>\n <div>To Tutorials Point</div>\n </div> `,\n})\n\nexport class AppComponent {\n appTitle: string = 'Welcome';\n}"
},
{
"code": null,
"e": 6224,
"s": 6162,
"text": "In the above example, the following things need to be noted −"
},
{
"code": null,
"e": 6322,
"s": 6224,
"text": "We are using the import keyword to import the ‘Component’ decorator from the angular/core module."
},
{
"code": null,
"e": 6420,
"s": 6322,
"text": "We are using the import keyword to import the ‘Component’ decorator from the angular/core module."
},
{
"code": null,
"e": 6475,
"s": 6420,
"text": "We are then using the decorator to define a component."
},
{
"code": null,
"e": 6530,
"s": 6475,
"text": "We are then using the decorator to define a component."
},
{
"code": null,
"e": 6657,
"s": 6530,
"text": "The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page."
},
{
"code": null,
"e": 6784,
"s": 6657,
"text": "The component has a selector called ‘my-app’. This is nothing but our custom html tag which can be used in our main html page."
},
{
"code": null,
"e": 6834,
"s": 6784,
"text": "Now, let’s go to our index.html file in our code."
},
{
"code": null,
"e": 7022,
"s": 6834,
"text": "Let’s make sure that the body tag now contains a reference to our custom tag in the component. Thus in the above case, we need to make sure that the body tag contains the following code −"
},
{
"code": null,
"e": 7059,
"s": 7022,
"text": "<body>\n <my-app></my-app>\n</body>\n"
},
{
"code": null,
"e": 7174,
"s": 7059,
"text": "Now if we go to the browser and see the output, we will see that the output is rendered as it is in the component."
},
{
"code": null,
"e": 7209,
"s": 7174,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7223,
"s": 7209,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7258,
"s": 7223,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7272,
"s": 7258,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7307,
"s": 7272,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7327,
"s": 7307,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7362,
"s": 7327,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7379,
"s": 7362,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7412,
"s": 7379,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7424,
"s": 7412,
"text": " Senol Atac"
},
{
"code": null,
"e": 7459,
"s": 7424,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7471,
"s": 7459,
"text": " Senol Atac"
},
{
"code": null,
"e": 7478,
"s": 7471,
"text": " Print"
},
{
"code": null,
"e": 7489,
"s": 7478,
"text": " Add Notes"
}
] |
WPF - Menu
|
Menu is a control that enables you to hierarchically organize elements associated with the commands and event handlers. Menu is an ItemsControl, so it can contain a collection of any object type such as string, image, or panel. The hierarchical inheritance of Menu class is as follows −
Below are the commonly used properties on Menu class
Background
Gets or sets a brush that describes the background of a control. (Inherited from Control.)
BindingGroup
Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.)
BitmapEffect
Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)
BorderThickness
Gets or sets the border thickness of a control. (Inherited from Control.)
ContextMenu
Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)
Effect
Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited from UIElement.)
Height
Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)
IsMainMenu
Gets or sets a value that indicates whether this Menu receives a main menu activation notification.
Items
Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
ItemsPanel
Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.)
ItemsSource
Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
ItemStringFormat
Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings. (Inherited from ItemsControl.)
ItemTemplate
Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.)
ToolTip
Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited from FrameworkElement.)
VerticalContentAlignment
Gets or sets the vertical alignment of the control's content. (Inherited from Control.)
Width
Gets or sets the width of the element. (Inherited from FrameworkElement.)
ContextMenuClosing
Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)
ContextMenuOpening
Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)
KeyDown
Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)
KeyUP
Occurs when a key is released while focus is on this element. (Inherited from UIElement.)
ToolTipClosing
Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.)
ToolTipOpening
Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.)
TouchDown
Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)
TouchEnter
Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)
TouchLeave
Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.)
TouchMove
Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)
TouchUp
Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)
Let’s create a new WPF project with the name WPFMenuControl.
Let’s create a new WPF project with the name WPFMenuControl.
Drag a menu control from the Toolbox to the design window.
Drag a menu control from the Toolbox to the design window.
The following example contains three menu options with some menu items. When the user clicks an item, the program updates the title. Here is the XAML code −
The following example contains three menu options with some menu items. When the user clicks an item, the program updates the title. Here is the XAML code −
<Window x:Class = "WPFMenuControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local = "clr-namespace:WPFMenuControl"
mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604">
<Grid>
<Menu HorizontalAlignment = "Left" VerticalAlignment = "Top" Width = "517">
<MenuItem Header = "File">
<MenuItem Header = "Item 1" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click" />
<MenuItem Header = "Item 2" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click" />
<Separator HorizontalAlignment = "Left" Width = "140" />
<MenuItem Header = "Item 3" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click"/>
</MenuItem>
<MenuItem Header = "Edit">
<MenuItem Header = "Item 1" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click1" />
<MenuItem Header = "Item 2" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click1" />
<Separator HorizontalAlignment = "Left" Width = "140" />
<MenuItem Header = "Item 3" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click1" />
</MenuItem>
<MenuItem Header = "View">
<MenuItem Header = "Item 1" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click2" />
<MenuItem Header = "Item 2" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click2" />
<Separator HorizontalAlignment = "Left" Width = "140" />
<MenuItem Header = "Item 3" HorizontalAlignment = "Left" Width = "140"
Click = "MenuItem_Click2"/>
</MenuItem>
</Menu>
</Grid>
</Window>
Here is the events implementation in C#.
using System.Windows;
using System.Windows.Controls;
namespace WPFMenuControl {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e) {
MenuItem item = sender as MenuItem;
this.Title = "File: " + item.Header;
}
private void MenuItem_Click1(object sender, RoutedEventArgs e) {
MenuItem item = sender as MenuItem;
this.Title = "Edit: " + item.Header;
}
private void MenuItem_Click2(object sender, RoutedEventArgs e) {
MenuItem item = sender as MenuItem;
this.Title = "View: " + item.Header;
}
}
}
When you compile and execute the above code, it will produce the following output −
We recommend that you execute the above example code and try the other properties and events of Menu class.
31 Lectures
2.5 hours
Anadi Sharma
30 Lectures
2.5 hours
Taurius Litvinavicius
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2307,
"s": 2020,
"text": "Menu is a control that enables you to hierarchically organize elements associated with the commands and event handlers. Menu is an ItemsControl, so it can contain a collection of any object type such as string, image, or panel. The hierarchical inheritance of Menu class is as follows −"
},
{
"code": null,
"e": 2360,
"s": 2307,
"text": "Below are the commonly used properties on Menu class"
},
{
"code": null,
"e": 2371,
"s": 2360,
"text": "Background"
},
{
"code": null,
"e": 2462,
"s": 2371,
"text": "Gets or sets a brush that describes the background of a control. (Inherited from Control.)"
},
{
"code": null,
"e": 2475,
"s": 2462,
"text": "BindingGroup"
},
{
"code": null,
"e": 2570,
"s": 2475,
"text": "Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 2583,
"s": 2570,
"text": "BitmapEffect"
},
{
"code": null,
"e": 2745,
"s": 2583,
"text": "Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.)"
},
{
"code": null,
"e": 2761,
"s": 2745,
"text": "BorderThickness"
},
{
"code": null,
"e": 2835,
"s": 2761,
"text": "Gets or sets the border thickness of a control. (Inherited from Control.)"
},
{
"code": null,
"e": 2847,
"s": 2835,
"text": "ContextMenu"
},
{
"code": null,
"e": 3032,
"s": 2847,
"text": "Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3039,
"s": 3032,
"text": "Effect"
},
{
"code": null,
"e": 3156,
"s": 3039,
"text": "Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited from UIElement.)"
},
{
"code": null,
"e": 3163,
"s": 3156,
"text": "Height"
},
{
"code": null,
"e": 3248,
"s": 3163,
"text": "Gets or sets the suggested height of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 3259,
"s": 3248,
"text": "IsMainMenu"
},
{
"code": null,
"e": 3359,
"s": 3259,
"text": "Gets or sets a value that indicates whether this Menu receives a main menu activation notification."
},
{
"code": null,
"e": 3365,
"s": 3359,
"text": "Items"
},
{
"code": null,
"e": 3466,
"s": 3365,
"text": "Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3477,
"s": 3466,
"text": "ItemsPanel"
},
{
"code": null,
"e": 3592,
"s": 3477,
"text": "Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3604,
"s": 3592,
"text": "ItemsSource"
},
{
"code": null,
"e": 3711,
"s": 3604,
"text": "Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3728,
"s": 3711,
"text": "ItemStringFormat"
},
{
"code": null,
"e": 3884,
"s": 3728,
"text": "Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3897,
"s": 3884,
"text": "ItemTemplate"
},
{
"code": null,
"e": 3985,
"s": 3897,
"text": "Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.)"
},
{
"code": null,
"e": 3993,
"s": 3985,
"text": "ToolTip"
},
{
"code": null,
"e": 4124,
"s": 3993,
"text": "Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4149,
"s": 4124,
"text": "VerticalContentAlignment"
},
{
"code": null,
"e": 4237,
"s": 4149,
"text": "Gets or sets the vertical alignment of the control's content. (Inherited from Control.)"
},
{
"code": null,
"e": 4243,
"s": 4237,
"text": "Width"
},
{
"code": null,
"e": 4317,
"s": 4243,
"text": "Gets or sets the width of the element. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4336,
"s": 4317,
"text": "ContextMenuClosing"
},
{
"code": null,
"e": 4433,
"s": 4336,
"text": "Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4452,
"s": 4433,
"text": "ContextMenuOpening"
},
{
"code": null,
"e": 4542,
"s": 4452,
"text": "Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4550,
"s": 4542,
"text": "KeyDown"
},
{
"code": null,
"e": 4639,
"s": 4550,
"text": "Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 4645,
"s": 4639,
"text": "KeyUP"
},
{
"code": null,
"e": 4735,
"s": 4645,
"text": "Occurs when a key is released while focus is on this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 4750,
"s": 4735,
"text": "ToolTipClosing"
},
{
"code": null,
"e": 4842,
"s": 4750,
"text": "Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4857,
"s": 4842,
"text": "ToolTipOpening"
},
{
"code": null,
"e": 4942,
"s": 4857,
"text": "Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.)"
},
{
"code": null,
"e": 4952,
"s": 4942,
"text": "TouchDown"
},
{
"code": null,
"e": 5059,
"s": 4952,
"text": "Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5070,
"s": 5059,
"text": "TouchEnter"
},
{
"code": null,
"e": 5175,
"s": 5070,
"text": "Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5186,
"s": 5175,
"text": "TouchLeave"
},
{
"code": null,
"e": 5291,
"s": 5186,
"text": "Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5301,
"s": 5291,
"text": "TouchMove"
},
{
"code": null,
"e": 5409,
"s": 5301,
"text": "Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5418,
"s": 5409,
"text": "TouchUp "
},
{
"code": null,
"e": 5534,
"s": 5418,
"text": "Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.)"
},
{
"code": null,
"e": 5595,
"s": 5534,
"text": "Let’s create a new WPF project with the name WPFMenuControl."
},
{
"code": null,
"e": 5656,
"s": 5595,
"text": "Let’s create a new WPF project with the name WPFMenuControl."
},
{
"code": null,
"e": 5715,
"s": 5656,
"text": "Drag a menu control from the Toolbox to the design window."
},
{
"code": null,
"e": 5774,
"s": 5715,
"text": "Drag a menu control from the Toolbox to the design window."
},
{
"code": null,
"e": 5931,
"s": 5774,
"text": "The following example contains three menu options with some menu items. When the user clicks an item, the program updates the title. Here is the XAML code −"
},
{
"code": null,
"e": 6088,
"s": 5931,
"text": "The following example contains three menu options with some menu items. When the user clicks an item, the program updates the title. Here is the XAML code −"
},
{
"code": null,
"e": 8242,
"s": 6088,
"text": "<Window x:Class = \"WPFMenuControl.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:d = \"http://schemas.microsoft.com/expression/blend/2008\" \n xmlns:mc = \"http://schemas.openxmlformats.org/markup-compatibility/2006\" \n xmlns:local = \"clr-namespace:WPFMenuControl\" \n mc:Ignorable = \"d\" Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <Menu HorizontalAlignment = \"Left\" VerticalAlignment = \"Top\" Width = \"517\"> \n\t\t\n <MenuItem Header = \"File\"> \n <MenuItem Header = \"Item 1\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click\" /> \n\t\t\t\t\t\n <MenuItem Header = \"Item 2\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click\" /> \n\t\t\t\t\t\n <Separator HorizontalAlignment = \"Left\" Width = \"140\" />\n\t\t\t\t\n <MenuItem Header = \"Item 3\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click\"/> \n </MenuItem> \n\t\t\t\n <MenuItem Header = \"Edit\"> \n <MenuItem Header = \"Item 1\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click1\" /> \n <MenuItem Header = \"Item 2\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click1\" /> \n <Separator HorizontalAlignment = \"Left\" Width = \"140\" /> \n <MenuItem Header = \"Item 3\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click1\" /> \n </MenuItem>\n\t\t\t\n <MenuItem Header = \"View\"> \n <MenuItem Header = \"Item 1\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click2\" /> \n <MenuItem Header = \"Item 2\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click2\" /> \n <Separator HorizontalAlignment = \"Left\" Width = \"140\" /> \n <MenuItem Header = \"Item 3\" HorizontalAlignment = \"Left\" Width = \"140\" \n Click = \"MenuItem_Click2\"/> \n </MenuItem>\n\t\t\t\n </Menu> \n </Grid> \n\t\n</Window>"
},
{
"code": null,
"e": 8283,
"s": 8242,
"text": "Here is the events implementation in C#."
},
{
"code": null,
"e": 9115,
"s": 8283,
"text": "using System.Windows; \nusing System.Windows.Controls;\n \nnamespace WPFMenuControl { \n /// <summary> \n /// Interaction logic for MainWindow.xaml\n /// </summary>\n\t\n public partial class MainWindow : Window {\n\t\n public MainWindow() { \n InitializeComponent(); \n } \n\t\t\n private void MenuItem_Click(object sender, RoutedEventArgs e) { \n MenuItem item = sender as MenuItem; \n this.Title = \"File: \" + item.Header; \n } \n\t\t\n private void MenuItem_Click1(object sender, RoutedEventArgs e) { \n MenuItem item = sender as MenuItem; \n this.Title = \"Edit: \" + item.Header; \n } \n\t\t\n private void MenuItem_Click2(object sender, RoutedEventArgs e) { \n MenuItem item = sender as MenuItem; \n this.Title = \"View: \" + item.Header; \n } \n\t\t\n } \n}"
},
{
"code": null,
"e": 9199,
"s": 9115,
"text": "When you compile and execute the above code, it will produce the following output −"
},
{
"code": null,
"e": 9307,
"s": 9199,
"text": "We recommend that you execute the above example code and try the other properties and events of Menu class."
},
{
"code": null,
"e": 9342,
"s": 9307,
"text": "\n 31 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9356,
"s": 9342,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9391,
"s": 9356,
"text": "\n 30 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9414,
"s": 9391,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 9421,
"s": 9414,
"text": " Print"
},
{
"code": null,
"e": 9432,
"s": 9421,
"text": " Add Notes"
}
] |
Create View SQL in SAP HANA database
|
>Create View View_name as
Select Col1,Col2 From Table_name;
In the above SQL statement, you are creating a view that contains Col1 and Col2 from the table.
Table Name − Emp_Info
To create a view, which contains only 3 columns you have to write-
>Create View View_EmpInfo As
Select Id, EmplName,Joining_Date From Emp_Info;
This view can be used by users to get Id, EmplName, and Joining_date.
|
[
{
"code": null,
"e": 1122,
"s": 1062,
"text": ">Create View View_name as\nSelect Col1,Col2 From Table_name;"
},
{
"code": null,
"e": 1218,
"s": 1122,
"text": "In the above SQL statement, you are creating a view that contains Col1 and Col2 from the table."
},
{
"code": null,
"e": 1240,
"s": 1218,
"text": "Table Name − Emp_Info"
},
{
"code": null,
"e": 1403,
"s": 1336,
"text": "To create a view, which contains only 3 columns you have to write-"
},
{
"code": null,
"e": 1481,
"s": 1403,
"text": ">Create View View_EmpInfo As\nSelect Id, EmplName,Joining_Date From Emp_Info;"
},
{
"code": null,
"e": 1551,
"s": 1481,
"text": "This view can be used by users to get Id, EmplName, and Joining_date."
}
] |
MS Project - Plan Duration Cost & Time
|
After assigning resources to tasks you can view the cost, duration and work required for the plan to complete.
In Gantt Chart View → View Tab → Split View group → Timeline checkbox.
You will be able to see the plan’s start and finish dates.
In the Gantt Chart view, you can also look at the project summary task, to note the duration, start and finish dates of the plan.
In the following example, Assign Resources is the project summary task (identified as Task 0). Duration=53 days, Start date: 1/5/15 and Finish Date: 3/19/15.
One can switch Project Summary Task on by following these steps −
In Gantt Chart View → Format Tab → Show/Hide → To check Project Summary Task on.
Click View tab → Data group → Tables → Cost.
Cost for each task gets rolled up into summary tasks, and then ultimately to project summary task.
Click Report Tab → View Reports group → click Resources → click Resource overview
In Resource status table which appears at the bottom, you will get a summary of resource’s earliest start dates and latest finish dates as well as remaining work.
Click Project Tab → Properties group → Project Information → in
the new dialog box click Statistics...
32 Lectures
2.5 hours
Pavan Lalwani
18 Lectures
1.5 hours
Dr. Saatya Prasad
102 Lectures
10 hours
Pavan Lalwani
52 Lectures
4 hours
Pavan Lalwani
239 Lectures
33 hours
Gowthami Swarna
53 Lectures
5 hours
Akshay Magre
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1992,
"s": 1881,
"text": "After assigning resources to tasks you can view the cost, duration and work required for the plan to complete."
},
{
"code": null,
"e": 2064,
"s": 1992,
"text": "In Gantt Chart View → View Tab → Split View group → Timeline checkbox.\n"
},
{
"code": null,
"e": 2123,
"s": 2064,
"text": "You will be able to see the plan’s start and finish dates."
},
{
"code": null,
"e": 2253,
"s": 2123,
"text": "In the Gantt Chart view, you can also look at the project summary task, to note the duration, start and finish dates of the plan."
},
{
"code": null,
"e": 2411,
"s": 2253,
"text": "In the following example, Assign Resources is the project summary task (identified as Task 0). Duration=53 days, Start date: 1/5/15 and Finish Date: 3/19/15."
},
{
"code": null,
"e": 2477,
"s": 2411,
"text": "One can switch Project Summary Task on by following these steps −"
},
{
"code": null,
"e": 2559,
"s": 2477,
"text": "In Gantt Chart View → Format Tab → Show/Hide → To check Project Summary Task on.\n"
},
{
"code": null,
"e": 2605,
"s": 2559,
"text": "Click View tab → Data group → Tables → Cost.\n"
},
{
"code": null,
"e": 2704,
"s": 2605,
"text": "Cost for each task gets rolled up into summary tasks, and then ultimately to project summary task."
},
{
"code": null,
"e": 2787,
"s": 2704,
"text": "Click Report Tab → View Reports group → click Resources → click Resource overview\n"
},
{
"code": null,
"e": 2950,
"s": 2787,
"text": "In Resource status table which appears at the bottom, you will get a summary of resource’s earliest start dates and latest finish dates as well as remaining work."
},
{
"code": null,
"e": 3057,
"s": 2950,
"text": "Click Project Tab → Properties group → Project Information → in\n the new dialog box click Statistics...\n"
},
{
"code": null,
"e": 3092,
"s": 3057,
"text": "\n 32 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3107,
"s": 3092,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3142,
"s": 3107,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3161,
"s": 3142,
"text": " Dr. Saatya Prasad"
},
{
"code": null,
"e": 3196,
"s": 3161,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3211,
"s": 3196,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3244,
"s": 3211,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3259,
"s": 3244,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3294,
"s": 3259,
"text": "\n 239 Lectures \n 33 hours \n"
},
{
"code": null,
"e": 3311,
"s": 3294,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 3344,
"s": 3311,
"text": "\n 53 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3358,
"s": 3344,
"text": " Akshay Magre"
},
{
"code": null,
"e": 3365,
"s": 3358,
"text": " Print"
},
{
"code": null,
"e": 3376,
"s": 3365,
"text": " Add Notes"
}
] |
How do I define string constants in C++?
|
To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
#include<iostream>
#include<string>
int main() {
const std::string MY_STRING = "Hello World!";
std::cout << MY_STRING;
return 0;
}
This will give the output −
Hello World!
Note that if you try to reassign a value to this variable it'll cause an error.
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword."
},
{
"code": null,
"e": 1348,
"s": 1217,
"text": "#include<iostream>\n#include<string>\nint main() {\nconst std::string MY_STRING = \"Hello World!\";\nstd::cout << MY_STRING;\nreturn 0;\n}"
},
{
"code": null,
"e": 1376,
"s": 1348,
"text": "This will give the output −"
},
{
"code": null,
"e": 1390,
"s": 1376,
"text": "Hello World!\n"
},
{
"code": null,
"e": 1470,
"s": 1390,
"text": "Note that if you try to reassign a value to this variable it'll cause an error."
}
] |
Groovy - Arithmetic Operators
|
The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −
int x = 5;
x++;
x will give 6
int x = 5;
x--;
x will give 4
The following code snippet shows how the various operators can be used.
class Example {
static void main(String[] args) {
// Initializing 3 variables
def x = 5;
def y = 10;
def z = 8;
//Performing addition of 2 operands
println(x+y);
//Subtracts second operand from the first
println(x-y);
//Multiplication of both operands
println(x*y);
//Division of numerator by denominator
println(z/x);
//Modulus Operator and remainder of after an integer/float division
println(z%x);
//Incremental operator
println(x++);
//Decrementing operator
println(x--);
}
}
When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above.
15
-5
50
1.6
3
5
6
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2381,
"s": 2238,
"text": "The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −"
},
{
"code": null,
"e": 2392,
"s": 2381,
"text": "int x = 5;"
},
{
"code": null,
"e": 2397,
"s": 2392,
"text": "x++;"
},
{
"code": null,
"e": 2411,
"s": 2397,
"text": "x will give 6"
},
{
"code": null,
"e": 2422,
"s": 2411,
"text": "int x = 5;"
},
{
"code": null,
"e": 2427,
"s": 2422,
"text": "x--;"
},
{
"code": null,
"e": 2441,
"s": 2427,
"text": "x will give 4"
},
{
"code": null,
"e": 2513,
"s": 2441,
"text": "The following code snippet shows how the various operators can be used."
},
{
"code": null,
"e": 3150,
"s": 2513,
"text": "class Example { \n static void main(String[] args) { \n // Initializing 3 variables \n def x = 5; \n def y = 10; \n def z = 8; \n\t\t\n //Performing addition of 2 operands \n println(x+y); \n\t\t\n //Subtracts second operand from the first \n println(x-y); \n\t\t\n //Multiplication of both operands \n println(x*y);\n\t\t\n //Division of numerator by denominator \n println(z/x); \n\t\t\n //Modulus Operator and remainder of after an integer/float division \n println(z%x); \n\t\t\n //Incremental operator \n println(x++); \n\t\t\n //Decrementing operator \n println(x--); \n } \n} "
},
{
"code": null,
"e": 3317,
"s": 3150,
"text": "When we run the above program, we will get the following result. It can be seen that the results are as expected from the description of the operators as shown above."
},
{
"code": null,
"e": 3343,
"s": 3317,
"text": "15 \n-5 \n50 \n1.6 \n3 \n5 \n6\n"
},
{
"code": null,
"e": 3376,
"s": 3343,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3394,
"s": 3376,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3429,
"s": 3394,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3447,
"s": 3429,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3454,
"s": 3447,
"text": " Print"
},
{
"code": null,
"e": 3465,
"s": 3454,
"text": " Add Notes"
}
] |
How can we decode a JSON object in Java?
|
A JSON is a lightweight, text-based and language-independent data exchange format. A JSON can represent two structured types like objects and arrays. We can decode a JSON object using JSONObject and JSONArray from json.simple API. A JSONObject works as a java.util.Map whereas JSONArray works as a java.util.List.
In the below example, we can decode a JSON object.
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONDecodingTest {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
String str = "[ 0 , {\"1\" : { \"2\" : {\"3\" : {\"4\" : [5, { \"6\" : { \"7\" : 8 } } ] } } } } ]";
try {
Object obj = parser.parse(str);
JSONArray array = (JSONArray)obj;
System.out.println("2nd Array element: ");
System.out.println(array.get(1));
System.out.println();
JSONObject object2 = (JSONObject) array.get(1);
System.out.println("Field \"1\"");
System.out.println(object2.get("1"));
str = "{}";
obj = parser.parse(str);
System.out.println(obj);
str = "[6,]";
obj = parser.parse(str);
System.out.println(obj);
str = "[6,,3]";
obj = parser.parse(str);
System.out.println(obj);
} catch(ParseException parseExp) {
System.out.println("Exception position: " + parseExp.getPosition());
System.out.println(parseExp);
}
}
}
2nd Array element:
{"1":{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}}
Field "1"
{"2":{"3":{"4":[5,{"6":{"7":8}}]}}}
{}
[6]
[6,3]
|
[
{
"code": null,
"e": 1376,
"s": 1062,
"text": "A JSON is a lightweight, text-based and language-independent data exchange format. A JSON can represent two structured types like objects and arrays. We can decode a JSON object using JSONObject and JSONArray from json.simple API. A JSONObject works as a java.util.Map whereas JSONArray works as a java.util.List."
},
{
"code": null,
"e": 1427,
"s": 1376,
"text": "In the below example, we can decode a JSON object."
},
{
"code": null,
"e": 2536,
"s": 1427,
"text": "import org.json.simple.*;\nimport org.json.simple.parser.*;\npublic class JSONDecodingTest {\n public static void main(String[] args) {\n JSONParser parser = new JSONParser();\n String str = \"[ 0 , {\\\"1\\\" : { \\\"2\\\" : {\\\"3\\\" : {\\\"4\\\" : [5, { \\\"6\\\" : { \\\"7\\\" : 8 } } ] } } } } ]\";\n try {\n Object obj = parser.parse(str);\n JSONArray array = (JSONArray)obj;\n System.out.println(\"2nd Array element: \");\n System.out.println(array.get(1));\n System.out.println();\n JSONObject object2 = (JSONObject) array.get(1);\n System.out.println(\"Field \\\"1\\\"\");\n System.out.println(object2.get(\"1\"));\n str = \"{}\";\n obj = parser.parse(str);\n System.out.println(obj);\n str = \"[6,]\";\n obj = parser.parse(str);\n System.out.println(obj);\n str = \"[6,,3]\";\n obj = parser.parse(str);\n System.out.println(obj);\n } catch(ParseException parseExp) {\n System.out.println(\"Exception position: \" + parseExp.getPosition());\n System.out.println(parseExp);\n }\n }\n}"
},
{
"code": null,
"e": 2657,
"s": 2536,
"text": "2nd Array element:\n{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":{\"7\":8}}]}}}}\n\nField \"1\"\n{\"2\":{\"3\":{\"4\":[5,{\"6\":{\"7\":8}}]}}}\n{}\n[6]\n[6,3]"
}
] |
Macros vs Functions - GeeksforGeeks
|
19 Oct, 2021
A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive. Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not preprocessed but compiled.
See the following example of Macro:
C
C++
#include<stdio.h>#define NUMBER 10int main(){ printf("%d", NUMBER); return 0;}
#include<iostream>#define NUMBER 10using namespace std;int main(){ cout<<NUMBER; return 0;}//This code is contributed by Mayank Tyagi
Output:
10
See the following example of Function:
C
C++
#include<stdio.h>int number(){ return 10;}int main(){ printf("%d", number()); return 0;}
#include<iostream>using namespace std;int number(){ return 10;}int main(){ cout<<number(); return 0;}//This code is contributed by Mayank Tyagi
Output:
10
Now compile them using the command:
gcc –E file_name.c
This will give you the executable code as shown in the figure:
This shows that the macros are preprocessed while functions are not.In macros, no type checking(incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any). Consider the following two codes:
Macros:
C
#include<stdio.h>#define CUBE(b) b*b*bint main(){ printf("%d", CUBE(1+2)); return 0;}
Output: Unexpected output
7
Note: This macro is expanded as below
CUBE(1+2) === 1+2*1+2*1+2 which is equal to 7 [correct but unexpected result depending upon the execution of the mathematical operators]
To fix this we need to replace #define CUBE(b) b*b*b as #define CUBE(b) (b)*(b)*(b). With updated macro, CUBE(1+2) will be expanded as
CUBE(1+2) === (1+2)*(1+2)*(1+2) which is equal to 27 [correct and expected result]
Functions:
C
#include<stdio.h>int cube(int a){ return a*a*a;}int main(){ printf("%d", cube(1+2)); return 0;}
Output: As expected
27
Macros are usually one liner. However, they can consist of more than one line, Click here to see the usage. There are no such constraints in functions.
The speed at which macros and functions differs. Macros are typically faster than functions as they don’t involve actual function call overhead.
Conclusion: Macros are no longer recommended as they cause following issues. There is a better way in modern compilers that is inline functions and const variable. Below are disadvantages of macros:a) There is no type checkingb) Difficult to debug as they cause simple replacement.c) Macro don’t have namespace, so a macro in one section of code can affect other section.d) Macros can cause side effects as shown in above CUBE() example.
See following for more details on macros: Interesting facts about Macros and Preprocessors This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
RishabhPrabhu
iamsamyak
mayanktyagi1709
klynsaha
shubhamsoni191
rvnay4phri4nwp6gvt8c3lz6yl3gaonp6z7f0tdp
CPP-Functions
cpp-macros
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
rand() and srand() in C/C++
fork() in C
Command line arguments in C/C++
Substring in C++
Function Pointer in C
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
|
[
{
"code": null,
"e": 24013,
"s": 23985,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24439,
"s": 24013,
"text": "A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive. Macros are pre-processed which means that all the macros would be processed before your program compiles. However, functions are not preprocessed but compiled."
},
{
"code": null,
"e": 24475,
"s": 24439,
"text": "See the following example of Macro:"
},
{
"code": null,
"e": 24477,
"s": 24475,
"text": "C"
},
{
"code": null,
"e": 24481,
"s": 24477,
"text": "C++"
},
{
"code": "#include<stdio.h>#define NUMBER 10int main(){ printf(\"%d\", NUMBER); return 0;}",
"e": 24568,
"s": 24481,
"text": null
},
{
"code": "#include<iostream>#define NUMBER 10using namespace std;int main(){ cout<<NUMBER; return 0;}//This code is contributed by Mayank Tyagi",
"e": 24710,
"s": 24568,
"text": null
},
{
"code": null,
"e": 24719,
"s": 24710,
"text": "Output: "
},
{
"code": null,
"e": 24722,
"s": 24719,
"text": "10"
},
{
"code": null,
"e": 24761,
"s": 24722,
"text": "See the following example of Function:"
},
{
"code": null,
"e": 24763,
"s": 24761,
"text": "C"
},
{
"code": null,
"e": 24767,
"s": 24763,
"text": "C++"
},
{
"code": "#include<stdio.h>int number(){ return 10;}int main(){ printf(\"%d\", number()); return 0;}",
"e": 24865,
"s": 24767,
"text": null
},
{
"code": "#include<iostream>using namespace std;int number(){ return 10;}int main(){ cout<<number(); return 0;}//This code is contributed by Mayank Tyagi",
"e": 25018,
"s": 24865,
"text": null
},
{
"code": null,
"e": 25027,
"s": 25018,
"text": "Output: "
},
{
"code": null,
"e": 25030,
"s": 25027,
"text": "10"
},
{
"code": null,
"e": 25067,
"s": 25030,
"text": "Now compile them using the command: "
},
{
"code": null,
"e": 25086,
"s": 25067,
"text": "gcc –E file_name.c"
},
{
"code": null,
"e": 25150,
"s": 25086,
"text": "This will give you the executable code as shown in the figure: "
},
{
"code": null,
"e": 25490,
"s": 25150,
"text": "This shows that the macros are preprocessed while functions are not.In macros, no type checking(incompatible operand, etc.) is done and thus use of macros can lead to errors/side-effects in some cases. However, this is not the case with functions. Also, macros do not check for compilation error (if any). Consider the following two codes:"
},
{
"code": null,
"e": 25500,
"s": 25490,
"text": "Macros: "
},
{
"code": null,
"e": 25502,
"s": 25500,
"text": "C"
},
{
"code": "#include<stdio.h>#define CUBE(b) b*b*bint main(){ printf(\"%d\", CUBE(1+2)); return 0;}",
"e": 25596,
"s": 25502,
"text": null
},
{
"code": null,
"e": 25623,
"s": 25596,
"text": "Output: Unexpected output "
},
{
"code": null,
"e": 25625,
"s": 25623,
"text": "7"
},
{
"code": null,
"e": 25663,
"s": 25625,
"text": "Note: This macro is expanded as below"
},
{
"code": null,
"e": 25801,
"s": 25663,
"text": "CUBE(1+2) === 1+2*1+2*1+2 which is equal to 7 [correct but unexpected result depending upon the execution of the mathematical operators]"
},
{
"code": null,
"e": 25937,
"s": 25801,
"text": "To fix this we need to replace #define CUBE(b) b*b*b as #define CUBE(b) (b)*(b)*(b). With updated macro, CUBE(1+2) will be expanded as "
},
{
"code": null,
"e": 26021,
"s": 25937,
"text": "CUBE(1+2) === (1+2)*(1+2)*(1+2) which is equal to 27 [correct and expected result]"
},
{
"code": null,
"e": 26032,
"s": 26021,
"text": "Functions:"
},
{
"code": null,
"e": 26034,
"s": 26032,
"text": "C"
},
{
"code": "#include<stdio.h>int cube(int a){ return a*a*a;}int main(){ printf(\"%d\", cube(1+2)); return 0;}",
"e": 26140,
"s": 26034,
"text": null
},
{
"code": null,
"e": 26161,
"s": 26140,
"text": "Output: As expected "
},
{
"code": null,
"e": 26164,
"s": 26161,
"text": "27"
},
{
"code": null,
"e": 26316,
"s": 26164,
"text": "Macros are usually one liner. However, they can consist of more than one line, Click here to see the usage. There are no such constraints in functions."
},
{
"code": null,
"e": 26461,
"s": 26316,
"text": "The speed at which macros and functions differs. Macros are typically faster than functions as they don’t involve actual function call overhead."
},
{
"code": null,
"e": 26899,
"s": 26461,
"text": "Conclusion: Macros are no longer recommended as they cause following issues. There is a better way in modern compilers that is inline functions and const variable. Below are disadvantages of macros:a) There is no type checkingb) Difficult to debug as they cause simple replacement.c) Macro don’t have namespace, so a macro in one section of code can affect other section.d) Macros can cause side effects as shown in above CUBE() example."
},
{
"code": null,
"e": 27260,
"s": 26899,
"text": "See following for more details on macros: Interesting facts about Macros and Preprocessors This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27386,
"s": 27260,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 27400,
"s": 27386,
"text": "RishabhPrabhu"
},
{
"code": null,
"e": 27410,
"s": 27400,
"text": "iamsamyak"
},
{
"code": null,
"e": 27426,
"s": 27410,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 27435,
"s": 27426,
"text": "klynsaha"
},
{
"code": null,
"e": 27450,
"s": 27435,
"text": "shubhamsoni191"
},
{
"code": null,
"e": 27491,
"s": 27450,
"text": "rvnay4phri4nwp6gvt8c3lz6yl3gaonp6z7f0tdp"
},
{
"code": null,
"e": 27505,
"s": 27491,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27516,
"s": 27505,
"text": "cpp-macros"
},
{
"code": null,
"e": 27527,
"s": 27516,
"text": "C Language"
},
{
"code": null,
"e": 27531,
"s": 27527,
"text": "C++"
},
{
"code": null,
"e": 27535,
"s": 27531,
"text": "CPP"
},
{
"code": null,
"e": 27633,
"s": 27535,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27642,
"s": 27633,
"text": "Comments"
},
{
"code": null,
"e": 27655,
"s": 27642,
"text": "Old Comments"
},
{
"code": null,
"e": 27683,
"s": 27655,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27695,
"s": 27683,
"text": "fork() in C"
},
{
"code": null,
"e": 27727,
"s": 27695,
"text": "Command line arguments in C/C++"
},
{
"code": null,
"e": 27744,
"s": 27727,
"text": "Substring in C++"
},
{
"code": null,
"e": 27766,
"s": 27744,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27784,
"s": 27766,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 27830,
"s": 27784,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 27873,
"s": 27830,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27892,
"s": 27873,
"text": "Inheritance in C++"
}
] |
Basic Algorithms — Counting Inversions | by Keita Miyaki | Towards Data Science
|
Even with significant advancement in computing capacities in recent years, it is still costly to operate on large datasets. Writing cost-efficient codes is, thus, one of the critical skills for data scientists. While an algorithm whose cost is linear to the input data size may be not so different from one that costs square, the former offers a huge advantage when the dataset increases to millions.
One basic way to write more efficient algorithms is the split-conquer method, where we write a nested function that applies the same function to the subset of the input recursively. In this article, we will compare split-conquer method against brute-force one in counting inverted pairs in a random array.
We are given an array of numbers without any duplication and asked to count inversions. Inversion is a case in which for two integers i<j, ith element in the array is larger than jth element.
If the array consists of (2,3,8,6,1), we can find five inversions of (2,1), (3,1), (8,6), (8,1), and (6,1).
The simplest and easiest way is to compare all the pairs in the array. With the array length n, we can just compare n(n-1)/2 pairs, and the cost is Θ(n2). Here is a simple coding sample with less than ten lines:
def bf_inversion_count(array): count = 0 for i in range(len(array)): j = i + 1 while j < len(array): if array[i] > array[j]: count +=1 j += 1 return count
Let’s think of a better and more efficient way. We can modify the merge-sort algorithm. A divide-conquer algorithm would cost:
T(n) = 2T(n/2) + f(n)
where the total cost T(n) is sum of cost for two half-size arrays T(n/2) and the cost to count inversions between two arrays f(n). We should be able to make f(n)=Θ(n) so that T(n)=Θ(nlgn).
Here is my sample code, which is mostly merge-sort code with counting lines added.
def sc_inversion_count(array): length = len(array) if length == 1: return array, 0 if length == 2: if array[0] > array[1]: return np.array([array[1], array[0]]), 1 else: return array, 0 elif length > 2: array_l = array[:length//2] array_r = array[length//2:] array_l_df = sc_inversion_count(array_l) array_r_df = sc_inversion_count(array_r) array_l_sorted = array_l_df[0] array_r_sorted = array_r_df[0] length_l = len(array_l) length_r = len(array_r) count = array_l_df[1] + array_r_df[1] l = 0 r = 0 sorted_list = [] for i in range(length): if r == length_r: sorted_list.append(array_l_sorted[l]) l += 1 elif l == length_l: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l] > array_r_sorted[r]: sorted_list.append(array_r_sorted[r]) r += 1 count += len(array_l_sorted) - l elif array_l_sorted[l] < array_r_sorted[r]: sorted_list.append(array_l_sorted[l]) l += 1 return np.array(sorted_list), count
Now we can compare how efficient the split-conquer method is versus the brute-force one. As the size of the array increases, obviously split-conquer method offers huge advantages in terms of calculation costs. This result clearly describes the importance of writing algorithms efficiently.
|
[
{
"code": null,
"e": 572,
"s": 171,
"text": "Even with significant advancement in computing capacities in recent years, it is still costly to operate on large datasets. Writing cost-efficient codes is, thus, one of the critical skills for data scientists. While an algorithm whose cost is linear to the input data size may be not so different from one that costs square, the former offers a huge advantage when the dataset increases to millions."
},
{
"code": null,
"e": 878,
"s": 572,
"text": "One basic way to write more efficient algorithms is the split-conquer method, where we write a nested function that applies the same function to the subset of the input recursively. In this article, we will compare split-conquer method against brute-force one in counting inverted pairs in a random array."
},
{
"code": null,
"e": 1070,
"s": 878,
"text": "We are given an array of numbers without any duplication and asked to count inversions. Inversion is a case in which for two integers i<j, ith element in the array is larger than jth element."
},
{
"code": null,
"e": 1178,
"s": 1070,
"text": "If the array consists of (2,3,8,6,1), we can find five inversions of (2,1), (3,1), (8,6), (8,1), and (6,1)."
},
{
"code": null,
"e": 1390,
"s": 1178,
"text": "The simplest and easiest way is to compare all the pairs in the array. With the array length n, we can just compare n(n-1)/2 pairs, and the cost is Θ(n2). Here is a simple coding sample with less than ten lines:"
},
{
"code": null,
"e": 1605,
"s": 1390,
"text": "def bf_inversion_count(array): count = 0 for i in range(len(array)): j = i + 1 while j < len(array): if array[i] > array[j]: count +=1 j += 1 return count"
},
{
"code": null,
"e": 1732,
"s": 1605,
"text": "Let’s think of a better and more efficient way. We can modify the merge-sort algorithm. A divide-conquer algorithm would cost:"
},
{
"code": null,
"e": 1754,
"s": 1732,
"text": "T(n) = 2T(n/2) + f(n)"
},
{
"code": null,
"e": 1943,
"s": 1754,
"text": "where the total cost T(n) is sum of cost for two half-size arrays T(n/2) and the cost to count inversions between two arrays f(n). We should be able to make f(n)=Θ(n) so that T(n)=Θ(nlgn)."
},
{
"code": null,
"e": 2026,
"s": 1943,
"text": "Here is my sample code, which is mostly merge-sort code with counting lines added."
},
{
"code": null,
"e": 3353,
"s": 2026,
"text": "def sc_inversion_count(array): length = len(array) if length == 1: return array, 0 if length == 2: if array[0] > array[1]: return np.array([array[1], array[0]]), 1 else: return array, 0 elif length > 2: array_l = array[:length//2] array_r = array[length//2:] array_l_df = sc_inversion_count(array_l) array_r_df = sc_inversion_count(array_r) array_l_sorted = array_l_df[0] array_r_sorted = array_r_df[0] length_l = len(array_l) length_r = len(array_r) count = array_l_df[1] + array_r_df[1] l = 0 r = 0 sorted_list = [] for i in range(length): if r == length_r: sorted_list.append(array_l_sorted[l]) l += 1 elif l == length_l: sorted_list.append(array_r_sorted[r]) r += 1 elif array_l_sorted[l] > array_r_sorted[r]: sorted_list.append(array_r_sorted[r]) r += 1 count += len(array_l_sorted) - l elif array_l_sorted[l] < array_r_sorted[r]: sorted_list.append(array_l_sorted[l]) l += 1 return np.array(sorted_list), count"
}
] |
Update 'a' record with 'b' and 'b' with 'a' in a MySQL column (swap) with only 'a' and 'b' values?
|
For this, use a CASE statement. Let us first create a table −
mysql> create table DemoTable
(
Value char(1)
);
Query OK, 0 rows affected (1.21 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('a');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('b');
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| a |
| b |
| a |
| a |
| b |
| a |
| b |
+-------+
7 rows in set (0.00 sec)
Following is the query to update 'a' record with 'b' and 'b' with 'a' −
mysql> update DemoTable set Value=case when Value='a' then 'b' else 'a' end;
Query OK, 7 rows affected (0.17 sec)
Rows matched: 7 Changed: 7 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| b |
| a |
| b |
| b |
| a |
| b |
| a |
+-------+
7 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1124,
"s": 1062,
"text": "For this, use a CASE statement. Let us first create a table −"
},
{
"code": null,
"e": 1213,
"s": 1124,
"text": "mysql> create table DemoTable\n(\n Value char(1)\n);\nQuery OK, 0 rows affected (1.21 sec)"
},
{
"code": null,
"e": 1269,
"s": 1213,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1815,
"s": 1269,
"text": "mysql> insert into DemoTable values('a');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('b');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('a');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('a');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('b');\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values('a');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('b');\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 1873,
"s": 1815,
"text": "Display all records from the table using select statement"
},
{
"code": null,
"e": 1904,
"s": 1873,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1945,
"s": 1904,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2080,
"s": 1945,
"text": "+-------+\n| Value |\n+-------+\n| a |\n| b |\n| a |\n| a |\n| b |\n| a |\n| b |\n+-------+\n7 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2152,
"s": 2080,
"text": "Following is the query to update 'a' record with 'b' and 'b' with 'a' −"
},
{
"code": null,
"e": 2305,
"s": 2152,
"text": "mysql> update DemoTable set Value=case when Value='a' then 'b' else 'a' end;\nQuery OK, 7 rows affected (0.17 sec)\nRows matched: 7 Changed: 7 Warnings: 0"
},
{
"code": null,
"e": 2349,
"s": 2305,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2380,
"s": 2349,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2421,
"s": 2380,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2556,
"s": 2421,
"text": "+-------+\n| Value |\n+-------+\n| b |\n| a |\n| b |\n| b |\n| a |\n| b |\n| a |\n+-------+\n7 rows in set (0.00 sec)"
}
] |
Tryit Editor v3.7
|
Tryit: The outline-offset property
|
[] |
How to find and remove duplicates from a table in Oracle?
|
Problem Statement:You want to find and remove duplicates from a table in Oracle.
Solution: We can use Oracle’s internal ROWID value for uniquely identifying rows in a table. The sample syntax to acheive this would like below.
delete from table
where rowid in
(... query here ...)
delete from table
where rowid in
(... query here ...)
To demonstrate the usage, we will begin by creating sample data.
-- table with tennis player rankings
DROP TABLE atp_stats;
CREATE TABLE atp_stats
( player_rank NUMBER NOT NULL,
player_name VARCHAR2(100) NOT NULL,
time_range TIMESTAMP(6));
-- sample records
INSERT INTO atp_stats VALUES (1,'ROGER FEDERER',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (2,'RAFAEL NADAL',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (3,'NOVAK DJOKOVIC',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (4,'ANDY MURRAY',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (1,'ROGER FEDERER',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (2,'RAFAEL NADAL',CURRENT_TIMESTAMP);
INSERT INTO atp_stats VALUES (3,'NOVAK DJOKOVIC',CURRENT_TIMESTAMP);
COMMIT;
Looking at the data we just created.
SELECT * FROM atp_stats ORDER BY 2;
SELECT * FROM atp_stats ORDER BY 2;
So, we have inserted 3 duplciates which we wanted to remove. before we go on and write a Delete statement, let us understand the inner query with ROWID.
SELECT rowid
FROM (
SELECT player_rank,
player_rank,
rowid ,
row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk
FROM atp_stats
)
WHERE rnk > 1;
SELECT rowid
FROM (
SELECT player_rank,
player_rank,
rowid ,
row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk
FROM atp_stats
)
WHERE rnk > 1;
I had intentionally added the columns player_rank and player_name to this innermost subquery to make the logic understandable. Ideally, innermost subquery could be written without them to the same effect. If we execute just this innermost query offcourse with the extra columns selected for clarity, we see these results.
The SQL returns the rowid for all the rows in the table. The ROW_NUMBER() function then works over sets of id and player_name driven by the PARTITION BY instruction. This means that for every unique player_rank and player_name, ROW_NUMBER will start a running count of rows we have aliased as rnk. When a new player_rank and player_name combination is observed, the rnk counter resets to 1.
Now we can apply the DELETE operator to remove the duplicate values as below.
DELETE
FROM atp_stats
WHERE rowid IN (
SELECT rowid
FROM(
SELECT player_rank, player_name,
rowid ,
row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk
FROM atp_stats
)
WHERE rnk > 1
);
DELETE
FROM atp_stats
WHERE rowid IN (
SELECT rowid
FROM(
SELECT player_rank, player_name,
rowid ,
row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk
FROM atp_stats
)
WHERE rnk > 1
);
3 rows deleted.
3 rows deleted.
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "Problem Statement:You want to find and remove duplicates from a table in Oracle."
},
{
"code": null,
"e": 1288,
"s": 1143,
"text": "Solution: We can use Oracle’s internal ROWID value for uniquely identifying rows in a table. The sample syntax to acheive this would like below."
},
{
"code": null,
"e": 1344,
"s": 1288,
"text": "delete from table\nwhere rowid in\n (... query here ...)"
},
{
"code": null,
"e": 1400,
"s": 1344,
"text": "delete from table\nwhere rowid in\n (... query here ...)"
},
{
"code": null,
"e": 1465,
"s": 1400,
"text": "To demonstrate the usage, we will begin by creating sample data."
},
{
"code": null,
"e": 2147,
"s": 1465,
"text": "-- table with tennis player rankings\nDROP TABLE atp_stats;\n\nCREATE TABLE atp_stats\n( player_rank NUMBER NOT NULL,\n player_name VARCHAR2(100) NOT NULL,\n time_range TIMESTAMP(6));\n\n-- sample records\nINSERT INTO atp_stats VALUES (1,'ROGER FEDERER',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (2,'RAFAEL NADAL',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (3,'NOVAK DJOKOVIC',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (4,'ANDY MURRAY',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (1,'ROGER FEDERER',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (2,'RAFAEL NADAL',CURRENT_TIMESTAMP);\nINSERT INTO atp_stats VALUES (3,'NOVAK DJOKOVIC',CURRENT_TIMESTAMP);\nCOMMIT;"
},
{
"code": null,
"e": 2184,
"s": 2147,
"text": "Looking at the data we just created."
},
{
"code": null,
"e": 2220,
"s": 2184,
"text": "SELECT * FROM atp_stats ORDER BY 2;"
},
{
"code": null,
"e": 2256,
"s": 2220,
"text": "SELECT * FROM atp_stats ORDER BY 2;"
},
{
"code": null,
"e": 2409,
"s": 2256,
"text": "So, we have inserted 3 duplciates which we wanted to remove. before we go on and write a Delete statement, let us understand the inner query with ROWID."
},
{
"code": null,
"e": 2609,
"s": 2409,
"text": "SELECT rowid\n FROM (\nSELECT player_rank,\n player_rank,\n rowid ,\n row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk\nFROM atp_stats\n)\nWHERE rnk > 1;"
},
{
"code": null,
"e": 2809,
"s": 2609,
"text": "SELECT rowid\n FROM (\nSELECT player_rank,\n player_rank,\n rowid ,\n row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk\nFROM atp_stats\n)\nWHERE rnk > 1;"
},
{
"code": null,
"e": 3131,
"s": 2809,
"text": "I had intentionally added the columns player_rank and player_name to this innermost subquery to make the logic understandable. Ideally, innermost subquery could be written without them to the same effect. If we execute just this innermost query offcourse with the extra columns selected for clarity, we see these results."
},
{
"code": null,
"e": 3522,
"s": 3131,
"text": "The SQL returns the rowid for all the rows in the table. The ROW_NUMBER() function then works over sets of id and player_name driven by the PARTITION BY instruction. This means that for every unique player_rank and player_name, ROW_NUMBER will start a running count of rows we have aliased as rnk. When a new player_rank and player_name combination is observed, the rnk counter resets to 1."
},
{
"code": null,
"e": 3600,
"s": 3522,
"text": "Now we can apply the DELETE operator to remove the duplicate values as below."
},
{
"code": null,
"e": 4045,
"s": 3600,
"text": "DELETE\n FROM atp_stats\n WHERE rowid IN (\n SELECT rowid\n FROM(\n SELECT player_rank, player_name,\n rowid ,\n row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk\n FROM atp_stats\n )\n WHERE rnk > 1\n );"
},
{
"code": null,
"e": 4490,
"s": 4045,
"text": "DELETE\n FROM atp_stats\n WHERE rowid IN (\n SELECT rowid\n FROM(\n SELECT player_rank, player_name,\n rowid ,\n row_number() over (partition BY player_rank, player_name order by player_rank,player_name) AS rnk\n FROM atp_stats\n )\n WHERE rnk > 1\n );"
},
{
"code": null,
"e": 4506,
"s": 4490,
"text": "3 rows deleted."
},
{
"code": null,
"e": 4522,
"s": 4506,
"text": "3 rows deleted."
}
] |
Indentation in Python - GeeksforGeeks
|
26 Nov, 2019
Indentation is a very important concept of Python because without proper indenting the Python code, you will end up seeing IndentationError and the code will not get compiled.
In simple terms indentation refers to adding white space before a statement. But the question arises is it even necessary?To understand this consider a situation where you are reading a book and all of a sudden all the page numbers from the book went missing. So you don’t know, where to continue reading and you will get confused. This situation is similar with Python. Without indentation, Python does not know which statement to execute next or which statement belongs to which block. This will lead to IndentationError.
In the above example,
Statement (line 1), if condition (line 2), and statement (last line) belongs to the same block which means that after statement 1, if condition will be executed. and suppose the if condition becomes False then the Python will jump to the last statement for execution.
The nested if-else belongs to block 2 which means that if nested if becomes False, then Python will execute the statements inside the else condition.
Statements inside nested if-else belongs to block 3 and only one statement will be executed depending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the group of statements belongs to a particular block of code. A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code.
Example #1:
# Python program showing # indentation site = 'gfg' if site == 'gfg': print('Logging on to geeksforgeeks...') else: print('retype the URL.') print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
The lines print(‘Logging on to geeksforgeeks...’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the else-block.
Example #2:
j = 1 while(j<= 5): print(j) j = j + 1
Output:
1
2
3
4
5
To indicate a block of code in Python, you must indent each line of the block by the same whitespace. The two lines of code in the while loop are both indented four spaces. It is required for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is not indented, and so it is not within while block. So, Python code structures by indentation.
Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used.
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23926,
"s": 23898,
"text": "\n26 Nov, 2019"
},
{
"code": null,
"e": 24102,
"s": 23926,
"text": "Indentation is a very important concept of Python because without proper indenting the Python code, you will end up seeing IndentationError and the code will not get compiled."
},
{
"code": null,
"e": 24626,
"s": 24102,
"text": "In simple terms indentation refers to adding white space before a statement. But the question arises is it even necessary?To understand this consider a situation where you are reading a book and all of a sudden all the page numbers from the book went missing. So you don’t know, where to continue reading and you will get confused. This situation is similar with Python. Without indentation, Python does not know which statement to execute next or which statement belongs to which block. This will lead to IndentationError."
},
{
"code": null,
"e": 24648,
"s": 24626,
"text": "In the above example,"
},
{
"code": null,
"e": 24916,
"s": 24648,
"text": "Statement (line 1), if condition (line 2), and statement (last line) belongs to the same block which means that after statement 1, if condition will be executed. and suppose the if condition becomes False then the Python will jump to the last statement for execution."
},
{
"code": null,
"e": 25066,
"s": 24916,
"text": "The nested if-else belongs to block 2 which means that if nested if becomes False, then Python will execute the statements inside the else condition."
},
{
"code": null,
"e": 25194,
"s": 25066,
"text": "Statements inside nested if-else belongs to block 3 and only one statement will be executed depending on the if-else condition."
},
{
"code": null,
"e": 25887,
"s": 25194,
"text": "Python indentation is a way of telling a Python interpreter that the group of statements belongs to a particular block of code. A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right. You can understand it better by looking at the following lines of code."
},
{
"code": null,
"e": 25899,
"s": 25887,
"text": "Example #1:"
},
{
"code": "# Python program showing # indentation site = 'gfg' if site == 'gfg': print('Logging on to geeksforgeeks...') else: print('retype the URL.') print('All set !') ",
"e": 26075,
"s": 25899,
"text": null
},
{
"code": null,
"e": 26083,
"s": 26075,
"text": "Output:"
},
{
"code": null,
"e": 26125,
"s": 26083,
"text": "Logging on to geeksforgeeks...\nAll set !\n"
},
{
"code": null,
"e": 26406,
"s": 26125,
"text": "The lines print(‘Logging on to geeksforgeeks...’) and print(‘retype the URL.’) are two separate code blocks. The two blocks of code in our example if-statement are both indented four spaces. The final print(‘All set!’) is not indented, and so it does not belong to the else-block."
},
{
"code": null,
"e": 26418,
"s": 26406,
"text": "Example #2:"
},
{
"code": "j = 1 while(j<= 5): print(j) j = j + 1",
"e": 26468,
"s": 26418,
"text": null
},
{
"code": null,
"e": 26476,
"s": 26468,
"text": "Output:"
},
{
"code": null,
"e": 26487,
"s": 26476,
"text": "1\n2\n3\n4\n5\n"
},
{
"code": null,
"e": 26864,
"s": 26487,
"text": "To indicate a block of code in Python, you must indent each line of the block by the same whitespace. The two lines of code in the while loop are both indented four spaces. It is required for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is not indented, and so it is not within while block. So, Python code structures by indentation."
},
{
"code": null,
"e": 27003,
"s": 26864,
"text": "Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used."
},
{
"code": null,
"e": 27017,
"s": 27003,
"text": "python-basics"
},
{
"code": null,
"e": 27024,
"s": 27017,
"text": "Python"
},
{
"code": null,
"e": 27122,
"s": 27024,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27131,
"s": 27122,
"text": "Comments"
},
{
"code": null,
"e": 27144,
"s": 27131,
"text": "Old Comments"
},
{
"code": null,
"e": 27176,
"s": 27144,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27232,
"s": 27176,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27274,
"s": 27232,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27316,
"s": 27274,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27352,
"s": 27316,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27374,
"s": 27352,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27413,
"s": 27374,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27440,
"s": 27413,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27471,
"s": 27440,
"text": "Python | os.path.join() method"
}
] |
How to retrieve Date from a table in JDBC?
|
The ResultSet interface provides a method named getDate() this method accepts an integer parameter representing the index of the column, (or, a String parameter representing the name of the column) from which you need to retrieve the date value. To retrieve date value from a table −
Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
Create a Statement object using the createStatement() method of the Connection interface.
Create a Statement object using the createStatement() method of the Connection interface.
Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it.
Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it.
From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface. Pass the name of the column (String) as a parameter to this.
From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface. Pass the name of the column (String) as a parameter to this.
Assume we have a table named Emp in the database as shown below −
+--------+------------+----------------+
| Name | DOB | Location |
+--------+------------+----------------+
| Amit | 1989-09-26 | Hyderabad |
| Sumith | 1989-09-01 | Vishakhapatnam |
| Sudha | 1980-09-01 | Vijayawada |
+--------+------------+----------------+
Following is a JDBC example which retrieves the Date and String values from a table using getDate() and getString() methods of the ResultSet interface.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingDate {
public static void main(String args[])throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating Statement object
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from Emp");
//Retrieving values
while(rs.next()) {
System.out.print("Name: "+rs.getString("Name"));
System.out.print(" Date of Birth: "+rs.getDate("DOB"));
System.out.print(" Location: "+rs.getString("Location"));
System.out.println();
}
}
}
Connection established......
Name: Amit Date Of Birth: 1989-09-26 Location: Hyderabad
Name: Sumith Date Of Birth: 1989-09-01 Location: Vishakhapatnam
Name: Sudha Date Of Birth: 1980-09-01 Location: Vijayawada
|
[
{
"code": null,
"e": 1346,
"s": 1062,
"text": "The ResultSet interface provides a method named getDate() this method accepts an integer parameter representing the index of the column, (or, a String parameter representing the name of the column) from which you need to retrieve the date value. To retrieve date value from a table −"
},
{
"code": null,
"e": 1482,
"s": 1346,
"text": "Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter."
},
{
"code": null,
"e": 1618,
"s": 1482,
"text": "Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter."
},
{
"code": null,
"e": 1783,
"s": 1618,
"text": "Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it."
},
{
"code": null,
"e": 1948,
"s": 1783,
"text": "Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it."
},
{
"code": null,
"e": 2038,
"s": 1948,
"text": "Create a Statement object using the createStatement() method of the Connection interface."
},
{
"code": null,
"e": 2128,
"s": 2038,
"text": "Create a Statement object using the createStatement() method of the Connection interface."
},
{
"code": null,
"e": 2249,
"s": 2128,
"text": "Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it."
},
{
"code": null,
"e": 2370,
"s": 2249,
"text": "Execute the query using the executeQuery() method. Pass the select query to retrieve data (String) as a parameter to it."
},
{
"code": null,
"e": 2567,
"s": 2370,
"text": "From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface. Pass the name of the column (String) as a parameter to this."
},
{
"code": null,
"e": 2764,
"s": 2567,
"text": "From the obtained result set object get the date value (along with other values) using the getDate() method of the ResultSet interface. Pass the name of the column (String) as a parameter to this."
},
{
"code": null,
"e": 2830,
"s": 2764,
"text": "Assume we have a table named Emp in the database as shown below −"
},
{
"code": null,
"e": 3117,
"s": 2830,
"text": "+--------+------------+----------------+\n| Name | DOB | Location |\n+--------+------------+----------------+\n| Amit | 1989-09-26 | Hyderabad |\n| Sumith | 1989-09-01 | Vishakhapatnam |\n| Sudha | 1980-09-01 | Vijayawada |\n+--------+------------+----------------+"
},
{
"code": null,
"e": 3269,
"s": 3117,
"text": "Following is a JDBC example which retrieves the Date and String values from a table using getDate() and getString() methods of the ResultSet interface."
},
{
"code": null,
"e": 4226,
"s": 3269,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class RetrievingDate {\n public static void main(String args[])throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/sampleDB\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating Statement object\n Statement stmt = con.createStatement();\n ResultSet rs = stmt.executeQuery(\"select * from Emp\");\n //Retrieving values\n while(rs.next()) {\n System.out.print(\"Name: \"+rs.getString(\"Name\"));\n System.out.print(\" Date of Birth: \"+rs.getDate(\"DOB\"));\n System.out.print(\" Location: \"+rs.getString(\"Location\"));\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 4435,
"s": 4226,
"text": "Connection established......\nName: Amit Date Of Birth: 1989-09-26 Location: Hyderabad\nName: Sumith Date Of Birth: 1989-09-01 Location: Vishakhapatnam\nName: Sudha Date Of Birth: 1980-09-01 Location: Vijayawada"
}
] |
Erlang - Funs
|
Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −
F = fun (Arg1, Arg2, ... ArgN) ->
...
End
Where
F − This is the variable name assigned to the anonymous function.
F − This is the variable name assigned to the anonymous function.
Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function.
Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function.
The following example showcases how the anonymous function can be used.
-module(helloworld).
-export([start/0]).
start() ->
A = fun() -> io:fwrite("Hello") end,
A().
The following things need to be noted about the above program.
The anonymous function is assigned to the variable A.
The anonymous function is assigned to the variable A.
The anonymous function via the variable A().
The anonymous function via the variable A().
When we run the above program we will get the following result.
“Hello”
Another example of anonymous function is as follows, but this is with the use of parameters.
-module(helloworld).
-export([start/0]).
start() ->
A = fun(X) ->
io:fwrite("~p~n",[X])
end,
A(5).
When we run the above program we will get the following result.
5
The Anonymous function have the ability to access the variables which are outside of the scope of the anonymous function. Let’s look at an example of this −
-module(helloworld).
-export([start/0]).
start() ->
B = 6,
A = fun(X) ->
io:fwrite("~p~n",[X]),
io:fwrite("~p~n",[B])
end,
A(5).
The following things need to be noted about the above program.
The variable B is outside of the scope of the anonymous function.
The variable B is outside of the scope of the anonymous function.
The anonymous function can still access the variable defined in the global scope.
The anonymous function can still access the variable defined in the global scope.
When we run the above program we will get the following result.
5
6
One of the other most powerful aspects of higher order functions, is that you can define a function within a function. Let’s see an example of how we can achieve this.
-module(helloworld).
-export([start/0]).
start() ->
Adder = fun(X) -> fun(Y) -> io:fwrite("~p~n",[X + Y]) end end,
A = Adder(6),
A(10).
The following things need to be noted about the above program.
Adder is a higher order function defined as fun(X).
Adder is a higher order function defined as fun(X).
The Adder function fun(X) has a reference to another function fun(Y).
The Adder function fun(X) has a reference to another function fun(Y).
When we run the above program we will get the following result.
16
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2417,
"s": 2301,
"text": "Funs are used to define anonymous functions in Erlang. The general syntax of an anonymous function is given below −"
},
{
"code": null,
"e": 2463,
"s": 2417,
"text": "F = fun (Arg1, Arg2, ... ArgN) ->\n ...\nEnd\n"
},
{
"code": null,
"e": 2469,
"s": 2463,
"text": "Where"
},
{
"code": null,
"e": 2535,
"s": 2469,
"text": "F − This is the variable name assigned to the anonymous function."
},
{
"code": null,
"e": 2601,
"s": 2535,
"text": "F − This is the variable name assigned to the anonymous function."
},
{
"code": null,
"e": 2692,
"s": 2601,
"text": "Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function."
},
{
"code": null,
"e": 2783,
"s": 2692,
"text": "Arg1, Arg2, ... ArgN − These are the arguments which are passed to the anonymous function."
},
{
"code": null,
"e": 2855,
"s": 2783,
"text": "The following example showcases how the anonymous function can be used."
},
{
"code": null,
"e": 2960,
"s": 2855,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n A = fun() -> io:fwrite(\"Hello\") end, \n A()."
},
{
"code": null,
"e": 3023,
"s": 2960,
"text": "The following things need to be noted about the above program."
},
{
"code": null,
"e": 3077,
"s": 3023,
"text": "The anonymous function is assigned to the variable A."
},
{
"code": null,
"e": 3131,
"s": 3077,
"text": "The anonymous function is assigned to the variable A."
},
{
"code": null,
"e": 3176,
"s": 3131,
"text": "The anonymous function via the variable A()."
},
{
"code": null,
"e": 3221,
"s": 3176,
"text": "The anonymous function via the variable A()."
},
{
"code": null,
"e": 3285,
"s": 3221,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 3294,
"s": 3285,
"text": "“Hello”\n"
},
{
"code": null,
"e": 3387,
"s": 3294,
"text": "Another example of anonymous function is as follows, but this is with the use of parameters."
},
{
"code": null,
"e": 3511,
"s": 3387,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n A = fun(X) -> \n io:fwrite(\"~p~n\",[X]) \n end, \n A(5)."
},
{
"code": null,
"e": 3575,
"s": 3511,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 3578,
"s": 3575,
"text": "5\n"
},
{
"code": null,
"e": 3735,
"s": 3578,
"text": "The Anonymous function have the ability to access the variables which are outside of the scope of the anonymous function. Let’s look at an example of this −"
},
{
"code": null,
"e": 3900,
"s": 3735,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n B = 6, \n A = fun(X) -> \n io:fwrite(\"~p~n\",[X]), \n io:fwrite(\"~p~n\",[B]) \n end, \n A(5)."
},
{
"code": null,
"e": 3963,
"s": 3900,
"text": "The following things need to be noted about the above program."
},
{
"code": null,
"e": 4029,
"s": 3963,
"text": "The variable B is outside of the scope of the anonymous function."
},
{
"code": null,
"e": 4095,
"s": 4029,
"text": "The variable B is outside of the scope of the anonymous function."
},
{
"code": null,
"e": 4177,
"s": 4095,
"text": "The anonymous function can still access the variable defined in the global scope."
},
{
"code": null,
"e": 4259,
"s": 4177,
"text": "The anonymous function can still access the variable defined in the global scope."
},
{
"code": null,
"e": 4323,
"s": 4259,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 4328,
"s": 4323,
"text": "5\n6\n"
},
{
"code": null,
"e": 4496,
"s": 4328,
"text": "One of the other most powerful aspects of higher order functions, is that you can define a function within a function. Let’s see an example of how we can achieve this."
},
{
"code": null,
"e": 4647,
"s": 4496,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() -> \n Adder = fun(X) -> fun(Y) -> io:fwrite(\"~p~n\",[X + Y]) end end, \n A = Adder(6), \n A(10)."
},
{
"code": null,
"e": 4710,
"s": 4647,
"text": "The following things need to be noted about the above program."
},
{
"code": null,
"e": 4762,
"s": 4710,
"text": "Adder is a higher order function defined as fun(X)."
},
{
"code": null,
"e": 4814,
"s": 4762,
"text": "Adder is a higher order function defined as fun(X)."
},
{
"code": null,
"e": 4884,
"s": 4814,
"text": "The Adder function fun(X) has a reference to another function fun(Y)."
},
{
"code": null,
"e": 4954,
"s": 4884,
"text": "The Adder function fun(X) has a reference to another function fun(Y)."
},
{
"code": null,
"e": 5018,
"s": 4954,
"text": "When we run the above program we will get the following result."
},
{
"code": null,
"e": 5022,
"s": 5018,
"text": "16\n"
},
{
"code": null,
"e": 5029,
"s": 5022,
"text": " Print"
},
{
"code": null,
"e": 5040,
"s": 5029,
"text": " Add Notes"
}
] |
Build and Run a Docker Container for your Machine Learning Model | by Xavier Vasques | Towards Data Science
|
The idea of this article is to do a quick and easy build of a Docker container with a simple machine learning model and run it. Before reading this article, do not hesitate to read Why use Docker for Machine Learning and Quick Install and First Use of Docker.
In order to start building a Docker container for a machine learning model, let’s consider three files: Dockerfile, train.py, inference.py.
You can find all files on GitHub.
The train.py is a python script that ingest and normalize EEG data in a csv file (train.csv) and train two models to classify the data (using scikit-learn). The script saves two models: Linear Discriminant Analysis (clf_lda) and Neural Networks multi-layer perceptron (clf_NN).
The inference.py will be called to perform batch inference by loading the two models that has been previously created. The application will normalize new EEG data coming from a csv file (test.csv), perform inference on the dataset and print the classification accuracy and predictions.
Let’s create a simple Dockerfile with the jupyter/scipy-notebook image as our base image. We need to install joblib to allow serialization and deserialization of our trained model. We copy the train.csv, test.csv, train.py and inference.py files into the image. Then, we run train.py which will fit and serialize the machine learning models as part of our image build process which provide several advantages such as the ability to debug at the beginning of the process, use Docker Image ID for keeping track or use different versions.
In order to build the image, we run the following command in our terminal:
docker build -t docker-ml-model -f Dockerfile .
The output is the following:
It’s time to perform the inference on new data (test.csv):
docker run docker-ml-model python3 inference.py
The output is the following:
We can do a few things that can improve our containerization experience. We can for example bind a host directory in the container using WORKDIR in the Dockerfile:
In inference.py, we can decide for example to save an output.csv file with the X_test data in it:
When you build it and run it you should be able to see the output.csv file in /mydata :
We can also add the VOLUME instruction in the Dockerfile resulting in an image that will create a new mount point:
With the name that we specify, the VOLUME instruction creates a mount point which is tagged as holding externally mounted volume from native host or other containers where we find the data we want to process.
For the future of your developments, it can be necessary to set environment variables from the beginning, just once at the build time, for persisting the trained model and maybe add additional data or metadata to a specific location. The advantage of setting environment variables is to avoid the hard code of the necessary paths all over your code and to better share your work with others on an agreed directory structure.
Let’s take another example, with a new Dockerfile:
We need to add the environment variables to train.py:
and inference.py:
The goal was to produce quick and easy steps to build a Docker container with a simple machine learning model. Building is as simple as doing a docker build -t my-docker-image ..
From this step, we can start the deployment of our models which will be much simpler and removing the fear to publish and scale your machine learning model. The next step is to produce a workflow with a CI/CD tool (Continuous Integration/Continuous Delivery) such as Jenkins. Thanks to this approach, it will be possible to build and serve anywhere a docker container and expose a REST API so that external stakeholders can consume it. If you are training a deep learning model that needs high computational needs, you can move your containers to high performance computing servers or any platform of your choice such as on premises, private or public cloud. The idea is that you can scale your model but also create resilient deployment as you can scale the container across regions/availability zones.
I hope you can see the great simplicity and flexibility containers provide. By containerizing your machine/deep learning application, you can make it visible to the world. The next step is to deploy it in the cloud and expose it. At certain points in time, you will need to orchestrate, monitor and scale your containers to serve millions of users with the help of technologies such as Red Hat OpenShift, a Kubernetes distribution.
|
[
{
"code": null,
"e": 432,
"s": 172,
"text": "The idea of this article is to do a quick and easy build of a Docker container with a simple machine learning model and run it. Before reading this article, do not hesitate to read Why use Docker for Machine Learning and Quick Install and First Use of Docker."
},
{
"code": null,
"e": 572,
"s": 432,
"text": "In order to start building a Docker container for a machine learning model, let’s consider three files: Dockerfile, train.py, inference.py."
},
{
"code": null,
"e": 606,
"s": 572,
"text": "You can find all files on GitHub."
},
{
"code": null,
"e": 884,
"s": 606,
"text": "The train.py is a python script that ingest and normalize EEG data in a csv file (train.csv) and train two models to classify the data (using scikit-learn). The script saves two models: Linear Discriminant Analysis (clf_lda) and Neural Networks multi-layer perceptron (clf_NN)."
},
{
"code": null,
"e": 1170,
"s": 884,
"text": "The inference.py will be called to perform batch inference by loading the two models that has been previously created. The application will normalize new EEG data coming from a csv file (test.csv), perform inference on the dataset and print the classification accuracy and predictions."
},
{
"code": null,
"e": 1706,
"s": 1170,
"text": "Let’s create a simple Dockerfile with the jupyter/scipy-notebook image as our base image. We need to install joblib to allow serialization and deserialization of our trained model. We copy the train.csv, test.csv, train.py and inference.py files into the image. Then, we run train.py which will fit and serialize the machine learning models as part of our image build process which provide several advantages such as the ability to debug at the beginning of the process, use Docker Image ID for keeping track or use different versions."
},
{
"code": null,
"e": 1781,
"s": 1706,
"text": "In order to build the image, we run the following command in our terminal:"
},
{
"code": null,
"e": 1829,
"s": 1781,
"text": "docker build -t docker-ml-model -f Dockerfile ."
},
{
"code": null,
"e": 1858,
"s": 1829,
"text": "The output is the following:"
},
{
"code": null,
"e": 1917,
"s": 1858,
"text": "It’s time to perform the inference on new data (test.csv):"
},
{
"code": null,
"e": 1965,
"s": 1917,
"text": "docker run docker-ml-model python3 inference.py"
},
{
"code": null,
"e": 1994,
"s": 1965,
"text": "The output is the following:"
},
{
"code": null,
"e": 2158,
"s": 1994,
"text": "We can do a few things that can improve our containerization experience. We can for example bind a host directory in the container using WORKDIR in the Dockerfile:"
},
{
"code": null,
"e": 2256,
"s": 2158,
"text": "In inference.py, we can decide for example to save an output.csv file with the X_test data in it:"
},
{
"code": null,
"e": 2344,
"s": 2256,
"text": "When you build it and run it you should be able to see the output.csv file in /mydata :"
},
{
"code": null,
"e": 2459,
"s": 2344,
"text": "We can also add the VOLUME instruction in the Dockerfile resulting in an image that will create a new mount point:"
},
{
"code": null,
"e": 2668,
"s": 2459,
"text": "With the name that we specify, the VOLUME instruction creates a mount point which is tagged as holding externally mounted volume from native host or other containers where we find the data we want to process."
},
{
"code": null,
"e": 3093,
"s": 2668,
"text": "For the future of your developments, it can be necessary to set environment variables from the beginning, just once at the build time, for persisting the trained model and maybe add additional data or metadata to a specific location. The advantage of setting environment variables is to avoid the hard code of the necessary paths all over your code and to better share your work with others on an agreed directory structure."
},
{
"code": null,
"e": 3144,
"s": 3093,
"text": "Let’s take another example, with a new Dockerfile:"
},
{
"code": null,
"e": 3198,
"s": 3144,
"text": "We need to add the environment variables to train.py:"
},
{
"code": null,
"e": 3216,
"s": 3198,
"text": "and inference.py:"
},
{
"code": null,
"e": 3395,
"s": 3216,
"text": "The goal was to produce quick and easy steps to build a Docker container with a simple machine learning model. Building is as simple as doing a docker build -t my-docker-image .."
},
{
"code": null,
"e": 4199,
"s": 3395,
"text": "From this step, we can start the deployment of our models which will be much simpler and removing the fear to publish and scale your machine learning model. The next step is to produce a workflow with a CI/CD tool (Continuous Integration/Continuous Delivery) such as Jenkins. Thanks to this approach, it will be possible to build and serve anywhere a docker container and expose a REST API so that external stakeholders can consume it. If you are training a deep learning model that needs high computational needs, you can move your containers to high performance computing servers or any platform of your choice such as on premises, private or public cloud. The idea is that you can scale your model but also create resilient deployment as you can scale the container across regions/availability zones."
}
] |
Difference between %s and %d in Python string
|
24 Jan, 2021
In this article, we will see the difference between %s and %d in Python. Here, we start with the proper explanation of one at a time, then both, and at last compare these.
The % symbol is used in Python with a large variety of data types and configurations. It is used as an argument specifier and string formatter. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. Following code illustrates the usage of %s symbol :
Python3
# declaring a string variablename = "Geek"#append a string within a string print("Hey, %s!" % name)
Output
Hey, Geek!
The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values.
Python3
#declaring numeric variablesnum = 2021#concatenating numeric value within stringprint("%d is here!!" % num)
Output
2021 is here!!
The decimal and rational numbers are rounded off to the absolute integral part and the numbers after the decimal are scraped off, that is only the integers are extracted. The following code illustrates the usage of %d with decimal and fractional numbers:
Python3
#declaring rational numberfrac_num = 8/3#concatenating numeric value within stringprint ("Rational number formatting using %d")print("%d is equal to 8/3 using this operator." % frac_num) #declaring decimal numberdec_num = 10.9785#concatenating numeric value within stringprint ("Decimal number formatting using %d")print("%d is equal to 10.9785 using this operator." % dec_num)
Output
Rational number formatting using %d
2 is equal to 8/3 using this operator.
Decimal number formatting using %d
10 is equal to 10.9785 using this operator.
We can use a combination of operators also within a single program. Before that first, clear some concepts by comparing as given below :
Python3
name = "Sita"age = 22print("Using %s and %d both")print ("%s's age is %d."%(name,age))
Output
Using %s and %d both
Sita's age is 22.
Note 1: %s automatically converts numeric value to a string without throwing an error.
Python3
name = "Sita"age = 22print("Using %s ")print ("%s's age is %s."%(name,age))
Output
Using %s
Sita's age is 22.
Note 2: %d, however, can only be used for numeric values. Otherwise, an error is returned.
Python3
name = "Sita"age = 22print("Using %d")print ("%d's age is %d."%(name,age))
Error
Using %d
Traceback (most recent call last):
File "<string>", line 4, in <module>
TypeError: %d format: a number is required, not str
Picked
python-string
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": "\n24 Jan, 2021"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "In this article, we will see the difference between %s and %d in Python. Here, we start with the proper explanation of one at a time, then both, and at last compare these."
},
{
"code": null,
"e": 584,
"s": 200,
"text": "The % symbol is used in Python with a large variety of data types and configurations. It is used as an argument specifier and string formatter. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string."
},
{
"code": null,
"e": 861,
"s": 584,
"text": "The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. Following code illustrates the usage of %s symbol :"
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Python3"
},
{
"code": "# declaring a string variablename = \"Geek\"#append a string within a string print(\"Hey, %s!\" % name)",
"e": 969,
"s": 869,
"text": null
},
{
"code": null,
"e": 976,
"s": 969,
"text": "Output"
},
{
"code": null,
"e": 987,
"s": 976,
"text": "Hey, Geek!"
},
{
"code": null,
"e": 1270,
"s": 987,
"text": "The %d operator is used as a placeholder to specify integer values, decimals or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values. "
},
{
"code": null,
"e": 1278,
"s": 1270,
"text": "Python3"
},
{
"code": "#declaring numeric variablesnum = 2021#concatenating numeric value within stringprint(\"%d is here!!\" % num)",
"e": 1386,
"s": 1278,
"text": null
},
{
"code": null,
"e": 1393,
"s": 1386,
"text": "Output"
},
{
"code": null,
"e": 1408,
"s": 1393,
"text": "2021 is here!!"
},
{
"code": null,
"e": 1663,
"s": 1408,
"text": "The decimal and rational numbers are rounded off to the absolute integral part and the numbers after the decimal are scraped off, that is only the integers are extracted. The following code illustrates the usage of %d with decimal and fractional numbers:"
},
{
"code": null,
"e": 1671,
"s": 1663,
"text": "Python3"
},
{
"code": "#declaring rational numberfrac_num = 8/3#concatenating numeric value within stringprint (\"Rational number formatting using %d\")print(\"%d is equal to 8/3 using this operator.\" % frac_num) #declaring decimal numberdec_num = 10.9785#concatenating numeric value within stringprint (\"Decimal number formatting using %d\")print(\"%d is equal to 10.9785 using this operator.\" % dec_num)",
"e": 2050,
"s": 1671,
"text": null
},
{
"code": null,
"e": 2057,
"s": 2050,
"text": "Output"
},
{
"code": null,
"e": 2211,
"s": 2057,
"text": "Rational number formatting using %d\n2 is equal to 8/3 using this operator.\nDecimal number formatting using %d\n10 is equal to 10.9785 using this operator."
},
{
"code": null,
"e": 2348,
"s": 2211,
"text": "We can use a combination of operators also within a single program. Before that first, clear some concepts by comparing as given below :"
},
{
"code": null,
"e": 2356,
"s": 2348,
"text": "Python3"
},
{
"code": "name = \"Sita\"age = 22print(\"Using %s and %d both\")print (\"%s's age is %d.\"%(name,age))",
"e": 2443,
"s": 2356,
"text": null
},
{
"code": null,
"e": 2450,
"s": 2443,
"text": "Output"
},
{
"code": null,
"e": 2489,
"s": 2450,
"text": "Using %s and %d both\nSita's age is 22."
},
{
"code": null,
"e": 2577,
"s": 2489,
"text": "Note 1: %s automatically converts numeric value to a string without throwing an error. "
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Python3"
},
{
"code": "name = \"Sita\"age = 22print(\"Using %s \")print (\"%s's age is %s.\"%(name,age))",
"e": 2661,
"s": 2585,
"text": null
},
{
"code": null,
"e": 2668,
"s": 2661,
"text": "Output"
},
{
"code": null,
"e": 2696,
"s": 2668,
"text": "Using %s \nSita's age is 22."
},
{
"code": null,
"e": 2788,
"s": 2696,
"text": "Note 2: %d, however, can only be used for numeric values. Otherwise, an error is returned. "
},
{
"code": null,
"e": 2796,
"s": 2788,
"text": "Python3"
},
{
"code": "name = \"Sita\"age = 22print(\"Using %d\")print (\"%d's age is %d.\"%(name,age))",
"e": 2871,
"s": 2796,
"text": null
},
{
"code": null,
"e": 2877,
"s": 2871,
"text": "Error"
},
{
"code": null,
"e": 3011,
"s": 2877,
"text": "Using %d\nTraceback (most recent call last):\n File \"<string>\", line 4, in <module>\nTypeError: %d format: a number is required, not str"
},
{
"code": null,
"e": 3018,
"s": 3011,
"text": "Picked"
},
{
"code": null,
"e": 3032,
"s": 3018,
"text": "python-string"
},
{
"code": null,
"e": 3039,
"s": 3032,
"text": "Python"
},
{
"code": null,
"e": 3137,
"s": 3039,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3169,
"s": 3137,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3196,
"s": 3169,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3217,
"s": 3196,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3240,
"s": 3217,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3296,
"s": 3240,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3327,
"s": 3296,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3369,
"s": 3327,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3411,
"s": 3369,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3450,
"s": 3411,
"text": "Python | Get unique values from a list"
}
] |
Output of Python programs | Set 9 (Dictionary)
|
09 Mar, 2022
Prerequisite: Dictionary 1) What is the output of the following program?
Python3
dictionary = {'GFG' : 'geeksforgeeks.org', 'google' : 'google.com', 'facebook' : 'facebook.com' }del dictionary['google'];for key, values in dictionary.items(): print(key)dictionary.clear();for key, values in dictionary.items(): print(key)del dictionary;for key, values in dictionary.items(): print(key)
a) Both b and d b) Runtime error c) GFG facebook d) facebook GFGAns. (a) Output:
facebook
GFG
Explanation: The statement: del dictionary; removes the entire dictionary, so iterating over a deleted dictionary throws a runtime error as follows:
Traceback (most recent call last):
File "cbeac2f0e35485f19ae7c07f6b416e84.py", line 12, in
for key, values in dictionary.items():
NameError: name 'dictionary' is not defined
2) What is the output of the following program?
Python3
dictionary1 = {'Google' : 1, 'Facebook' : 2, 'Microsoft' : 3 }dictionary2 = {'GFG' : 1, 'Microsoft' : 2, 'Youtube' : 3 }dictionary1.update(dictionary2);for key, values in dictionary1.items(): print(key, values)
a) Compilation error b) Runtime error c) (‘Google’, 1) (‘Facebook’, 2) (‘Youtube’, 3) (‘Microsoft’, 2) (‘GFG’, 1) d) None of theseAns. (c) Explanation: dictionary1.update(dictionary2) is used to update the entries of dictionary1 with entries of dictionary2. If there are same keys in two dictionaries, then the value in second dictionary is used.
3) What is the output of the following program?
Python3
dictionary1 = {'GFG' : 1, 'Google' : 2, 'GFG' : 3 }print(dictionary1['GFG']);
a) Compilation error due to duplicate keys b) Runtime time error due to duplicate keys c) 3 d) 1Ans. (c) Explanation: Here, GFG is the duplicate key. Duplicate keys are not allowed in python. If there are same keys in a dictionary, then the value assigned mostly recently is assigned to that key.
4) What is the output of the following program?
Python3
temp = dict()temp['key1'] = {'key1' : 44, 'key2' : 566}temp['key2'] = [1, 2, 3, 4]for (key, values) in temp.items(): print(values, end = "")
a) Compilation error b) {‘key1’: 44, ‘key2’: 566}[1, 2, 3, 4] c) Runtime error d) None of the aboveAns. (b) Explanation: A dictionary can hold any value such as an integer, string, list, or even another dictionary holding key-value pairs.
5) What is the output of the following Python program?
Python3
temp = {'GFG' : 1, 'Facebook' : 2, 'Google' : 3 }for (key, values) in temp.items(): print(key, values, end = " ")
a) Google 3 GFG 1 Facebook 2 b) Facebook 2 GFG 1 Google 3 c) Facebook 2 Google 3 GFG 1 d) Any of the above
e) None of the aboveAns. (e)
Explanation for (e): Since python 3.7 dictionaries are ordered in the insertion order.
This article is contributed by Mayank Kumar. 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.
rajeev0719singh
sarkardchamp
amartyaghoshgfg
python-dict
Python-Output
Program Output
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Different ways to copy a string in C/C++
Output of C++ Program | Set 1
Output of C Programs | Set 3
Output of Java Program | Set 3
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 126,
"s": 52,
"text": "Prerequisite: Dictionary 1) What is the output of the following program? "
},
{
"code": null,
"e": 134,
"s": 126,
"text": "Python3"
},
{
"code": "dictionary = {'GFG' : 'geeksforgeeks.org', 'google' : 'google.com', 'facebook' : 'facebook.com' }del dictionary['google'];for key, values in dictionary.items(): print(key)dictionary.clear();for key, values in dictionary.items(): print(key)del dictionary;for key, values in dictionary.items(): print(key)",
"e": 486,
"s": 134,
"text": null
},
{
"code": null,
"e": 567,
"s": 486,
"text": "a) Both b and d b) Runtime error c) GFG facebook d) facebook GFGAns. (a) Output:"
},
{
"code": null,
"e": 580,
"s": 567,
"text": "facebook\nGFG"
},
{
"code": null,
"e": 731,
"s": 580,
"text": "Explanation: The statement: del dictionary; removes the entire dictionary, so iterating over a deleted dictionary throws a runtime error as follows: "
},
{
"code": null,
"e": 912,
"s": 731,
"text": "Traceback (most recent call last):\n File \"cbeac2f0e35485f19ae7c07f6b416e84.py\", line 12, in \n for key, values in dictionary.items():\nNameError: name 'dictionary' is not defined"
},
{
"code": null,
"e": 961,
"s": 912,
"text": "2) What is the output of the following program? "
},
{
"code": null,
"e": 969,
"s": 961,
"text": "Python3"
},
{
"code": "dictionary1 = {'Google' : 1, 'Facebook' : 2, 'Microsoft' : 3 }dictionary2 = {'GFG' : 1, 'Microsoft' : 2, 'Youtube' : 3 }dictionary1.update(dictionary2);for key, values in dictionary1.items(): print(key, values)",
"e": 1267,
"s": 969,
"text": null
},
{
"code": null,
"e": 1615,
"s": 1267,
"text": "a) Compilation error b) Runtime error c) (‘Google’, 1) (‘Facebook’, 2) (‘Youtube’, 3) (‘Microsoft’, 2) (‘GFG’, 1) d) None of theseAns. (c) Explanation: dictionary1.update(dictionary2) is used to update the entries of dictionary1 with entries of dictionary2. If there are same keys in two dictionaries, then the value in second dictionary is used. "
},
{
"code": null,
"e": 1664,
"s": 1615,
"text": "3) What is the output of the following program? "
},
{
"code": null,
"e": 1672,
"s": 1664,
"text": "Python3"
},
{
"code": "dictionary1 = {'GFG' : 1, 'Google' : 2, 'GFG' : 3 }print(dictionary1['GFG']);",
"e": 1792,
"s": 1672,
"text": null
},
{
"code": null,
"e": 2089,
"s": 1792,
"text": "a) Compilation error due to duplicate keys b) Runtime time error due to duplicate keys c) 3 d) 1Ans. (c) Explanation: Here, GFG is the duplicate key. Duplicate keys are not allowed in python. If there are same keys in a dictionary, then the value assigned mostly recently is assigned to that key."
},
{
"code": null,
"e": 2138,
"s": 2089,
"text": "4) What is the output of the following program? "
},
{
"code": null,
"e": 2146,
"s": 2138,
"text": "Python3"
},
{
"code": "temp = dict()temp['key1'] = {'key1' : 44, 'key2' : 566}temp['key2'] = [1, 2, 3, 4]for (key, values) in temp.items(): print(values, end = \"\")",
"e": 2290,
"s": 2146,
"text": null
},
{
"code": null,
"e": 2530,
"s": 2290,
"text": "a) Compilation error b) {‘key1’: 44, ‘key2’: 566}[1, 2, 3, 4] c) Runtime error d) None of the aboveAns. (b) Explanation: A dictionary can hold any value such as an integer, string, list, or even another dictionary holding key-value pairs. "
},
{
"code": null,
"e": 2586,
"s": 2530,
"text": "5) What is the output of the following Python program? "
},
{
"code": null,
"e": 2594,
"s": 2586,
"text": "Python3"
},
{
"code": "temp = {'GFG' : 1, 'Facebook' : 2, 'Google' : 3 }for (key, values) in temp.items(): print(key, values, end = \" \")",
"e": 2732,
"s": 2594,
"text": null
},
{
"code": null,
"e": 2839,
"s": 2732,
"text": "a) Google 3 GFG 1 Facebook 2 b) Facebook 2 GFG 1 Google 3 c) Facebook 2 Google 3 GFG 1 d) Any of the above"
},
{
"code": null,
"e": 2868,
"s": 2839,
"text": "e) None of the aboveAns. (e)"
},
{
"code": null,
"e": 2955,
"s": 2868,
"text": "Explanation for (e): Since python 3.7 dictionaries are ordered in the insertion order."
},
{
"code": null,
"e": 3376,
"s": 2955,
"text": "This article is contributed by Mayank Kumar. 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": 3392,
"s": 3376,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3405,
"s": 3392,
"text": "sarkardchamp"
},
{
"code": null,
"e": 3421,
"s": 3405,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 3433,
"s": 3421,
"text": "python-dict"
},
{
"code": null,
"e": 3447,
"s": 3433,
"text": "Python-Output"
},
{
"code": null,
"e": 3462,
"s": 3447,
"text": "Program Output"
},
{
"code": null,
"e": 3469,
"s": 3462,
"text": "Python"
},
{
"code": null,
"e": 3481,
"s": 3469,
"text": "python-dict"
},
{
"code": null,
"e": 3579,
"s": 3481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3594,
"s": 3579,
"text": "Runtime Errors"
},
{
"code": null,
"e": 3635,
"s": 3594,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 3665,
"s": 3635,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 3694,
"s": 3665,
"text": "Output of C Programs | Set 3"
},
{
"code": null,
"e": 3725,
"s": 3694,
"text": "Output of Java Program | Set 3"
},
{
"code": null,
"e": 3753,
"s": 3725,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3775,
"s": 3753,
"text": "Python map() function"
},
{
"code": null,
"e": 3825,
"s": 3775,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3843,
"s": 3825,
"text": "Python Dictionary"
}
] |
Solidity – Basics of Interface
|
11 May, 2022
Interfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in interfaces do not have any statements. Functions of Interface can be only of type external. They can inherit from other interfaces, but they can’t inherit from other contracts. An interface can have enum, structs which can be accessed using interface name dot notation.
Example: In the below example, the contract thisContract implements an interface InterfaceExample and implements all the interface functions.
Solidity
// Solidity program to // demonstrate the working // of the interface pragma solidity 0.4.19; // A simple interfaceinterface InterfaceExample{ // Functions having only // declaration not definition function getStr( ) public view returns(string memory); function setValue( uint _num1, uint _num2) public; function add( ) public view returns(uint);} // Contract that implements interfacecontract thisContract is InterfaceExample{ // Private variables uint private num1; uint private num2; // Function definitions of functions // declared inside an interface function getStr( ) public view returns(string memory){ return "GeeksForGeeks"; } // Function to set the values // of the private variables function setValue( uint _num1, uint _num2) public{ num1 = _num1; num2 = _num2; } // Function to add 2 numbers function add( ) public view returns(uint){ return num1 + num2; } } contract call{ //Creating an object InterfaceExample obj; function call() public{ obj = new thisContract(); } // Function to print string // value and the sum value function getValue( ) public returns(uint){ obj.getStr; obj.setValue(10, 16); return obj.add(); }}
Output :
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 594,
"s": 28,
"text": "Interfaces are the same as abstract contracts created by using an interface keyword, also known as a pure abstract contract. Interfaces do not have any definition or any state variables, constructors, or any function with implementation, they only contain function declarations i.e. functions in interfaces do not have any statements. Functions of Interface can be only of type external. They can inherit from other interfaces, but they can’t inherit from other contracts. An interface can have enum, structs which can be accessed using interface name dot notation."
},
{
"code": null,
"e": 736,
"s": 594,
"text": "Example: In the below example, the contract thisContract implements an interface InterfaceExample and implements all the interface functions."
},
{
"code": null,
"e": 745,
"s": 736,
"text": "Solidity"
},
{
"code": "// Solidity program to // demonstrate the working // of the interface pragma solidity 0.4.19; // A simple interfaceinterface InterfaceExample{ // Functions having only // declaration not definition function getStr( ) public view returns(string memory); function setValue( uint _num1, uint _num2) public; function add( ) public view returns(uint);} // Contract that implements interfacecontract thisContract is InterfaceExample{ // Private variables uint private num1; uint private num2; // Function definitions of functions // declared inside an interface function getStr( ) public view returns(string memory){ return \"GeeksForGeeks\"; } // Function to set the values // of the private variables function setValue( uint _num1, uint _num2) public{ num1 = _num1; num2 = _num2; } // Function to add 2 numbers function add( ) public view returns(uint){ return num1 + num2; } } contract call{ //Creating an object InterfaceExample obj; function call() public{ obj = new thisContract(); } // Function to print string // value and the sum value function getValue( ) public returns(uint){ obj.getStr; obj.setValue(10, 16); return obj.add(); }}",
"e": 2089,
"s": 745,
"text": null
},
{
"code": null,
"e": 2099,
"s": 2089,
"text": "Output : "
},
{
"code": null,
"e": 2112,
"s": 2101,
"text": "Blockchain"
},
{
"code": null,
"e": 2121,
"s": 2112,
"text": "Solidity"
}
] |
How to determine if a binary tree is height-balanced?
|
16 Jun, 2022
A tree where no leaf is much farther away from the root than any other leaf. Different balancing schemes allow different definitions of “much farther” and different amounts of work to keep them balanced.Consider a height-balancing scheme where the following conditions should be checked to determine if a binary tree is balanced. An empty tree is height-balanced. A non-empty binary tree T is balanced if:
Left subtree of T is balanced Right subtree of T is balancedThe difference between heights of left subtree and the right subtree is not more than 1.
Left subtree of T is balanced
Right subtree of T is balanced
The difference between heights of left subtree and the right subtree is not more than 1.
The above height-balancing scheme is used in AVL trees. The diagram below shows two trees, one of them is height-balanced and other is not. The second tree is not height-balanced because height of left subtree is 2 more than height of right subtree.
To check if a tree is height-balanced, get the height of left and right subtrees. Return true if difference between heights is not more than 1 and left and right subtrees are balanced, otherwise return false.
C++
C
Java
Python3
C#
Javascript
/* CPP program to check ifa tree is height-balanced or not */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node {public: int data; node* left; node* right;}; /* Returns the height of a binary tree */int height(node* node); /* Returns true if binary treewith root as root is height-balanced */bool isBalanced(node* root){ int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (root == NULL) return 1; /* Get the height of left and right sub trees */ lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; /* If we reach here then tree is not height-balanced */ return 0;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* returns maximum of two integers */int max(int a, int b){ return (a >= b) ? a : b;} /* The function Compute the "height"of a tree. Height is the number ofnodes along the longest path fromthe root node down to the farthest leaf node.*/int height(node* node){ /* base case tree is empty */ if (node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right));} /* Helper function that allocatesa new node with the given dataand NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Driver codeint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(8); if (isBalanced(root)) cout << "Tree is balanced"; else cout << "Tree is not balanced"; return 0;} // This code is contributed by rathbhupendra
/* C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* Returns the height of a binary tree */int height(struct node* node); /* Returns true if binary tree with root as root is height-balanced */bool isBalanced(struct node* root){ int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (root == NULL) return 1; /* Get the height of left and right sub trees */ lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; /* If we reach here then tree is not height-balanced */ return 0;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* returns maximum of two integers */int max(int a, int b){ return (a >= b) ? a : b;} /* The function Compute the "height" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ /* base case tree is empty */ if (node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(8); if (isBalanced(root)) printf("Tree is balanced"); else printf("Tree is not balanced"); getchar(); return 0;}
/* Java program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree { Node root; /* Returns true if binary tree with root as root is height-balanced */ boolean isBalanced(Node node) { int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (node == null) return true; /* Get the height of left and right sub trees */ lh = height(node.left); rh = height(node.right); if (Math.abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) return true; /* If we reach here then tree is not height-balanced */ return false; } /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* The function Compute the "height" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { /* base case tree is empty */ if (node == null) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.max(height(node.left), height(node.right)); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(8); if (tree.isBalanced(tree.root)) System.out.println("Tree is balanced"); else System.out.println("Tree is not balanced"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
"""Python3 program to check if a tree is height-balanced"""# A binary tree Node class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None # function to find height of binary treedef height(root): # base condition when binary tree is empty if root is None: return 0 return max(height(root.left), height(root.right)) + 1 # function to check if tree is height-balanced or notdef isBalanced(root): # Base condition if root is None: return True # for left and right subtree height lh = height(root.left) rh = height(root.right) # allowed values for (lh - rh) are 1, -1, 0 if (abs(lh - rh) <= 1) and isBalanced( root.left) is True and isBalanced( root.right) is True: return True # if we reach here means tree is not # height-balanced tree return False # Driver function to test the above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.left.left.left = Node(8)if isBalanced(root): print("Tree is balanced")else: print("Tree is not balanced") # This code is contributed by Shweta Singh
using System; /* C# program to determine if binary tree isheight balanced or not */ /* A binary tree node has data, pointer to left child,and a pointer to right child */public class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree { public Node root; /* Returns true if binary tree with root as root is height-balanced */ public virtual bool isBalanced(Node node) { int lh; // for height of left subtree int rh; // for height of right subtree /* If tree is empty then return true */ if (node == null) { return true; } /* Get the height of left and right sub trees */ lh = height(node.left); rh = height(node.right); if (Math.Abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) { return true; } /* If we reach here then tree is not height-balanced */ return false; } /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* The function Compute the "height" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { /* base case tree is empty */ if (node == null) { return 0; } /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.Max(height(node.left), height(node.right)); } public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(8); if (tree.isBalanced(tree.root)) { Console.WriteLine("Tree is balanced"); } else { Console.WriteLine("Tree is not balanced"); } }} // This code is contributed by Shrikant13
<script> // JavaScript program to check if a tree is height-balanced// A binary tree Node class Node{ // Constructor to create a new Node constructor(data){ this.data = data this.left = null this.right = null }} // function to find height of binary treefunction height(root){ // base condition when binary tree is empty if(root == null) return 0 return Math.max(height(root.left), height(root.right)) + 1} // function to check if tree is height-balanced or notfunction isBalanced(root){ // Base condition if(root == null) return true // for left and right subtree height let lh = height(root.left) let rh = height(root.right) // allowed values for (lh - rh) are 1, -1, 0 if (Math.abs(lh - rh) <= 1 && isBalanced( root.left)== true && isBalanced( root.right) == true) return true // if we reach here means tree is not // height-balanced tree return false} // Driver function to test the above functionlet root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(4)root.left.right = new Node(5)root.left.left.left = new Node(8)if(isBalanced(root)) document.write("Tree is balanced","</br>")else document.write("Tree is not balanced","</br>") // This code is contributed by ShinjanPatra </script>
Output:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Tree is not balanced
Time Complexity: O(n^2) in case of full binary tree.
Auxiliary Space: O(n) space for call stack since using recursion
Optimized implementation: Above implementation can be optimized by calculating the height in the same recursion rather than calling a height() function separately. Thanks to Amar for suggesting this optimized version. This optimization reduces time complexity to O(n).
C++
C
Java
Python3
C#
Javascript
/* C++ program to check if a treeis height-balanced or not */#include <bits/stdc++.h>using namespace std;#define bool int /* A binary tree node has data,pointer to left child anda pointer to right child */class node {public: int data; node* left; node* right;}; /* The function returns true if root isbalanced else false The second parameteris to store the height of tree. Initially,we need to pass a pointer to a location withvalue as 0. We can also write a wrapperover this function */bool isBalanced(node* root, int* height){ /* lh --> Height of left subtree rh --> Height of right subtree */ int lh = 0, rh = 0; /* l will be true if left subtree is balanced and r will be true if right subtree is balanced */ int l = 0, r = 0; if (root == NULL) { *height = 0; return 1; } /* Get the heights of left and right subtrees in lh and rh And store the returned values in l and r */ l = isBalanced(root->left, &lh); r = isBalanced(root->right, &rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ *height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (abs(lh - rh) >= 2) return 0; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Driver codeint main(){ int height = 0; /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 6 / 7 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(7); if (isBalanced(root, &height)) cout << "Tree is balanced"; else cout << "Tree is not balanced"; return 0;} // This is code is contributed by rathbhupendra
/* C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* The function returns true if root is balanced else false The second parameter is to store the height of tree. Initially, we need to pass a pointer to a location with value as 0. We can also write a wrapper over this function */bool isBalanced(struct node* root, int* height){ /* lh --> Height of left subtree rh --> Height of right subtree */ int lh = 0, rh = 0; /* l will be true if left subtree is balanced and r will be true if right subtree is balanced */ int l = 0, r = 0; if (root == NULL) { *height = 0; return 1; } /* Get the heights of left and right subtrees in lh and rh And store the returned values in l and r */ l = isBalanced(root->left, &lh); r = isBalanced(root->right, &rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ *height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (abs(lh - rh) >= 2) return 0; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} // Driver codeint main(){ int height = 0; /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 6 / 7 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(7); if (isBalanced(root, &height)) printf("Tree is balanced"); else printf("Tree is not balanced"); getchar(); return 0;}
/* Java program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} // A wrapper class used to modify height across// recursive calls.class Height { int height = 0;} class BinaryTree { Node root; /* Returns true if binary tree with root as root is height-balanced */ boolean isBalanced(Node root, Height height) { /* If tree is empty then return true */ if (root == null) { height.height = 0; return true; } /* Get heights of left and right sub trees */ Height lheight = new Height(), rheight = new Height(); boolean l = isBalanced(root.left, lheight); boolean r = isBalanced(root.right, rheight); int lh = lheight.height, rh = rheight.height; /* Height of current node is max of heights of left and right subtrees plus 1*/ height.height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (Math.abs(lh - rh) >= 2) return false; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r; } public static void main(String args[]) { Height height = new Height(); /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 6 / 7 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); if (tree.isBalanced(tree.root, height)) System.out.println("Tree is balanced"); else System.out.println("Tree is not balanced"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)
"""Python3 program to check if Binary tree isheight-balanced""" # A binary tree nodeclass Node: # constructor to create node of # binary tree def __init__(self, data): self.data = data self.left = self.right = None # utility class to pass height objectclass Height: def __init__(self): self.height = 0 # function to find height of binary treedef height(root): # base condition when binary tree is empty if root is None: return 0 return max(height(root.left), height(root.right)) + 1 # helper function to check if binary# tree is height balanceddef isBalanced(root): # Base condition when tree is # empty return true if root is None: return True # lh and rh to store height of # left and right subtree lh = Height() rh = Height() # Calculating height of left and right tree lh.height = height(root.left) rh.height = height(root.right) # l and r are used to check if left # and right subtree are balanced l = isBalanced(root.left) r = isBalanced(root.right) # height of tree is maximum of # left subtree height and # right subtree height plus 1 if abs(lh.height - rh.height) <= 1: return l and r # if we reach here then the tree # is not balanced return False # Driver function to test the above function"""Constructed binary tree is 1 / \ 2 3 / \ / 4 5 6 / 7"""# to store the height of tree during traversal root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.left.left.left = Node(7) if isBalanced(root): print('Tree is balanced')else: print('Tree is not balanced') # This code is contributed by Shubhank Gupta
using System; /* C# program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */public class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} // A wrapper class used to modify height across// recursive calls.public class Height { public int height = 0;} public class BinaryTree { public Node root; /* Returns true if binary tree with root as root is height-balanced */ public virtual bool isBalanced(Node root, Height height) { /* If tree is empty then return true */ if (root == null) { height.height = 0; return true; } /* Get heights of left and right sub trees */ Height lheight = new Height(), rheight = new Height(); bool l = isBalanced(root.left, lheight); bool r = isBalanced(root.right, rheight); int lh = lheight.height, rh = rheight.height; /* Height of current node is max of heights of left and right subtrees plus 1*/ height.height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (Math.Abs(lh - rh) >= 2) { return false; } /* If this node is balanced and left and right subtrees are balanced then return true */ else { return l && r; } } /* The function Compute the "height" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { /* base case tree is empty */ if (node == null) { return 0; } /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.Max(height(node.left), height(node.right)); } public static void Main(string[] args) { Height height = new Height(); /* Constructed binary tree is 1 / \ 2 3 / \ / 4 5 6 / 7 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); if (tree.isBalanced(tree.root, height)) { Console.WriteLine("Tree is balanced"); } else { Console.WriteLine("Tree is not balanced"); } }} // This code is contributed by Shrikant13
<script> // JavaScript program to check if Binary tree is height-balanced // A binary tree nodeclass Node{ // constructor to create node of // binary tree constructor(data){ this.data = data this.left = this.right = null }} // utility class to pass height objectclass Height{ constructor() { this.height = 0 }} // function to find height of binary treefunction height(root){ // base condition when binary tree is empty if(root == null) return 0 return Math.max(height(root.left), height(root.right)) + 1 } // helper function to check if binary// tree is height balancedfunction isBalanced(root){ // Base condition when tree is // empty return true if(root == null) return true // lh and rh to store height of // left and right subtree let lh = new Height() let rh = new Height() // Calculating height of left and right tree lh.height = height(root.left) rh.height = height(root.right) // l and r are used to check if left // and right subtree are balanced let l = isBalanced(root.left) let r = isBalanced(root.right) // height of tree is maximum of // left subtree height and // right subtree height plus 1 if(Math.abs(lh.height - rh.height) <= 1) return l && r // if we reach here then the tree // is not balanced return false } // Driver function to test the above function // Constructed binary tree is// 1// / \// 2 3// / \ /// 4 5 6 / 7//// to store the height of tree during traversal let root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(4)root.left.right = new Node(5)root.right.left = new Node(6)root.left.left.left = new Node(7) if(isBalanced(root)) document.write('Tree is balanced',"</br>")else document.write('Tree is not balanced',"</br>") // This code is contributed by shinjanpatra</script>
Output:
Tree is balanced
Time Complexity: O(n) Auxiliary Space: O(n)
https://www.youtube.com/watch?v=qIdVVH1tKM4
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
shweta44
shrikanth13
rathbhupendra
nobody_cares
HarshUpadhyay
saurabhlohiya1234
AakashYadav4
Shubhank Gupta
prasanna1995
adnanirshad158
shinjanpatra
technophpfij
hardikkoriintern
Amazon
Belzabar
Goldman Sachs
InMobi
Intel
Microsoft
Paytm
Self-Balancing-BST
Synopsys
Walmart
Zillious
Tree
Paytm
Amazon
Microsoft
Walmart
Goldman Sachs
Synopsys
Intel
Zillious
InMobi
Belzabar
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 461,
"s": 54,
"text": "A tree where no leaf is much farther away from the root than any other leaf. Different balancing schemes allow different definitions of “much farther” and different amounts of work to keep them balanced.Consider a height-balancing scheme where the following conditions should be checked to determine if a binary tree is balanced. An empty tree is height-balanced. A non-empty binary tree T is balanced if: "
},
{
"code": null,
"e": 611,
"s": 461,
"text": "Left subtree of T is balanced Right subtree of T is balancedThe difference between heights of left subtree and the right subtree is not more than 1. "
},
{
"code": null,
"e": 642,
"s": 611,
"text": "Left subtree of T is balanced "
},
{
"code": null,
"e": 673,
"s": 642,
"text": "Right subtree of T is balanced"
},
{
"code": null,
"e": 763,
"s": 673,
"text": "The difference between heights of left subtree and the right subtree is not more than 1. "
},
{
"code": null,
"e": 1014,
"s": 763,
"text": "The above height-balancing scheme is used in AVL trees. The diagram below shows two trees, one of them is height-balanced and other is not. The second tree is not height-balanced because height of left subtree is 2 more than height of right subtree. "
},
{
"code": null,
"e": 1224,
"s": 1014,
"text": "To check if a tree is height-balanced, get the height of left and right subtrees. Return true if difference between heights is not more than 1 and left and right subtrees are balanced, otherwise return false. "
},
{
"code": null,
"e": 1228,
"s": 1224,
"text": "C++"
},
{
"code": null,
"e": 1230,
"s": 1228,
"text": "C"
},
{
"code": null,
"e": 1235,
"s": 1230,
"text": "Java"
},
{
"code": null,
"e": 1243,
"s": 1235,
"text": "Python3"
},
{
"code": null,
"e": 1246,
"s": 1243,
"text": "C#"
},
{
"code": null,
"e": 1257,
"s": 1246,
"text": "Javascript"
},
{
"code": "/* CPP program to check ifa tree is height-balanced or not */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data,pointer to left child anda pointer to right child */class node {public: int data; node* left; node* right;}; /* Returns the height of a binary tree */int height(node* node); /* Returns true if binary treewith root as root is height-balanced */bool isBalanced(node* root){ int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (root == NULL) return 1; /* Get the height of left and right sub trees */ lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; /* If we reach here then tree is not height-balanced */ return 0;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* returns maximum of two integers */int max(int a, int b){ return (a >= b) ? a : b;} /* The function Compute the \"height\"of a tree. Height is the number ofnodes along the longest path fromthe root node down to the farthest leaf node.*/int height(node* node){ /* base case tree is empty */ if (node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right));} /* Helper function that allocatesa new node with the given dataand NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Driver codeint main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(8); if (isBalanced(root)) cout << \"Tree is balanced\"; else cout << \"Tree is not balanced\"; return 0;} // This code is contributed by rathbhupendra",
"e": 3319,
"s": 1257,
"text": null
},
{
"code": "/* C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* Returns the height of a binary tree */int height(struct node* node); /* Returns true if binary tree with root as root is height-balanced */bool isBalanced(struct node* root){ int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (root == NULL) return 1; /* Get the height of left and right sub trees */ lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; /* If we reach here then tree is not height-balanced */ return 0;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* returns maximum of two integers */int max(int a, int b){ return (a >= b) ? a : b;} /* The function Compute the \"height\" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ /* base case tree is empty */ if (node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} int main(){ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(8); if (isBalanced(root)) printf(\"Tree is balanced\"); else printf(\"Tree is not balanced\"); getchar(); return 0;}",
"e": 5427,
"s": 3319,
"text": null
},
{
"code": "/* Java program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree { Node root; /* Returns true if binary tree with root as root is height-balanced */ boolean isBalanced(Node node) { int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (node == null) return true; /* Get the height of left and right sub trees */ lh = height(node.left); rh = height(node.right); if (Math.abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) return true; /* If we reach here then tree is not height-balanced */ return false; } /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* The function Compute the \"height\" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { /* base case tree is empty */ if (node == null) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.max(height(node.left), height(node.right)); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(8); if (tree.isBalanced(tree.root)) System.out.println(\"Tree is balanced\"); else System.out.println(\"Tree is not balanced\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 7462,
"s": 5427,
"text": null
},
{
"code": "\"\"\"Python3 program to check if a tree is height-balanced\"\"\"# A binary tree Node class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None # function to find height of binary treedef height(root): # base condition when binary tree is empty if root is None: return 0 return max(height(root.left), height(root.right)) + 1 # function to check if tree is height-balanced or notdef isBalanced(root): # Base condition if root is None: return True # for left and right subtree height lh = height(root.left) rh = height(root.right) # allowed values for (lh - rh) are 1, -1, 0 if (abs(lh - rh) <= 1) and isBalanced( root.left) is True and isBalanced( root.right) is True: return True # if we reach here means tree is not # height-balanced tree return False # Driver function to test the above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.left.left.left = Node(8)if isBalanced(root): print(\"Tree is balanced\")else: print(\"Tree is not balanced\") # This code is contributed by Shweta Singh",
"e": 8687,
"s": 7462,
"text": null
},
{
"code": "using System; /* C# program to determine if binary tree isheight balanced or not */ /* A binary tree node has data, pointer to left child,and a pointer to right child */public class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree { public Node root; /* Returns true if binary tree with root as root is height-balanced */ public virtual bool isBalanced(Node node) { int lh; // for height of left subtree int rh; // for height of right subtree /* If tree is empty then return true */ if (node == null) { return true; } /* Get the height of left and right sub trees */ lh = height(node.left); rh = height(node.right); if (Math.Abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) { return true; } /* If we reach here then tree is not height-balanced */ return false; } /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* The function Compute the \"height\" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { /* base case tree is empty */ if (node == null) { return 0; } /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.Max(height(node.left), height(node.right)); } public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(8); if (tree.isBalanced(tree.root)) { Console.WriteLine(\"Tree is balanced\"); } else { Console.WriteLine(\"Tree is not balanced\"); } }} // This code is contributed by Shrikant13",
"e": 10813,
"s": 8687,
"text": null
},
{
"code": "<script> // JavaScript program to check if a tree is height-balanced// A binary tree Node class Node{ // Constructor to create a new Node constructor(data){ this.data = data this.left = null this.right = null }} // function to find height of binary treefunction height(root){ // base condition when binary tree is empty if(root == null) return 0 return Math.max(height(root.left), height(root.right)) + 1} // function to check if tree is height-balanced or notfunction isBalanced(root){ // Base condition if(root == null) return true // for left and right subtree height let lh = height(root.left) let rh = height(root.right) // allowed values for (lh - rh) are 1, -1, 0 if (Math.abs(lh - rh) <= 1 && isBalanced( root.left)== true && isBalanced( root.right) == true) return true // if we reach here means tree is not // height-balanced tree return false} // Driver function to test the above functionlet root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(4)root.left.right = new Node(5)root.left.left.left = new Node(8)if(isBalanced(root)) document.write(\"Tree is balanced\",\"</br>\")else document.write(\"Tree is not balanced\",\"</br>\") // This code is contributed by ShinjanPatra </script>",
"e": 12154,
"s": 10813,
"text": null
},
{
"code": null,
"e": 12163,
"s": 12154,
"text": "Output: "
},
{
"code": null,
"e": 12172,
"s": 12163,
"text": "Chapters"
},
{
"code": null,
"e": 12199,
"s": 12172,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 12249,
"s": 12199,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 12272,
"s": 12249,
"text": "captions off, selected"
},
{
"code": null,
"e": 12280,
"s": 12272,
"text": "English"
},
{
"code": null,
"e": 12298,
"s": 12280,
"text": "default, selected"
},
{
"code": null,
"e": 12322,
"s": 12298,
"text": "This is a modal window."
},
{
"code": null,
"e": 12391,
"s": 12322,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 12413,
"s": 12391,
"text": "End of dialog window."
},
{
"code": null,
"e": 12434,
"s": 12413,
"text": "Tree is not balanced"
},
{
"code": null,
"e": 12487,
"s": 12434,
"text": "Time Complexity: O(n^2) in case of full binary tree."
},
{
"code": null,
"e": 12552,
"s": 12487,
"text": "Auxiliary Space: O(n) space for call stack since using recursion"
},
{
"code": null,
"e": 12821,
"s": 12552,
"text": "Optimized implementation: Above implementation can be optimized by calculating the height in the same recursion rather than calling a height() function separately. Thanks to Amar for suggesting this optimized version. This optimization reduces time complexity to O(n)."
},
{
"code": null,
"e": 12825,
"s": 12821,
"text": "C++"
},
{
"code": null,
"e": 12827,
"s": 12825,
"text": "C"
},
{
"code": null,
"e": 12832,
"s": 12827,
"text": "Java"
},
{
"code": null,
"e": 12840,
"s": 12832,
"text": "Python3"
},
{
"code": null,
"e": 12843,
"s": 12840,
"text": "C#"
},
{
"code": null,
"e": 12854,
"s": 12843,
"text": "Javascript"
},
{
"code": "/* C++ program to check if a treeis height-balanced or not */#include <bits/stdc++.h>using namespace std;#define bool int /* A binary tree node has data,pointer to left child anda pointer to right child */class node {public: int data; node* left; node* right;}; /* The function returns true if root isbalanced else false The second parameteris to store the height of tree. Initially,we need to pass a pointer to a location withvalue as 0. We can also write a wrapperover this function */bool isBalanced(node* root, int* height){ /* lh --> Height of left subtree rh --> Height of right subtree */ int lh = 0, rh = 0; /* l will be true if left subtree is balanced and r will be true if right subtree is balanced */ int l = 0, r = 0; if (root == NULL) { *height = 0; return 1; } /* Get the heights of left and right subtrees in lh and rh And store the returned values in l and r */ l = isBalanced(root->left, &lh); r = isBalanced(root->right, &rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ *height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (abs(lh - rh) >= 2) return 0; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Driver codeint main(){ int height = 0; /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 6 / 7 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(7); if (isBalanced(root, &height)) cout << \"Tree is balanced\"; else cout << \"Tree is not balanced\"; return 0;} // This is code is contributed by rathbhupendra",
"e": 15180,
"s": 12854,
"text": null
},
{
"code": "/* C program to check if a tree is height-balanced or not */#include <stdio.h>#include <stdlib.h>#define bool int /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* The function returns true if root is balanced else false The second parameter is to store the height of tree. Initially, we need to pass a pointer to a location with value as 0. We can also write a wrapper over this function */bool isBalanced(struct node* root, int* height){ /* lh --> Height of left subtree rh --> Height of right subtree */ int lh = 0, rh = 0; /* l will be true if left subtree is balanced and r will be true if right subtree is balanced */ int l = 0, r = 0; if (root == NULL) { *height = 0; return 1; } /* Get the heights of left and right subtrees in lh and rh And store the returned values in l and r */ l = isBalanced(root->left, &lh); r = isBalanced(root->right, &rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ *height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (abs(lh - rh) >= 2) return 0; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r;} /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} // Driver codeint main(){ int height = 0; /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 6 / 7 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->left->left->left = newNode(7); if (isBalanced(root, &height)) printf(\"Tree is balanced\"); else printf(\"Tree is not balanced\"); getchar(); return 0;}",
"e": 17543,
"s": 15180,
"text": null
},
{
"code": "/* Java program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} // A wrapper class used to modify height across// recursive calls.class Height { int height = 0;} class BinaryTree { Node root; /* Returns true if binary tree with root as root is height-balanced */ boolean isBalanced(Node root, Height height) { /* If tree is empty then return true */ if (root == null) { height.height = 0; return true; } /* Get heights of left and right sub trees */ Height lheight = new Height(), rheight = new Height(); boolean l = isBalanced(root.left, lheight); boolean r = isBalanced(root.right, rheight); int lh = lheight.height, rh = rheight.height; /* Height of current node is max of heights of left and right subtrees plus 1*/ height.height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (Math.abs(lh - rh) >= 2) return false; /* If this node is balanced and left and right subtrees are balanced then return true */ else return l && r; } public static void main(String args[]) { Height height = new Height(); /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 6 / 7 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); if (tree.isBalanced(tree.root, height)) System.out.println(\"Tree is balanced\"); else System.out.println(\"Tree is not balanced\"); }} // This code has been contributed by Mayank Jaiswal(mayank_24)",
"e": 19834,
"s": 17543,
"text": null
},
{
"code": "\"\"\"Python3 program to check if Binary tree isheight-balanced\"\"\" # A binary tree nodeclass Node: # constructor to create node of # binary tree def __init__(self, data): self.data = data self.left = self.right = None # utility class to pass height objectclass Height: def __init__(self): self.height = 0 # function to find height of binary treedef height(root): # base condition when binary tree is empty if root is None: return 0 return max(height(root.left), height(root.right)) + 1 # helper function to check if binary# tree is height balanceddef isBalanced(root): # Base condition when tree is # empty return true if root is None: return True # lh and rh to store height of # left and right subtree lh = Height() rh = Height() # Calculating height of left and right tree lh.height = height(root.left) rh.height = height(root.right) # l and r are used to check if left # and right subtree are balanced l = isBalanced(root.left) r = isBalanced(root.right) # height of tree is maximum of # left subtree height and # right subtree height plus 1 if abs(lh.height - rh.height) <= 1: return l and r # if we reach here then the tree # is not balanced return False # Driver function to test the above function\"\"\"Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 6 / 7\"\"\"# to store the height of tree during traversal root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.left.left.left = Node(7) if isBalanced(root): print('Tree is balanced')else: print('Tree is not balanced') # This code is contributed by Shubhank Gupta",
"e": 21613,
"s": 19834,
"text": null
},
{
"code": "using System; /* C# program to determine if binary tree is height balanced or not */ /* A binary tree node has data, pointer to left child, and a pointer to right child */public class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} // A wrapper class used to modify height across// recursive calls.public class Height { public int height = 0;} public class BinaryTree { public Node root; /* Returns true if binary tree with root as root is height-balanced */ public virtual bool isBalanced(Node root, Height height) { /* If tree is empty then return true */ if (root == null) { height.height = 0; return true; } /* Get heights of left and right sub trees */ Height lheight = new Height(), rheight = new Height(); bool l = isBalanced(root.left, lheight); bool r = isBalanced(root.right, rheight); int lh = lheight.height, rh = rheight.height; /* Height of current node is max of heights of left and right subtrees plus 1*/ height.height = (lh > rh ? lh : rh) + 1; /* If difference between heights of left and right subtrees is more than 2 then this node is not balanced so return 0 */ if (Math.Abs(lh - rh) >= 2) { return false; } /* If this node is balanced and left and right subtrees are balanced then return true */ else { return l && r; } } /* The function Compute the \"height\" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { /* base case tree is empty */ if (node == null) { return 0; } /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.Max(height(node.left), height(node.right)); } public static void Main(string[] args) { Height height = new Height(); /* Constructed binary tree is 1 / \\ 2 3 / \\ / 4 5 6 / 7 */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.right.right = new Node(6); tree.root.left.left.left = new Node(7); if (tree.isBalanced(tree.root, height)) { Console.WriteLine(\"Tree is balanced\"); } else { Console.WriteLine(\"Tree is not balanced\"); } }} // This code is contributed by Shrikant13",
"e": 24481,
"s": 21613,
"text": null
},
{
"code": "<script> // JavaScript program to check if Binary tree is height-balanced // A binary tree nodeclass Node{ // constructor to create node of // binary tree constructor(data){ this.data = data this.left = this.right = null }} // utility class to pass height objectclass Height{ constructor() { this.height = 0 }} // function to find height of binary treefunction height(root){ // base condition when binary tree is empty if(root == null) return 0 return Math.max(height(root.left), height(root.right)) + 1 } // helper function to check if binary// tree is height balancedfunction isBalanced(root){ // Base condition when tree is // empty return true if(root == null) return true // lh and rh to store height of // left and right subtree let lh = new Height() let rh = new Height() // Calculating height of left and right tree lh.height = height(root.left) rh.height = height(root.right) // l and r are used to check if left // and right subtree are balanced let l = isBalanced(root.left) let r = isBalanced(root.right) // height of tree is maximum of // left subtree height and // right subtree height plus 1 if(Math.abs(lh.height - rh.height) <= 1) return l && r // if we reach here then the tree // is not balanced return false } // Driver function to test the above function // Constructed binary tree is// 1// / \\// 2 3// / \\ /// 4 5 6 / 7//// to store the height of tree during traversal let root = new Node(1)root.left = new Node(2)root.right = new Node(3)root.left.left = new Node(4)root.left.right = new Node(5)root.right.left = new Node(6)root.left.left.left = new Node(7) if(isBalanced(root)) document.write('Tree is balanced',\"</br>\")else document.write('Tree is not balanced',\"</br>\") // This code is contributed by shinjanpatra</script>",
"e": 26435,
"s": 24481,
"text": null
},
{
"code": null,
"e": 26443,
"s": 26435,
"text": "Output:"
},
{
"code": null,
"e": 26460,
"s": 26443,
"text": "Tree is balanced"
},
{
"code": null,
"e": 26504,
"s": 26460,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 26548,
"s": 26504,
"text": "https://www.youtube.com/watch?v=qIdVVH1tKM4"
},
{
"code": null,
"e": 26673,
"s": 26548,
"text": "Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem."
},
{
"code": null,
"e": 26682,
"s": 26673,
"text": "shweta44"
},
{
"code": null,
"e": 26694,
"s": 26682,
"text": "shrikanth13"
},
{
"code": null,
"e": 26708,
"s": 26694,
"text": "rathbhupendra"
},
{
"code": null,
"e": 26721,
"s": 26708,
"text": "nobody_cares"
},
{
"code": null,
"e": 26735,
"s": 26721,
"text": "HarshUpadhyay"
},
{
"code": null,
"e": 26753,
"s": 26735,
"text": "saurabhlohiya1234"
},
{
"code": null,
"e": 26766,
"s": 26753,
"text": "AakashYadav4"
},
{
"code": null,
"e": 26781,
"s": 26766,
"text": "Shubhank Gupta"
},
{
"code": null,
"e": 26794,
"s": 26781,
"text": "prasanna1995"
},
{
"code": null,
"e": 26809,
"s": 26794,
"text": "adnanirshad158"
},
{
"code": null,
"e": 26822,
"s": 26809,
"text": "shinjanpatra"
},
{
"code": null,
"e": 26835,
"s": 26822,
"text": "technophpfij"
},
{
"code": null,
"e": 26852,
"s": 26835,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 26859,
"s": 26852,
"text": "Amazon"
},
{
"code": null,
"e": 26868,
"s": 26859,
"text": "Belzabar"
},
{
"code": null,
"e": 26882,
"s": 26868,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 26889,
"s": 26882,
"text": "InMobi"
},
{
"code": null,
"e": 26895,
"s": 26889,
"text": "Intel"
},
{
"code": null,
"e": 26905,
"s": 26895,
"text": "Microsoft"
},
{
"code": null,
"e": 26911,
"s": 26905,
"text": "Paytm"
},
{
"code": null,
"e": 26930,
"s": 26911,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 26939,
"s": 26930,
"text": "Synopsys"
},
{
"code": null,
"e": 26947,
"s": 26939,
"text": "Walmart"
},
{
"code": null,
"e": 26956,
"s": 26947,
"text": "Zillious"
},
{
"code": null,
"e": 26961,
"s": 26956,
"text": "Tree"
},
{
"code": null,
"e": 26967,
"s": 26961,
"text": "Paytm"
},
{
"code": null,
"e": 26974,
"s": 26967,
"text": "Amazon"
},
{
"code": null,
"e": 26984,
"s": 26974,
"text": "Microsoft"
},
{
"code": null,
"e": 26992,
"s": 26984,
"text": "Walmart"
},
{
"code": null,
"e": 27006,
"s": 26992,
"text": "Goldman Sachs"
},
{
"code": null,
"e": 27015,
"s": 27006,
"text": "Synopsys"
},
{
"code": null,
"e": 27021,
"s": 27015,
"text": "Intel"
},
{
"code": null,
"e": 27030,
"s": 27021,
"text": "Zillious"
},
{
"code": null,
"e": 27037,
"s": 27030,
"text": "InMobi"
},
{
"code": null,
"e": 27046,
"s": 27037,
"text": "Belzabar"
},
{
"code": null,
"e": 27051,
"s": 27046,
"text": "Tree"
},
{
"code": null,
"e": 27149,
"s": 27051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27199,
"s": 27149,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 27234,
"s": 27199,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 27268,
"s": 27234,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 27300,
"s": 27268,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 27336,
"s": 27300,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 27377,
"s": 27336,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 27439,
"s": 27377,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 27503,
"s": 27439,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 27546,
"s": 27503,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
How to find Windows Product Key Using PowerShell?
|
Windows Product key can be retrieved using PowerShell or CMD. To retrieve the product key using PowerShell, we need to query SoftwareLicesingService class and there is a property called OA3xOriginalProductKey which stores the product key.
Get-WmiObject -query `select * from SoftwareLicensingService' | Select OA3xOriginalProductKey
OA3xOriginalProductKey
----------------------
BBBBB-CSDSC-EESSR-KKIDS-AAAAA
We can also query this WMI class using cmd as shown below.
wmic path softwarelicensingservice get OA3xOriginalProductKey
Caution: It may or may not work for all the Windows OS. The above is tested in Windows 10.
|
[
{
"code": null,
"e": 1426,
"s": 1187,
"text": "Windows Product key can be retrieved using PowerShell or CMD. To retrieve the product key using PowerShell, we need to query SoftwareLicesingService class and there is a property called OA3xOriginalProductKey which stores the product key."
},
{
"code": null,
"e": 1520,
"s": 1426,
"text": "Get-WmiObject -query `select * from SoftwareLicensingService' | Select OA3xOriginalProductKey"
},
{
"code": null,
"e": 1596,
"s": 1520,
"text": "OA3xOriginalProductKey\n----------------------\nBBBBB-CSDSC-EESSR-KKIDS-AAAAA"
},
{
"code": null,
"e": 1655,
"s": 1596,
"text": "We can also query this WMI class using cmd as shown below."
},
{
"code": null,
"e": 1717,
"s": 1655,
"text": "wmic path softwarelicensingservice get OA3xOriginalProductKey"
},
{
"code": null,
"e": 1808,
"s": 1717,
"text": "Caution: It may or may not work for all the Windows OS. The above is tested in Windows 10."
}
] |
Create a small-caps effect for CSS
|
To create a small-caps effect, use the font-variant property.
You can try to run the following code to learn how to work with font-variant property in CSS:
<html>
<head>
</head>
<body>
<p style = "font-variant:small-caps;">
Asia, Antartica, Africa are continents
</p>
</body>
</html>
|
[
{
"code": null,
"e": 1249,
"s": 1187,
"text": "To create a small-caps effect, use the font-variant property."
},
{
"code": null,
"e": 1343,
"s": 1249,
"text": "You can try to run the following code to learn how to work with font-variant property in CSS:"
},
{
"code": null,
"e": 1504,
"s": 1343,
"text": "<html>\n <head>\n </head>\n <body>\n <p style = \"font-variant:small-caps;\">\n Asia, Antartica, Africa are continents\n </p>\n </body>\n</html>"
}
] |
DC.js - Dashboard Working Example
|
In this chapter, we will develop a dashboard in DC by clicking and selecting a chart.
Now, we have the background and can start to write some code. It contains the following steps −
Let us add styles in the CSS using the coding given below.
<style>
.dc-chart { font-size: 12px; }
.dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; }
.dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; }
</style>
Here, we have assigned styles for the chart, grid-top and the grid-item.
Let us create a variable in DC as shown below.
var barChart = dc.barChart('#line');
var pieChart = dc.pieChart('#pie');
var countChart = dc.dataCount("#mystats");
var gridChart = dc.dataGrid("#mygrid");
Here, we have assigned a barChart variable id in line, countChart id is mystats, pieChart is pie and gridChart id is mygrid.
Read the data from the people.csv file as shown below.
d3.csv("data/people.csv", function(errors, people) {
var mycrossfilter = crossfilter(people);
}
If the data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we have used the same people.csv file, which we have used in our previous charting examples. It looks as shown below.
id,name,gender,DOB,MaritalStatus,CreditCardType
1,Damaris,Female,1973-02-18,false,visa-electron
2,Barbe,Female,1969-04-10,true,americanexpress
3,Belia,Female,1960-04-16,false,maestro
4,Leoline,Female,1995-01-19,true,bankcard
5,Valentine,Female,1992-04-16,false,
6,Rosanne,Female,1985-01-05,true,bankcard
7,Shalna,Female,1956-11-01,false,jcb
8,Mordy,Male,1990-03-27,true,china-unionpay
.........................................
.........................................
You can set the dimension using the coding below.
var ageDimension = mycrossfilter.dimension(function(data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000))
});
After the dimension has been assigned, group the age using the coding given below.
var ageGroup = ageDimension.group().reduceCount();
You can set the dimension using the coding below.
// gender dimension
var genderDimension = mycrossfilter.dimension(function(data) { return data.gender; });
var genderGroup = genderDimension.group().reduceCount();
Now, generate a bar chart using the coding below.
barChart
.width(400)
.height(200)
.x(d3.scale.linear().domain([15,70]))
.yAxisLabel("Count")
.xAxisLabel("Age")
.elasticY(true)
.elasticX(true)
.dimension(ageDimension)
.group(ageGroup);
Here,
We have assigned the chart width as 400 and height as 200.
Next, we have specified the domain range as [15, 70].
We have set the x-axis label as age and the y-axis label as count.
We have specified the elasticY and X function as true.
Now, generate a pie chart using the coding below.
pieChart
.width(200)
.height(100)
.dimension(genderDimension)
.group(genderGroup);
Here,
We have assigned the chart width as 200 and height as 100.
Now, group the dimension by gender.
Now, create the grid and count the chart using the coding given below.
countChart
.dimension(mycrossfilter)
.group(mycrossfilter.groupAll());
gridChart
.dimension(ageDimension)
.group(function (data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000));
})
Now, render the grid and count using the coding below.
.size(100)
.htmlGroup (function(d) {
return 'Age: ' + d.key +
'; Count: ' + d.values.length +
' people'
})
.html (function(d) { return d.name; })
.sortBy(function (d) {
return d.name;
})
.order(d3.ascending);
barChart.render();
pieChart.render();
countChart.render();
gridChart.render();
Here, we have sorted the name by using the html() function and have finally rendered the chart.
The complete code is as follows. Create a webpage dashboard.html and add the following changes to it.
<html>
<head>
<title>DC dashboard sample</title>
<link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css">
<link rel = "stylesheet" type = "text/css" href = "css/dc.css"/>
<style>
.dc-chart { font-size: 12px; }
.dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; }
.dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; }
</style>
<script src = "js/d3.js"></script>
<script src = "js/crossfilter.js"></script>
<script src = "js/dc.js"></script>
</head>
<body>
<div>
<div style = "width: 600px;">
<div id = "mystats" class = "dc-data-count" style = "float: right">
<span class = "filter-count"></span> selected out of <span
class = "total-count"></span> | <a href = "javascript:dc.filterAll();
dc.renderAll();">Reset All</a>
</div>
</div>
<div style = "clear: both; padding-top: 20px;">
<div>
<div id = "line"></div>
<div id = "pie"></div>
</div>
</div>
<div style = "clear: both">
<div class = "dc-data-grid" id = "mygrid"></div>
</div>
</div>
<script language = "javascript">
var barChart = dc.barChart('#line'); // , 'myChartGroup');
var pieChart = dc.pieChart('#pie'); //, 'myChartGroup');
var countChart = dc.dataCount("#mystats");
var gridChart = dc.dataGrid("#mygrid");
d3.csv("data/people.csv", function(errors, people) {
var mycrossfilter = crossfilter(people);
// age dimension
var ageDimension = mycrossfilter.dimension(function(data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000))
});
var ageGroup = ageDimension.group().reduceCount();
// gender dimension
var genderDimension = mycrossfilter.dimension(function(data) {
return data.gender;
});
var genderGroup = genderDimension.group().reduceCount();
barChart
.width(400)
.height(200)
.x(d3.scale.linear().domain([15,70]))
.yAxisLabel("Count")
.xAxisLabel("Age")
.elasticY(true)
.elasticX(true)
.dimension(ageDimension)
.group(ageGroup);
pieChart
.width(200)
.height(100)
.dimension(genderDimension)
.group(genderGroup);
countChart
.dimension(mycrossfilter)
.group(mycrossfilter.groupAll());
gridChart
.dimension(ageDimension)
.group(function (data) {
return ~~((Date.now() - new Date(data.DOB)) / (31557600000));
})
.size(100)
.htmlGroup (function(d) {
return 'Age: ' + d.key +
'; Count: ' + d.values.length +
' people'
})
.html (function(d) { return d.name; })
.sortBy(function (d) {
return d.name;
})
.order(d3.ascending);
barChart.render();
pieChart.render();
countChart.render();
gridChart.render();
});
</script>
</body>
</html>
Now, request the browser and we will see the following response.
You can check yourself by clicking bar, pie charts and see how the data changes.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2145,
"s": 2059,
"text": "In this chapter, we will develop a dashboard in DC by clicking and selecting a chart."
},
{
"code": null,
"e": 2241,
"s": 2145,
"text": "Now, we have the background and can start to write some code. It contains the following steps −"
},
{
"code": null,
"e": 2300,
"s": 2241,
"text": "Let us add styles in the CSS using the coding given below."
},
{
"code": null,
"e": 2506,
"s": 2300,
"text": "<style>\n .dc-chart { font-size: 12px; }\n .dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; }\n .dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; }\n</style>"
},
{
"code": null,
"e": 2579,
"s": 2506,
"text": "Here, we have assigned styles for the chart, grid-top and the grid-item."
},
{
"code": null,
"e": 2626,
"s": 2579,
"text": "Let us create a variable in DC as shown below."
},
{
"code": null,
"e": 2783,
"s": 2626,
"text": "var barChart = dc.barChart('#line');\nvar pieChart = dc.pieChart('#pie'); \nvar countChart = dc.dataCount(\"#mystats\");\nvar gridChart = dc.dataGrid(\"#mygrid\");"
},
{
"code": null,
"e": 2908,
"s": 2783,
"text": "Here, we have assigned a barChart variable id in line, countChart id is mystats, pieChart is pie and gridChart id is mygrid."
},
{
"code": null,
"e": 2963,
"s": 2908,
"text": "Read the data from the people.csv file as shown below."
},
{
"code": null,
"e": 3062,
"s": 2963,
"text": "d3.csv(\"data/people.csv\", function(errors, people) {\n var mycrossfilter = crossfilter(people);\n}"
},
{
"code": null,
"e": 3279,
"s": 3062,
"text": "If the data is not present, then it returns an error. Now, assign the data to a crossfilter. Here, we have used the same people.csv file, which we have used in our previous charting examples. It looks as shown below."
},
{
"code": null,
"e": 3750,
"s": 3279,
"text": "id,name,gender,DOB,MaritalStatus,CreditCardType\n1,Damaris,Female,1973-02-18,false,visa-electron\n2,Barbe,Female,1969-04-10,true,americanexpress\n3,Belia,Female,1960-04-16,false,maestro\n4,Leoline,Female,1995-01-19,true,bankcard\n5,Valentine,Female,1992-04-16,false,\n6,Rosanne,Female,1985-01-05,true,bankcard\n7,Shalna,Female,1956-11-01,false,jcb\n8,Mordy,Male,1990-03-27,true,china-unionpay\n\n.........................................\n.........................................\n"
},
{
"code": null,
"e": 3800,
"s": 3750,
"text": "You can set the dimension using the coding below."
},
{
"code": null,
"e": 3930,
"s": 3800,
"text": "var ageDimension = mycrossfilter.dimension(function(data) { \n return ~~((Date.now() - new Date(data.DOB)) / (31557600000)) \n});"
},
{
"code": null,
"e": 4013,
"s": 3930,
"text": "After the dimension has been assigned, group the age using the coding given below."
},
{
"code": null,
"e": 4064,
"s": 4013,
"text": "var ageGroup = ageDimension.group().reduceCount();"
},
{
"code": null,
"e": 4114,
"s": 4064,
"text": "You can set the dimension using the coding below."
},
{
"code": null,
"e": 4278,
"s": 4114,
"text": "// gender dimension\nvar genderDimension = mycrossfilter.dimension(function(data) { return data.gender; });\nvar genderGroup = genderDimension.group().reduceCount();"
},
{
"code": null,
"e": 4328,
"s": 4278,
"text": "Now, generate a bar chart using the coding below."
},
{
"code": null,
"e": 4542,
"s": 4328,
"text": "barChart\n .width(400)\n .height(200)\n .x(d3.scale.linear().domain([15,70]))\n .yAxisLabel(\"Count\")\n .xAxisLabel(\"Age\")\n .elasticY(true)\n .elasticX(true)\n .dimension(ageDimension)\n .group(ageGroup);"
},
{
"code": null,
"e": 4548,
"s": 4542,
"text": "Here,"
},
{
"code": null,
"e": 4607,
"s": 4548,
"text": "We have assigned the chart width as 400 and height as 200."
},
{
"code": null,
"e": 4661,
"s": 4607,
"text": "Next, we have specified the domain range as [15, 70]."
},
{
"code": null,
"e": 4728,
"s": 4661,
"text": "We have set the x-axis label as age and the y-axis label as count."
},
{
"code": null,
"e": 4783,
"s": 4728,
"text": "We have specified the elasticY and X function as true."
},
{
"code": null,
"e": 4833,
"s": 4783,
"text": "Now, generate a pie chart using the coding below."
},
{
"code": null,
"e": 4928,
"s": 4833,
"text": "pieChart\n .width(200)\n .height(100)\n .dimension(genderDimension)\n .group(genderGroup);"
},
{
"code": null,
"e": 4934,
"s": 4928,
"text": "Here,"
},
{
"code": null,
"e": 4993,
"s": 4934,
"text": "We have assigned the chart width as 200 and height as 100."
},
{
"code": null,
"e": 5029,
"s": 4993,
"text": "Now, group the dimension by gender."
},
{
"code": null,
"e": 5100,
"s": 5029,
"text": "Now, create the grid and count the chart using the coding given below."
},
{
"code": null,
"e": 5318,
"s": 5100,
"text": "countChart\n .dimension(mycrossfilter)\n .group(mycrossfilter.groupAll());\n\ngridChart\n .dimension(ageDimension)\n .group(function (data) {\n return ~~((Date.now() - new Date(data.DOB)) / (31557600000));\n })"
},
{
"code": null,
"e": 5373,
"s": 5318,
"text": "Now, render the grid and count using the coding below."
},
{
"code": null,
"e": 5705,
"s": 5373,
"text": ".size(100)\n .htmlGroup (function(d) { \n return 'Age: ' + d.key +\n '; Count: ' + d.values.length +\n ' people'\n })\n .html (function(d) { return d.name; })\n .sortBy(function (d) {\n return d.name;\n })\n .order(d3.ascending);\n\nbarChart.render();\npieChart.render();\ncountChart.render();\ngridChart.render();"
},
{
"code": null,
"e": 5801,
"s": 5705,
"text": "Here, we have sorted the name by using the html() function and have finally rendered the chart."
},
{
"code": null,
"e": 5903,
"s": 5801,
"text": "The complete code is as follows. Create a webpage dashboard.html and add the following changes to it."
},
{
"code": null,
"e": 9335,
"s": 5903,
"text": "<html>\n <head>\n <title>DC dashboard sample</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"css/bootstrap.css\">\n <link rel = \"stylesheet\" type = \"text/css\" href = \"css/dc.css\"/>\n \n <style>\n .dc-chart { font-size: 12px; }\n .dc-grid-top { padding-left: 10px; font-size: 14px; font-weight: bold; }\n .dc-grid-item { padding-left: 10px; font-size: 12px; font-weight: normal; }\n </style>\n\n <script src = \"js/d3.js\"></script>\n <script src = \"js/crossfilter.js\"></script>\n <script src = \"js/dc.js\"></script>\n </head>\n \n <body>\n <div>\n <div style = \"width: 600px;\">\n <div id = \"mystats\" class = \"dc-data-count\" style = \"float: right\">\n <span class = \"filter-count\"></span> selected out of <span\n class = \"total-count\"></span> | <a href = \"javascript:dc.filterAll();\n dc.renderAll();\">Reset All</a>\n </div>\n </div>\n\n <div style = \"clear: both; padding-top: 20px;\">\n <div>\n <div id = \"line\"></div>\n <div id = \"pie\"></div>\n </div>\n </div>\n\n <div style = \"clear: both\">\n <div class = \"dc-data-grid\" id = \"mygrid\"></div>\n </div>\n </div>\n\n <script language = \"javascript\">\n var barChart = dc.barChart('#line'); // , 'myChartGroup');\n var pieChart = dc.pieChart('#pie'); //, 'myChartGroup');\n var countChart = dc.dataCount(\"#mystats\");\n var gridChart = dc.dataGrid(\"#mygrid\");\n\n d3.csv(\"data/people.csv\", function(errors, people) {\n var mycrossfilter = crossfilter(people);\n\n // age dimension\n var ageDimension = mycrossfilter.dimension(function(data) { \n return ~~((Date.now() - new Date(data.DOB)) / (31557600000)) \n });\n var ageGroup = ageDimension.group().reduceCount();\n\n // gender dimension\n var genderDimension = mycrossfilter.dimension(function(data) { \n return data.gender; \n });\n var genderGroup = genderDimension.group().reduceCount();\n\n barChart\n .width(400)\n .height(200)\n .x(d3.scale.linear().domain([15,70]))\n .yAxisLabel(\"Count\")\n .xAxisLabel(\"Age\")\n .elasticY(true)\n .elasticX(true)\n .dimension(ageDimension)\n .group(ageGroup);\n\n pieChart\n .width(200)\n .height(100)\n .dimension(genderDimension)\n .group(genderGroup);\n\n countChart\n .dimension(mycrossfilter)\n .group(mycrossfilter.groupAll());\n\n gridChart\n .dimension(ageDimension)\n .group(function (data) {\n return ~~((Date.now() - new Date(data.DOB)) / (31557600000));\n })\n .size(100)\n .htmlGroup (function(d) { \n return 'Age: ' + d.key +\n '; Count: ' + d.values.length +\n ' people'\n })\n .html (function(d) { return d.name; })\n .sortBy(function (d) {\n return d.name;\n })\n .order(d3.ascending);\n\n barChart.render();\n pieChart.render();\n countChart.render();\n gridChart.render();\n });\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9400,
"s": 9335,
"text": "Now, request the browser and we will see the following response."
},
{
"code": null,
"e": 9481,
"s": 9400,
"text": "You can check yourself by clicking bar, pie charts and see how the data changes."
},
{
"code": null,
"e": 9488,
"s": 9481,
"text": " Print"
},
{
"code": null,
"e": 9499,
"s": 9488,
"text": " Add Notes"
}
] |
Drools - Debugging
|
There are different ways to debug a Drools project. Here, we will write a Utility class to let you know which rules are being triggered or fired.
With this approach, you can check what all rules are getting triggered in your Drools project. Here is our Utility Class
package com.sample;
import org.drools.spi.KnowledgeHelper;
public class Utility {
public static void help(final KnowledgeHelper drools, final String message){
System.out.println(message);
System.out.println("\nrule triggered: " + drools.getRule().getName());
}
public static void helper(final KnowledgeHelper drools){
System.out.println("\nrule triggered: " + drools.getRule().getName());
}
}
The first method help prints the rule triggered along with some extra information which you can pass as String via the DRL file.
The second rule helper prints whether the particular rule was triggered or not.
We have added one of the Utility methods in each DRL file. We have also added the import function in the DRL file (Pune.drl). In the then part of the rule, we have added the utility function call. The modified Pune.drl is given below. Changes are highlighted in blue.
//created on: Dec 24, 2014
package droolsexample
//list any import classes here.
import com.sample.ItemCity;
import java.math.BigDecimal;
import com.sample.HelloCity;
import function com.sample.Utility.helper;
// declare any global variables here
dialect "java"
rule "Pune Medicine Item"
when
item : ItemCity(purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.MEDICINES)
then
BigDecimal tax = new BigDecimal(0.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
HelloCity.writeHello(item.getPurchaseCity().toString());
helper(drools);
end
rule "Pune Groceries Item"
when
item : ItemCity(purchaseCity == ItemCity.City.PUNE,
typeofItem == ItemCity.Type.GROCERIES)
then
BigDecimal tax = new BigDecimal(2.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
helper(drools);
end
Similarly, we have added the other utility function in the second DRL file (Nagpur.drl). Here is the modified code −
// created on: Dec 26, 2014
package droolsexample
// list any import classes here.
import com.sample.ItemCity;
import java.math.BigDecimal;
import function com.sample.Utility.help;
//declare any global variables here
dialect "java"
rule "Nagpur Medicine Item"
when
item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,
typeofItem == ItemCity.Type.MEDICINES)
then
BigDecimal tax = new BigDecimal(0.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
help(drools,"added info");
end
rule "Nagpur Groceries Item"
when
item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,
typeofItem == ItemCity.Type.GROCERIES)
then
BigDecimal tax = new BigDecimal(1.0);
item.setLocalTax(tax.multiply(item.getSellPrice()));
help(drools,"info");
end
Run the program again and it should produce the following output −
info
rule triggered: Nagpur Groceries Item
added info
rule triggered: Nagpur Medicine Item
rule triggered: Pune Groceries Item
HELLO PUNE!!!!!!
rule triggered: Pune Medicine Item
PUNE 0
PUNE 20
NAGPUR 0
NAGPUR 10
Both the utility functions are called and it shows whether the particular rule was called or not. In the above example, all the rules are being called, but in an enterprise application, this utility function can be really useful to debug and find out whether a particular rule was fired or not.
You can debug the rules during the execution of your Drools application. You can add breakpoints in the consequences of your rules, and whenever such a breakpoint is encountered during the execution of the rules, execution is stopped temporarily. You can then inspect the variables known at that point as you do in a Java Application, and use the normal debugging options available in Eclipse.
To create a breakpoint in your DRL file, just double-click at the line where you want to create a breakpoint. Remember, you can only create a breakpoint in the then part of a rule. A breakpoint can be removed by double-clicking on the breakpoint in the DRL editor.
After applying the breakpoints, you need to debug your application as a Drools application. Drools breakpoints (breakpoints in DRL file) will only work if your application is being debugged as a Drools application. Here is how you need to do the same −
Once you debug your application as a Drools application, you would see the control on the DRL file as shown in the following screenshot −
You can see the variables and the current values of the object at that debug point. The same control of F6 to move to the next line and F8 to jump to the next debug point are applicable here as well. In this way, you can debug your Drools application.
Note − The debug perspective in Drools application works only if the dialect is MVEL until Drools 5.x.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1943,
"s": 1797,
"text": "There are different ways to debug a Drools project. Here, we will write a Utility class to let you know which rules are being triggered or fired."
},
{
"code": null,
"e": 2064,
"s": 1943,
"text": "With this approach, you can check what all rules are getting triggered in your Drools project. Here is our Utility Class"
},
{
"code": null,
"e": 2488,
"s": 2064,
"text": "package com.sample;\nimport org.drools.spi.KnowledgeHelper;\n\npublic class Utility {\n public static void help(final KnowledgeHelper drools, final String message){\n System.out.println(message);\n System.out.println(\"\\nrule triggered: \" + drools.getRule().getName());\n }\n public static void helper(final KnowledgeHelper drools){\n System.out.println(\"\\nrule triggered: \" + drools.getRule().getName());\n }\n}"
},
{
"code": null,
"e": 2617,
"s": 2488,
"text": "The first method help prints the rule triggered along with some extra information which you can pass as String via the DRL file."
},
{
"code": null,
"e": 2697,
"s": 2617,
"text": "The second rule helper prints whether the particular rule was triggered or not."
},
{
"code": null,
"e": 2965,
"s": 2697,
"text": "We have added one of the Utility methods in each DRL file. We have also added the import function in the DRL file (Pune.drl). In the then part of the rule, we have added the utility function call. The modified Pune.drl is given below. Changes are highlighted in blue."
},
{
"code": null,
"e": 3857,
"s": 2965,
"text": "//created on: Dec 24, 2014\npackage droolsexample\n\n//list any import classes here.\nimport com.sample.ItemCity;\nimport java.math.BigDecimal;\nimport com.sample.HelloCity; \nimport function com.sample.Utility.helper;\n\n// declare any global variables here\ndialect \"java\"\nrule \"Pune Medicine Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.PUNE, \n typeofItem == ItemCity.Type.MEDICINES)\n \n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\n HelloCity.writeHello(item.getPurchaseCity().toString()); \n helper(drools);\nend\n\nrule \"Pune Groceries Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.PUNE, \n typeofItem == ItemCity.Type.GROCERIES)\n then\n BigDecimal tax = new BigDecimal(2.0);\n item.setLocalTax(tax.multiply(item.getSellPrice())); \n helper(drools);\nend"
},
{
"code": null,
"e": 3974,
"s": 3857,
"text": "Similarly, we have added the other utility function in the second DRL file (Nagpur.drl). Here is the modified code −"
},
{
"code": null,
"e": 4798,
"s": 3974,
"text": "// created on: Dec 26, 2014\npackage droolsexample\n\n// list any import classes here.\nimport com.sample.ItemCity;\nimport java.math.BigDecimal; \nimport function com.sample.Utility.help;\n\n//declare any global variables here\ndialect \"java\"\n\nrule \"Nagpur Medicine Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR, \n typeofItem == ItemCity.Type.MEDICINES)\n \n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice())); \n help(drools,\"added info\");\nend\n\nrule \"Nagpur Groceries Item\"\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR, \n typeofItem == ItemCity.Type.GROCERIES)\n then\n BigDecimal tax = new BigDecimal(1.0);\n item.setLocalTax(tax.multiply(item.getSellPrice())); \n help(drools,\"info\");\nend"
},
{
"code": null,
"e": 4865,
"s": 4798,
"text": "Run the program again and it should produce the following output −"
},
{
"code": null,
"e": 5083,
"s": 4865,
"text": "info\n\nrule triggered: Nagpur Groceries Item\nadded info\n\nrule triggered: Nagpur Medicine Item\n\nrule triggered: Pune Groceries Item\nHELLO PUNE!!!!!!\n\nrule triggered: Pune Medicine Item\nPUNE 0\nPUNE 20\nNAGPUR 0\nNAGPUR 10\n"
},
{
"code": null,
"e": 5378,
"s": 5083,
"text": "Both the utility functions are called and it shows whether the particular rule was called or not. In the above example, all the rules are being called, but in an enterprise application, this utility function can be really useful to debug and find out whether a particular rule was fired or not."
},
{
"code": null,
"e": 5772,
"s": 5378,
"text": "You can debug the rules during the execution of your Drools application. You can add breakpoints in the consequences of your rules, and whenever such a breakpoint is encountered during the execution of the rules, execution is stopped temporarily. You can then inspect the variables known at that point as you do in a Java Application, and use the normal debugging options available in Eclipse."
},
{
"code": null,
"e": 6037,
"s": 5772,
"text": "To create a breakpoint in your DRL file, just double-click at the line where you want to create a breakpoint. Remember, you can only create a breakpoint in the then part of a rule. A breakpoint can be removed by double-clicking on the breakpoint in the DRL editor."
},
{
"code": null,
"e": 6290,
"s": 6037,
"text": "After applying the breakpoints, you need to debug your application as a Drools application. Drools breakpoints (breakpoints in DRL file) will only work if your application is being debugged as a Drools application. Here is how you need to do the same −"
},
{
"code": null,
"e": 6428,
"s": 6290,
"text": "Once you debug your application as a Drools application, you would see the control on the DRL file as shown in the following screenshot −"
},
{
"code": null,
"e": 6680,
"s": 6428,
"text": "You can see the variables and the current values of the object at that debug point. The same control of F6 to move to the next line and F8 to jump to the next debug point are applicable here as well. In this way, you can debug your Drools application."
},
{
"code": null,
"e": 6783,
"s": 6680,
"text": "Note − The debug perspective in Drools application works only if the dialect is MVEL until Drools 5.x."
},
{
"code": null,
"e": 6790,
"s": 6783,
"text": " Print"
},
{
"code": null,
"e": 6801,
"s": 6790,
"text": " Add Notes"
}
] |
What is a variable, field, property in Java?
|
In programming to hold data members we use variables, Java you can declare three types of variables namely,
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.
In addition to these, they are referred with different names based on the usage.
Fields − Variables of a class i.e. instance variables and static variables are called fields. They can’t be abstract except this you can use any other modifier with fields.
public class Sample{
int data = 90;
static data = 145;
}
In general, fields with private modifier, setter and getter methods are considered as properties.
public class Sample{
private int name;
public String getName(){
return this.number;
}
public void setName(String name){
this.name = name;
}
}
public class Student{
private String name;
private int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public static void main(String[] args){
Student std = new Student("Krishna", 29);
System.out.println(std.getName());
System.out.println(std.getAge());
}
}
Krishna
29
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "In programming to hold data members we use variables, Java you can declare three types of variables namely,"
},
{
"code": null,
"e": 1403,
"s": 1170,
"text": "Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed."
},
{
"code": null,
"e": 1667,
"s": 1403,
"text": "Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class."
},
{
"code": null,
"e": 1794,
"s": 1667,
"text": "Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword."
},
{
"code": null,
"e": 1875,
"s": 1794,
"text": "In addition to these, they are referred with different names based on the usage."
},
{
"code": null,
"e": 2048,
"s": 1875,
"text": "Fields − Variables of a class i.e. instance variables and static variables are called fields. They can’t be abstract except this you can use any other modifier with fields."
},
{
"code": null,
"e": 2111,
"s": 2048,
"text": "public class Sample{\n int data = 90;\n static data = 145;\n}"
},
{
"code": null,
"e": 2209,
"s": 2111,
"text": "In general, fields with private modifier, setter and getter methods are considered as properties."
},
{
"code": null,
"e": 2378,
"s": 2209,
"text": "public class Sample{\n private int name;\n public String getName(){\n return this.number;\n }\n public void setName(String name){\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 2953,
"s": 2378,
"text": "public class Student{\n private String name;\n private int age;\n public Student(String name, int age){\n this.name = name;\n this.age = age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getName() {\n return this.name;\n }\n public int getAge() {\n return this.age;\n }\n public static void main(String[] args){\n Student std = new Student(\"Krishna\", 29);\n System.out.println(std.getName());\n System.out.println(std.getAge());\n }\n}"
},
{
"code": null,
"e": 2964,
"s": 2953,
"text": "Krishna\n29"
}
] |
How to dynamically load a Python class?
|
There's no available function that takes a fully qualified class name and returns the class. However we can define a function that has this functionality.
The following code is of such a function.
def get_class( s ):
parts = s.split('.')
module = ".".join(parts[:-1])
n = __import__( module )
for comp in parts[1:]:
n = getattr(m, comp)
return n
One usage example of that function
import datetime
def get_class( cls ):
parts = cls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
print get_class('datetime.datetime').now()
This gives the output
2018-01-23 14:04:09.843000
|
[
{
"code": null,
"e": 1217,
"s": 1062,
"text": "There's no available function that takes a fully qualified class name and returns the class. However we can define a function that has this functionality."
},
{
"code": null,
"e": 1259,
"s": 1217,
"text": "The following code is of such a function."
},
{
"code": null,
"e": 1446,
"s": 1259,
"text": "def get_class( s ):\n parts = s.split('.')\n module = \".\".join(parts[:-1])\n n = __import__( module )\n for comp in parts[1:]:\n n = getattr(m, comp) \n return n"
},
{
"code": null,
"e": 1481,
"s": 1446,
"text": "One usage example of that function"
},
{
"code": null,
"e": 1721,
"s": 1481,
"text": "import datetime\ndef get_class( cls ):\n parts = cls.split('.')\n module = \".\".join(parts[:-1])\n m = __import__( module )\n for comp in parts[1:]:\n m = getattr(m, comp)\n return m\nprint get_class('datetime.datetime').now()"
},
{
"code": null,
"e": 1743,
"s": 1721,
"text": "This gives the output"
},
{
"code": null,
"e": 1772,
"s": 1743,
"text": "2018-01-23 14:04:09.843000\n\n"
}
] |
Jenkins - Quick Guide
|
Jenkins is a software that allows continuous integration. Jenkins will be installed on a server where the central build will take place. The following flowchart demonstrates a very simple workflow of how Jenkins works.
Along with Jenkins, sometimes, one might also see the association of Hudson. Hudson is a very popular open-source Java-based continuous integration tool developed by Sun Microsystems which was later acquired by Oracle. After the acquisition of Sun by Oracle, a fork was created from the Hudson source code, which brought about the introduction of Jenkins.
Continuous Integration is a development practice that requires developers to integrate code into a shared repository at regular intervals. This concept was meant to remove the problem of finding later occurrence of issues in the build lifecycle. Continuous integration requires the developers to have frequent builds. The common practice is that whenever a code commit occurs, a build should be triggered.
The official website for Jenkins is Jenkins. If you click the given link, you can get the home page of the Jenkins official website as shown below.
By default, the latest release and the Long-Term support release will be available for download. The past releases are also available for download. Click the Long-Term Support Release tab in the download section.
Click the link “Older but stable version” to download the Jenkins war file.
Open the command prompt. From the command prompt, browse to the directory where the jenkins.war file is present. Run the following command
D:\>Java –jar Jenkins.war
After the command is run, various tasks will run, one of which is the extraction of the war file which is done by an embedded webserver called winstone.
D:\>Java –jar Jenkins.war
Running from: D:\jenkins.war
Webroot: $user.home/ .jenkins
Sep 29, 2015 4:10:46 PM winstone.Logger logInternal
INFO: Beginning extraction from war file
Once the processing is complete without major errors, the following line will come in the output of the command prompt.
INFO: Jenkins is fully up and running
Once Jenkins is up and running, one can access Jenkins from the link − http://localhost:8080
This link will bring up the Jenkins dashboard.
The following prerequisites must be met for Jenkins Tomcat setup.
To verify Java installation, open the console and execute the following java command.
If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on.
Java version "1.7.0_60"
Java (TM) SE Run Time Environment (build 1.7.0_60-b19)
Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode)
java version "1.7.0_25"
Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)
Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)
We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial.
In case you do not have Java JDK, you can download it from the link Oracle
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,
Append the full path of the Java compiler location to the System Path.
Verify the command java-version from command prompt as explained above.
The official website for tomcat is Tomcat. If you click the given link, you can get the home page of the tomcat official website as shown below.
Browse to the link https://tomcat.apache.org/download-70.cgi to get the download for tomcat.
Go to the ‘Binary Distributions’ section. Download the 32-bit Windows zip file.
Then unzip the contents of the downloaded zip file.
Copy the Jenkis.war file which was downloaded from the previous section and copy it to the webapps folder in the tomcat folder.
Now open the command prompt. From the command prompt, browse to the directory where the tomcat7 folder is location. Browse to the bin directory in this folder and run the start.bat file
E:\Apps\tomcat7\bin>startup.bat
Once the processing is complete without major errors, the following line will come in the output of the command prompt.
INFO: Server startup in 1302 ms
Open the browser and go to the link − http://localhost:8080/jenkins. Jenkins will be up and running on tomcat.
For this exercise, you have to ensure that Internet connectivity is present from the machine on which Jenkins is installed. In your Jenkins Dashboard (Home screen), click the Manage Jenkins option on the left hand side.
In the next screen, click the ‘Manage Plugins’ option.
In the next screen, click the Available tab. This tab will give a list of plugins which are available for downloading. In the ‘Filter’ tab type ‘Git plugin’
The list will then be filtered. Check the Git Plugin option and click on the button ‘Install without restart’
The installation will then begin and the screen will be refreshed to show the status of the download.
Once all installations are complete, restart Jenkins by issue the following command in the browser. http://localhost:8080/jenkins/restart
After Jenkins is restarted, Git will be available as an option whilst configuring jobs. To verify, click on New Item in the menu options for Jenkins. Then enter a name for a job, in the following case, the name entered is ‘Demo’. Select ‘Freestyle project’ as the item type. Click the Ok button.
In the next screen, if you browse to the Source code Management section, you will now see ‘Git’ as an option.
The official website for maven is Apache Maven. If you click the given link, you can get the home page of the maven official website as shown below.
While browsing to the site, go to the Files section and download the link to the Binary.zip file.
Once the file is downloaded, extract the files to the relevant application folder. For this purpose, the maven files will be placed in E:\Apps\apache-maven-3.3.3.
In the Jenkins dashboard (Home screen), click Manage Jenkins from the left-hand side menu.
Then, click on ‘Configure System’ from the right hand side.
In the Configure system screen, scroll down till you see the Maven section and then click on the ‘Add Maven’ button.
Uncheck the ‘Install automatically’ option.
Add any name for the setting and the location of the MAVEN_HOME.
Then, click on the ‘Save’ button at the end of the screen.
You can now create a job with the ‘Maven project’ option. In the Jenkins dashboard, click the New Item option.
You probably would have seen a couple of times in the previous exercises wherein we had to configure options within Jenkins. The following shows the various configuration options in Jenkins.
So one can get the various configuration options for Jenkins by clicking the ‘Manage Jenkins’ option from the left hand menu side.
You will then be presented with the following screen −
Click on Configure system. Discussed below are some of the Jenkins configuration settings which can be carried out.
Jenkins needs some disk space to perform builds and keep archives. One can check this location from the configuration screen of Jenkins. By default, this is set to ~/.jenkins, and this location will initially be stored within your user profile location. In a proper environment, you need to change this location to an adequate location to store all relevant builds and archives. Once can do this in the following ways
Set "JENKINS_HOME" environment variable to the new home directory before launching the servlet container.
Set "JENKINS_HOME" environment variable to the new home directory before launching the servlet container.
Set "JENKINS_HOME" system property to the servlet container.
Set "JENKINS_HOME" system property to the servlet container.
Set JNDI environment entry "JENKINS_HOME" to the new directory.
Set JNDI environment entry "JENKINS_HOME" to the new directory.
The following example will use the first option of setting the "JENKINS_HOME" environment variable.
First create a new folder E:\Apps\Jenkins. Copy all the contents from the existing ~/.jenkins to this new directory.
Set the JENKINS_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,
In the Jenkins dashboard, click Manage Jenkins from the left hand side menu. Then click on ‘Configure System’ from the right hand side.
In the Home directory, you will now see the new directory which has been configured.
This refers to the total number of concurrent job executions that can take place on the Jenkins machine. This can be changed based on requirements. Sometimes the recommendation is to keep this number the same as the number of CPU on the machines for better performance.
This is used to add custom environment variables which will apply to all the jobs. These are key-value pairs and can be accessed and used in Builds wherever required.
By default, the Jenkins URL points to localhost. If you have a domain name setup for your machine, set this to the domain name else overwrite localhost with IP of machine. This will help in setting up slaves and while sending out links using the email as you can directly access the Jenkins URL using the environment variable JENKINS_URL which can be accessed as ${JENKINS_URL}.
In the email Notification area, you can configure the SMTP settings for sending out emails. This is required for Jenkins to connect to the SMTP mail server and send out emails to the recipient list.
To manage Jenkins, click on the ‘Manage Jenkins’ option from the left hand menu side.
So one can get the various configuration options for Jenkins by clicking the ‘Manage Jenkins’ option from the left hand menu side.
You will then be presented with the following screen −
Some of the management options are as follows −
This is where one can manage paths to the various tools to use in builds, such as the JDKs, the versions of Ant and Maven, as well as security options, email servers, and other system-wide configuration details. When plugins are installed. Jenkins will add the required configuration fields dynamically after the plugins are installed.
Jenkins stores all its system and build job configuration details as XML files which is stored in the Jenkins home directory. Here also all of the build history is stored. If you are migrating build jobs from one Jenkins instance to another, or archiving old build jobs, you will need to add or remove the corresponding build job directories to Jenkins’s builds directory. You don’t need to take Jenkins offline to do this—you can simply use the “Reload Configuration from Disk” option to reload the Jenkins system and build job configurations directly.
Here one can install a wide variety of third-party plugins right from different Source code management tools such as Git, Mercurial or ClearCase, to code quality and code coverage metrics reporting. Plugins can be installed, updated and removed through the Manage Plugins screen.
This screen displays a list of all the current Java system properties and system environment variables. Here one can check exactly what version of Java Jenkins is running in, what user it is running under, and so forth.
The following screenshot shows some of the name-value information available in this section.
The System Log screen is a convenient way to view the Jenkins log files in real time. Again, the main use of this screen is for troubleshooting.
This pages displays graphical data on how busy the Jenkins instance is in terms of the number of concurrent builds and the length of the build queue which gives an idea of how long your builds need to wait before being executed. These statistics can give a good idea of whether extra capacity or extra build nodes is required from an infrastructure perspective.
This screen lets you run Groovy scripts on the server. It is useful for advanced troubleshooting since it requires a strong knowledge of the internal Jenkins architecture.
Jenkins is capable of handling parallel and distributed builds. In this screen, you can configure how many builds you want. Jenkins runs simultaneously, and, if you are using distributed builds, set up build nodes. A build node is another machine that Jenkins can use to execute its builds.
If there is a need to shut down Jenkins, or the server Jenkins is running on, it is best not to do so when a build is being executed. To shut down Jenkins cleanly, you can use the Prepare for Shutdown link, which prevents any new builds from being started. Eventually, when all of the current builds have finished, one will be able to shut down Jenkins cleanly.
For this exercise, we will create a job in Jenkins which picks up a simple HelloWorld application, builds and runs the java program.
Step 1 − Go to the Jenkins dashboard and Click on New Item
Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’
Step 3 − The following screen will come up in which you can specify the details of the job.
Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git repository(E:\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of the local git repository.
Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository.
Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command
Step 6 − In the command window, enter the following commands and then click on the Save button.
Javac HelloWorld.java
Java HelloWorld
Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job.
Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress.
Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has been executed successfully. Click on the #1 in the Build history to bring up the details of the build.
Step 10 − Click on the Console Output link to see the details of the build
Apart from the steps shown above there are just so many ways to create a build job, the options available are many, which what makes Jenkins such a fantastic continuous deployment tool.
Jenkins provides an out of box functionality for Junit, and provides a host of plugins for unit testing for other technologies, an example being MSTest for .Net Unit tests. If you go to the link https://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin it will give the list of Unit Testing plugins available.
The following example will consider
A simple HelloWorldTest class based on Junit.
Ant as the build tool within Jenkins to build the class accordingly.
Step 1 − Go to the Jenkins dashboard and Click on the existing HelloWorld project and choose the Configure option
Step 2 − Browse to the section to Add a Build step and choose the option to Invoke Ant.
Step 3 − Click on the Advanced button.
Step 4 − In the build file section, enter the location of the build.xml file.
Step 5 − Next click the option to Add post-build option and choose the option of “Publish Junit test result report”
Step 6 − In the Test reports XML’s, enter the location as shown below. Ensure that Reports is a folder which is created in the HelloWorld project workspace. The “*.xml” basically tells Jenkins to pick up the result xml files which are produced by the running of the Junit test cases. These xml files which then be converted into reports which can be viewed later.
Once done, click the Save option at the end.
Step 7 − Once saved, you can click on the Build Now option.
Once the build is completed, a status of the build will show if the build was successful or not. In the Build output information, you will now notice an additional section called Test Result. In our case, we entered a negative Test case so that the result would fail just as an example.
One can go to the Console output to see further information. But what’s more interesting is that if you click on Test Result, you will now see a drill down of the Test results.
One of the basic principles of Continuous Integration is that a build should be verifiable. You have to be able to objectively determine whether a particular build is ready to proceed to the next stage of the build process, and the most convenient way to do this is to use automated tests. Without proper automated testing, you find yourself having to retain many build artifacts and test them by hand, which is hardly in the spirit of Continuous Integration. The following example shows how to use Selenium to run automated web tests.
Step 1 − Go to Manage Plugins.
Step 2 − Find the Hudson Selenium Plugin and choose to install. Restart the Jenkins instance.
Step 3 − Go to Configure system.
Step 4 − Configure the selenium server jar and click on the Save button.
Note − The selenium jar file can be downloaded from the location SeleniumHQ
Click on the download for the Selenium standalone server.
Step 5 − Go back to your dashboard and click on the Configure option for the HelloWorld project.
Step 6 − Click on Add build step and choose the optin of “SeleniumHQ htmlSuite Run”
Step 7 − Add the necessary details for the selenium test. Here the suiteFile is the TestSuite generated by using the Selenium IDE. Click on Save and execute a build. Now the post build will launch the selenium driver, and execute the html test.
Jenkins comes with an out of box facility to add an email notification for a build project.
Step 1 − Configuring an SMTP server. Goto Manage Jenkins → Configure System. Go to the E-mail notification section and enter the required SMTP server and user email-suffix details.
Step 2 − Configure the recipients in the Jenkins project - When you configure any Jenkins build project, right at the end is the ability to add recipients who would get email notifications for unstable or broken builds. Then click on the Save button.
Apart from the default, there are also notification plugin’s available in the market. An example is the notification plugin from Tikal Knowledge which allows sending Job Status notifications in JSON and XML formats. This plugin enables end-points to be configured as shown below.
Here are the details of each option −
"Format" − This is the notification payload format which can either be JSON or XML.
"Format" − This is the notification payload format which can either be JSON or XML.
"Protocol" − protocol to use for sending notification messages, HTTP, TCP or UDP.
"Protocol" − protocol to use for sending notification messages, HTTP, TCP or UDP.
"Event" − The job events that trigger notifications: Job Started, Job Completed, Job Finalized or All Events (the default option).
"Event" − The job events that trigger notifications: Job Started, Job Completed, Job Finalized or All Events (the default option).
"URL" − URL to send notifications to. It takes the form of "http://host" for HTTP protocol, and "host:port" for TCP and UDP protocols.
"URL" − URL to send notifications to. It takes the form of "http://host" for HTTP protocol, and "host:port" for TCP and UDP protocols.
"Timeout" − Timeout in milliseconds for sending notification request, 30 seconds by default.
"Timeout" − Timeout in milliseconds for sending notification request, 30 seconds by default.
As demonstrated in the earlier section, there are many reporting plugins available with the simplest one being the reports available for jUnit tests.
In the Post-build action for any job, you can define the reports to be created. After the builds are complete, the Test Results option will be available for further drill-down.
Jenkins has a host of Code Analysis plugin. The various plugins can be found at https://wiki.jenkins-ci.org/display/JENKINS/Static+Code+Analysis+Plugins
This plugin provides utilities for the static code analysis plugins. Jenkins can parse the results file from various Code Analysis tools such as CheckStyle, FindBugs, PMD etc. For each corresponding code analysis tool, a plugin in Jenkins needs to be installed.
Additionally the add-on plugin Static Analysis Collector is available that combines the individual results of these plugins into a single trend graph and view.
The plugins can provide information such as
The total number of warnings in a job
A showing of the new and fixed warnings of a build
Trend Reports showing the number of warnings per build
Overview of the found warnings per module, package, category, or type
Detailed reports of the found warnings optionally filtered by severity (or new and fixed)
Sometimes many build machines are required if there are instances wherein there are a larger and heavier projects which get built on a regular basis. And running all of these builds on a central machine may not be the best option. In such a scenario, one can configure other Jenkins machines to be slave machines to take the load off the master Jenkins server.
Sometimes you might also need several different environments to test your builds. In this case using a slave to represent each of your required environments is almost a must.
A slave is a computer that is set up to offload build projects from the master and once setup this distribution of tasks is fairly automatic. The exact delegation behavior depends on the configuration of each project; some projects may choose to "stick" to a particular machine for a build, while others may choose to roam freely between slaves.
Since each slave runs a separate program called a "slave agent" there is no need to install the full Jenkins (package or compiled binaries) on a slave. There are various ways to start slave agents, but in the end the slave agent and Jenkins master needs to establish a bi-directional communication link (for example a TCP/IP socket.) in order to operate.
To set up slaves/nodes in Jenkins follow the steps given below.
Step 1 − Go to the Manage Jenkins section and scroll down to the section of Manage Nodes.
Step 2 − Click on New Node
Step 3 − Give a name for the node, choose the Dumb slave option and click on Ok.
Step 4 − Enter the details of the node slave machine. In the below example, we are considering the slave machine to be a windows machine, hence the option of “Let Jenkins control this Windows slave as a Windows service” was chosen as the launch method. We also need to add the necessary details of the slave node such as the node name and the login credentials for the node machine. Click the Save button. The Labels for which the name is entered as “New_Slave” is what can be used to configure jobs to use this slave machine.
Once the above steps are completed, the new node machine will initially be in an offline state, but will come online if all the settings in the previous screen were entered correctly. One can at any time make the node slave machine as offline if required.
There are many plugins available which can be used to transfer the build files after a successful build to the respective application/web server. On example is the “Deploy to container Plugin”. To use this follow the steps given below.
Step 1 − Go to Manage Jenkins → Manage Plugins. Go to the Available section and find the plugin “Deploy to container Plugin” and install the plugin. Restart the Jenkins server.
This plugin takes a war/ear file and deploys that to a running remote application server at the end of a build.
Tomcat 4.x/5.x/6.x/7.x
JBoss 3.x/4.x
Glassfish 2.x/3.x
Step 2 − Go to your Build project and click the Configure option. Choose the option “Deploy war/ear to a container”
Step 3 − In the Deploy war/ear to a container section, enter the required details of the server on which the files need to be deployed and click on the Save button. These steps will now ensure that the necessary files get deployed to the necessary container after a successful build.
There are various plugins which are available in Jenkins to showcase metrics for builds which are carried out over a period of time. These metrics are useful to understand your builds and how frequently they fail/pass over time. As an example, let’s look at the ‘Build History Metrics plugin’.
This plugin calculates the following metrics for all of the builds once installed
Mean Time To Failure (MTTF)
Mean Time To Recovery (MTTR)
Standard Deviation of Build Times
Step 1 − Go to the Jenkins dashboard and click on Manage Jenkins
Step 2 − Go to the Manage Plugins option.
Step 3 − Go to the Available tab and search for the plugin ‘Build History Metrics plugin’ and choose to ‘install without restart’.
Step 4 − The following screen shows up to confirm successful installation of the plugin. Restart the Jenkins instance.
When you go to your Job page, you will see a table with the calculated metrics. Metric’s are shown for the last 7 days, last 30 days and all time.
To see overall trends in Jenkins, there are plugins available to gather information from within the builds and Jenkins and display them in a graphical format. One example of such a plugin is the ‘Hudson global-build-stats plugin’. So let’s go through the steps for this.
Step 1 − Go to the Jenkins dashboard and click on Manage Jenkins
Step 2 − Go to the Manage Plugins option
Step 3 − Go to the Available tab and search for the plugin ‘Hudson global-build-stats plugin’ and choose to ‘install without restart’.
Step 4 − The following screen shows up to confirm successful installation of the plugin. Restart the Jenkins instance.
To see the Global statistics, please follow the Step 5 through 8.
Step 5 − Go to the Jenkins dashboard and click on Manage Jenkins. In the Manage Jenkins screen, scroll down and now you will now see an option called ‘Global Build Stats’. Click on this link.
Step 6 − Click on the button ‘Initialize stats’. What this does is that it gather’s all the existing records for builds which have already been carried out and charts can be created based on these results.
Step 7 − Once the data has been initialized, it’s time to create a new chart. Click on the ‘Create new chart’ link.
Step 8 − A pop-up will come to enter relevant information for the new chart details. Enter the following mandatory information
Title – Any title information, for this example is given as ‘Demo’
Chart Width – 800
Chart Height – 600
Chart time scale – Daily
Chart time length – 30 days
The rest of the information can remain as it is. Once the information is entered, click on Create New chart.
You will now see the chart which displays the trends of the builds over time.
If you click on any section within the chart, it will give you a drill down of the details of the job and their builds.
The following are some of the basic activities you will carry out, some of which are best practices for Jenkins server maintenance
The following commands when appended to the Jenkins instance URL will carry out the relevant actions on the Jenkins instance.
http://localhost:8080/jenkins/exit − shutdown jenkins
http://localhost:8080/jenkins/restart − restart jenkins
http://localhost:8080/jenkins/reload − to reload the configuration
The Jenkins Home directory is nothing but the location on your drive where Jenkins stores all information for the jobs, builds etc. The location of your home directory can be seen when you click on Manage Jenkins → Configure system.
Set up Jenkins on the partition that has the most free disk-space – Since Jenkins would be taking source code for the various jobs defined and doing continuous builds, always ensure that Jenkins is setup on a drive that has enough hard disk space. If you hard disk runs out of space, then all builds on the Jenkins instance will start failing.
Another best practice is to write cron jobs or maintenance tasks that can carry out clean-up operations to avoid the disk where Jenkins is setup from becoming full.
Jenkins provides good support for providing continuous deployment and delivery. If you look at the flow of any software development through deployment, it will be as shown below.
The main part of Continuous deployment is to ensure that the entire process which is shown above is automated. Jenkins achieves all of this via various plugins, one of them being the “Deploy to container Plugin” which was seen in the earlier lessons.
There are plugins available which can actually give you a graphical representation of the Continuous deployment process. But first lets create another project in Jenkins, so that we can see best how this works.
Let’s create a simple project which emulates the QA stage, and does a test of the Helloworld application.
Step 1 − Go to the Jenkins dashboard and click on New Item. Choose a ‘Freestyle project’ and enter the project name as ‘QA’. Click on the Ok button to create the project.
Step 2 − In this example, we are keeping it simple and just using this project to execute a test program for the Helloworld application.
So our project QA is now setup. You can do a build to see if it builds properly.
Step 3 − Now go to you Helloworld project and click on the Configure option
Step 4 − In the project configuration, choose the ‘Add post-build action’ and choose ‘Build other projects’
Step 5 − In the ‘Project to build’ section, enter QA as the project name to build. You can leave the option as default of ‘Trigger only if build is stable’. Click on the Save button.
Step 6 − Build the Helloworld project. Now if you see the Console output, you will also see that after the Helloworld project is successfully built, the build of the QA project will also happen.
Step 7 − Let now install the Delivery pipeline plugin. Go to Manage Jenkins → Manage Plugin’s. In the available tab, search for ‘Delivery Pipeline Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance.
Step 8 − To see the Delivery pipeline in action, in the Jenkins Dashboard, click on the + symbol in the Tab next to the ‘All’ Tab.
Step 9 − Enter any name for the View name and choose the option ‘Delivery Pipeline View’.
Step 10 − In the next screen, you can leave the default options. One can change the following settings −
Ensure the option ‘Show static analysis results’ is checked.
Ensure the option ‘Show total build time’ is checked.
For the Initial job – Enter the Helloworld project as the first job which should build.
Enter any name for the Pipeline
Click the OK button.
You will now see a great view of the entire delivery pipeline and you will be able to see the status of each project in the entire pipeline.
Another famous plugin is the build pipeline plugin. Let’s take a look at this.
Step 1 − Go to Manage Jenkins → Manage Plugin’s. In the available tab, search for ‘Build Pipeline Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance.
Step 2 − To see the Build pipeline in action, in the Jenkins Dashboard, click on the + symbol in the Tab next to the ‘All’ Tab.
Step 3 − Enter any name for the View name and choose the option ‘Build Pipeline View’.
Step 4 − Accept the default settings, just in the Selected Initial job, ensure to enter the name of the Helloworld project. Click on the Ok button.
You will now see a great view of the entire delivery pipeline and you will be able to see the status of each project in the entire pipeline.
To get the list of all plugins available within Jenkins, one can visit the link − https://wiki.jenkins-ci.org/display/JENKINS/Plugins
We’ve already seen many instances for installing plugins, let’s look at some other maintenance tasks with regards to plugins
To uninstall a plugin, Go to Manage Jenkins → Manage plugins. Click on the Installed tab. Some of the plugins will have the Uninstall option. You can click these buttons to uninstall the plugins. Ensure to restart your Jenkins instance after the uninstallation.
Sometimes it may be required to install an older version of a plugin, in such a case, you can download the plugin from the relevant plugin page on the Jenkins web site. You can then use the Upload option to upload the plugin manually.
In Jenkins you have the ability to setup users and their relevant permissions on the Jenkins instance. By default you will not want everyone to be able to define jobs or other administrative tasks in Jenkins. So Jenkins has the ability to have a security configuration in place.
To configure Security in Jenkins, follow the steps given below.
Step 1 − Click on Manage Jenkins and choose the ‘Configure Global Security’ option.
Step 2 − Click on Enable Security option. As an example, let’s assume that we want Jenkins to maintain it’s own database of users, so in the Security Realm, choose the option of ‘Jenkins’ own user database’.
By default you would want a central administrator to define users in the system, hence ensure the ‘Allow users to sign up’ option is unselected. You can leave the rest as it is for now and click the Save button.
Step 3 − You will be prompted to add your first user. As an example, we are setting up an admin users for the system.
Step 4 − It’s now time to setup your users in the system. Now when you go to Manage Jenkins, and scroll down, you will see a ‘Manage Users’ option. Click this option.
Step 5 − Just like you defined your admin user, start creating other users for the system. As an example, we are just creating another user called ‘user’.
Step 6 − Now it’s time to setup your authorizations, basically who has access to what. Go to Manage Jenkins → Configure Global Security.
Now in the Authorization section, click on ‘Matrix based security’
Step 7 − If you don’t see the user in the user group list, enter the user name and add it to the list. Then give the appropriate permissions to the user.
Click on the Save button once you have defined the relevant authorizations.
Your Jenkins security is now setup.
Note − For Windows AD authentication, one has to add the Active Directory plugin to Jenkins.
Jenkins has a backup plugin which can used to backup critical configuration settings related to Jenkins. Follow the steps given below to have a backup in place.
Step 1 − Click on Manage Jenkins and choose the ‘Manage Plugins’ option.
Step 2 − In the available tab, search for ‘Backup Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance
Step 3 − Now when you go to Manage Jenkins, and scroll down you will see ‘Backup Manager’ as an option. Click on this option.
Step 4 − Click on Setup.
Step 5 − Here, the main field to define is the directory for your backup. Ensure it’s on another drive which is different from the drive where your Jenkins instance is setup. Click on the Save button.
Step 6 − Click on the ‘Backup Hudson configuration’ from the Backup manager screen to initiate the backup.
The next screen will show the status of the backup
To recover from a backup, go to the Backup Manager screen, click on Restore Hudson configuration.
The list of backup’s will be shown, click on the appropriate one to click on Launch Restore to begin the restoration of the backup.
Web tests such as selenium tests can be run on remote slave machines via the master slave and selenium suite plugin installation. The following steps show how to run remote tests using this configuration.
Step 1 − Ensure your master slave configuration is in place. Go to your master Jenkins server. Go to Manage Jenkins → Manage Nodes.
In our node list, the DXBMEM30 label is the slave machine. In this example, both the master and slave machines are windows machines.
Step 2 − Click on configure for the DXBMEM30 slave machine.
Step 3 − Ensure the launch method is put as ‘Launch slave agents via Java Web Start’
Step 4 − Now go to your slave machine and from there, open a browser instance to your Jenkins master instance. Then go to Manage Jenkins → Manage Nodes. Go to DXBMEM30 and click on
Step 5 − Click on the DXBMEM30 instance.
Step 6 − Scroll down and you will see the Launch option which is the option to Start ‘Java Web Start’
Step 7 − You will be presented with a Security Warning. Click on the Acceptance checkbox and click on run.
You will now see a Jenkins Slave window opened and now connected.
Step 8 − Configuring your tests to run on the slave. Here, you have to ensure that the job being created is meant specifically to only run the selenium tests.
In the job configuration, ensure the option ‘Restrict where this project can be run’ is selected and in the Label expression put the name of the slave node.
Step 9 − Ensure the selenium part of your job is configured. You have to ensure that the Sample.html file and the selenium-server.jar file is also present on the slave machine.
Once you have followed all of the above steps, and click on Build, this project will run the Selenium test on the slave machine as expected.
38 Lectures
5 hours
Eduonix Learning Solutions
41 Lectures
5 hours
AR Shankar
42 Lectures
2 hours
Chaitanya Allidona
37 Lectures
2.5 hours
Spotle Learn
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2342,
"s": 2123,
"text": "Jenkins is a software that allows continuous integration. Jenkins will be installed on a server where the central build will take place. The following flowchart demonstrates a very simple workflow of how Jenkins works."
},
{
"code": null,
"e": 2698,
"s": 2342,
"text": "Along with Jenkins, sometimes, one might also see the association of Hudson. Hudson is a very popular open-source Java-based continuous integration tool developed by Sun Microsystems which was later acquired by Oracle. After the acquisition of Sun by Oracle, a fork was created from the Hudson source code, which brought about the introduction of Jenkins."
},
{
"code": null,
"e": 3104,
"s": 2698,
"text": "Continuous Integration is a development practice that requires developers to integrate code into a shared repository at regular intervals. This concept was meant to remove the problem of finding later occurrence of issues in the build lifecycle. Continuous integration requires the developers to have frequent builds. The common practice is that whenever a code commit occurs, a build should be triggered."
},
{
"code": null,
"e": 3252,
"s": 3104,
"text": "The official website for Jenkins is Jenkins. If you click the given link, you can get the home page of the Jenkins official website as shown below."
},
{
"code": null,
"e": 3465,
"s": 3252,
"text": "By default, the latest release and the Long-Term support release will be available for download. The past releases are also available for download. Click the Long-Term Support Release tab in the download section."
},
{
"code": null,
"e": 3541,
"s": 3465,
"text": "Click the link “Older but stable version” to download the Jenkins war file."
},
{
"code": null,
"e": 3680,
"s": 3541,
"text": "Open the command prompt. From the command prompt, browse to the directory where the jenkins.war file is present. Run the following command"
},
{
"code": null,
"e": 3707,
"s": 3680,
"text": "D:\\>Java –jar Jenkins.war\n"
},
{
"code": null,
"e": 3860,
"s": 3707,
"text": "After the command is run, various tasks will run, one of which is the extraction of the war file which is done by an embedded webserver called winstone."
},
{
"code": null,
"e": 4039,
"s": 3860,
"text": "D:\\>Java –jar Jenkins.war\nRunning from: D:\\jenkins.war\nWebroot: $user.home/ .jenkins\nSep 29, 2015 4:10:46 PM winstone.Logger logInternal\nINFO: Beginning extraction from war file\n"
},
{
"code": null,
"e": 4159,
"s": 4039,
"text": "Once the processing is complete without major errors, the following line will come in the output of the command prompt."
},
{
"code": null,
"e": 4198,
"s": 4159,
"text": "INFO: Jenkins is fully up and running\n"
},
{
"code": null,
"e": 4291,
"s": 4198,
"text": "Once Jenkins is up and running, one can access Jenkins from the link − http://localhost:8080"
},
{
"code": null,
"e": 4338,
"s": 4291,
"text": "This link will bring up the Jenkins dashboard."
},
{
"code": null,
"e": 4404,
"s": 4338,
"text": "The following prerequisites must be met for Jenkins Tomcat setup."
},
{
"code": null,
"e": 4490,
"s": 4404,
"text": "To verify Java installation, open the console and execute the following java command."
},
{
"code": null,
"e": 4638,
"s": 4490,
"text": "If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on."
},
{
"code": null,
"e": 4662,
"s": 4638,
"text": "Java version \"1.7.0_60\""
},
{
"code": null,
"e": 4717,
"s": 4662,
"text": "Java (TM) SE Run Time Environment (build 1.7.0_60-b19)"
},
{
"code": null,
"e": 4782,
"s": 4717,
"text": "Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode)"
},
{
"code": null,
"e": 4806,
"s": 4782,
"text": "java version \"1.7.0_25\""
},
{
"code": null,
"e": 4864,
"s": 4806,
"text": "Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)"
},
{
"code": null,
"e": 4919,
"s": 4864,
"text": "Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)"
},
{
"code": null,
"e": 5040,
"s": 4919,
"text": "We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial."
},
{
"code": null,
"e": 5115,
"s": 5040,
"text": "In case you do not have Java JDK, you can download it from the link Oracle"
},
{
"code": null,
"e": 5248,
"s": 5115,
"text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,"
},
{
"code": null,
"e": 5319,
"s": 5248,
"text": "Append the full path of the Java compiler location to the System Path."
},
{
"code": null,
"e": 5391,
"s": 5319,
"text": "Verify the command java-version from command prompt as explained above."
},
{
"code": null,
"e": 5536,
"s": 5391,
"text": "The official website for tomcat is Tomcat. If you click the given link, you can get the home page of the tomcat official website as shown below."
},
{
"code": null,
"e": 5629,
"s": 5536,
"text": "Browse to the link https://tomcat.apache.org/download-70.cgi to get the download for tomcat."
},
{
"code": null,
"e": 5709,
"s": 5629,
"text": "Go to the ‘Binary Distributions’ section. Download the 32-bit Windows zip file."
},
{
"code": null,
"e": 5761,
"s": 5709,
"text": "Then unzip the contents of the downloaded zip file."
},
{
"code": null,
"e": 5889,
"s": 5761,
"text": "Copy the Jenkis.war file which was downloaded from the previous section and copy it to the webapps folder in the tomcat folder."
},
{
"code": null,
"e": 6075,
"s": 5889,
"text": "Now open the command prompt. From the command prompt, browse to the directory where the tomcat7 folder is location. Browse to the bin directory in this folder and run the start.bat file"
},
{
"code": null,
"e": 6108,
"s": 6075,
"text": "E:\\Apps\\tomcat7\\bin>startup.bat\n"
},
{
"code": null,
"e": 6228,
"s": 6108,
"text": "Once the processing is complete without major errors, the following line will come in the output of the command prompt."
},
{
"code": null,
"e": 6261,
"s": 6228,
"text": "INFO: Server startup in 1302 ms\n"
},
{
"code": null,
"e": 6372,
"s": 6261,
"text": "Open the browser and go to the link − http://localhost:8080/jenkins. Jenkins will be up and running on tomcat."
},
{
"code": null,
"e": 6592,
"s": 6372,
"text": "For this exercise, you have to ensure that Internet connectivity is present from the machine on which Jenkins is installed. In your Jenkins Dashboard (Home screen), click the Manage Jenkins option on the left hand side."
},
{
"code": null,
"e": 6647,
"s": 6592,
"text": "In the next screen, click the ‘Manage Plugins’ option."
},
{
"code": null,
"e": 6804,
"s": 6647,
"text": "In the next screen, click the Available tab. This tab will give a list of plugins which are available for downloading. In the ‘Filter’ tab type ‘Git plugin’"
},
{
"code": null,
"e": 6914,
"s": 6804,
"text": "The list will then be filtered. Check the Git Plugin option and click on the button ‘Install without restart’"
},
{
"code": null,
"e": 7016,
"s": 6914,
"text": "The installation will then begin and the screen will be refreshed to show the status of the download."
},
{
"code": null,
"e": 7154,
"s": 7016,
"text": "Once all installations are complete, restart Jenkins by issue the following command in the browser. http://localhost:8080/jenkins/restart"
},
{
"code": null,
"e": 7450,
"s": 7154,
"text": "After Jenkins is restarted, Git will be available as an option whilst configuring jobs. To verify, click on New Item in the menu options for Jenkins. Then enter a name for a job, in the following case, the name entered is ‘Demo’. Select ‘Freestyle project’ as the item type. Click the Ok button."
},
{
"code": null,
"e": 7560,
"s": 7450,
"text": "In the next screen, if you browse to the Source code Management section, you will now see ‘Git’ as an option."
},
{
"code": null,
"e": 7709,
"s": 7560,
"text": "The official website for maven is Apache Maven. If you click the given link, you can get the home page of the maven official website as shown below."
},
{
"code": null,
"e": 7807,
"s": 7709,
"text": "While browsing to the site, go to the Files section and download the link to the Binary.zip file."
},
{
"code": null,
"e": 7970,
"s": 7807,
"text": "Once the file is downloaded, extract the files to the relevant application folder. For this purpose, the maven files will be placed in E:\\Apps\\apache-maven-3.3.3."
},
{
"code": null,
"e": 8061,
"s": 7970,
"text": "In the Jenkins dashboard (Home screen), click Manage Jenkins from the left-hand side menu."
},
{
"code": null,
"e": 8121,
"s": 8061,
"text": "Then, click on ‘Configure System’ from the right hand side."
},
{
"code": null,
"e": 8238,
"s": 8121,
"text": "In the Configure system screen, scroll down till you see the Maven section and then click on the ‘Add Maven’ button."
},
{
"code": null,
"e": 8282,
"s": 8238,
"text": "Uncheck the ‘Install automatically’ option."
},
{
"code": null,
"e": 8347,
"s": 8282,
"text": "Add any name for the setting and the location of the MAVEN_HOME."
},
{
"code": null,
"e": 8406,
"s": 8347,
"text": "Then, click on the ‘Save’ button at the end of the screen."
},
{
"code": null,
"e": 8517,
"s": 8406,
"text": "You can now create a job with the ‘Maven project’ option. In the Jenkins dashboard, click the New Item option."
},
{
"code": null,
"e": 8708,
"s": 8517,
"text": "You probably would have seen a couple of times in the previous exercises wherein we had to configure options within Jenkins. The following shows the various configuration options in Jenkins."
},
{
"code": null,
"e": 8839,
"s": 8708,
"text": "So one can get the various configuration options for Jenkins by clicking the ‘Manage Jenkins’ option from the left hand menu side."
},
{
"code": null,
"e": 8894,
"s": 8839,
"text": "You will then be presented with the following screen −"
},
{
"code": null,
"e": 9010,
"s": 8894,
"text": "Click on Configure system. Discussed below are some of the Jenkins configuration settings which can be carried out."
},
{
"code": null,
"e": 9428,
"s": 9010,
"text": "Jenkins needs some disk space to perform builds and keep archives. One can check this location from the configuration screen of Jenkins. By default, this is set to ~/.jenkins, and this location will initially be stored within your user profile location. In a proper environment, you need to change this location to an adequate location to store all relevant builds and archives. Once can do this in the following ways"
},
{
"code": null,
"e": 9534,
"s": 9428,
"text": "Set \"JENKINS_HOME\" environment variable to the new home directory before launching the servlet container."
},
{
"code": null,
"e": 9640,
"s": 9534,
"text": "Set \"JENKINS_HOME\" environment variable to the new home directory before launching the servlet container."
},
{
"code": null,
"e": 9701,
"s": 9640,
"text": "Set \"JENKINS_HOME\" system property to the servlet container."
},
{
"code": null,
"e": 9762,
"s": 9701,
"text": "Set \"JENKINS_HOME\" system property to the servlet container."
},
{
"code": null,
"e": 9826,
"s": 9762,
"text": "Set JNDI environment entry \"JENKINS_HOME\" to the new directory."
},
{
"code": null,
"e": 9890,
"s": 9826,
"text": "Set JNDI environment entry \"JENKINS_HOME\" to the new directory."
},
{
"code": null,
"e": 9990,
"s": 9890,
"text": "The following example will use the first option of setting the \"JENKINS_HOME\" environment variable."
},
{
"code": null,
"e": 10107,
"s": 9990,
"text": "First create a new folder E:\\Apps\\Jenkins. Copy all the contents from the existing ~/.jenkins to this new directory."
},
{
"code": null,
"e": 10243,
"s": 10107,
"text": "Set the JENKINS_HOME environment variable to point to the base directory location where Java is installed on your machine. For example,"
},
{
"code": null,
"e": 10379,
"s": 10243,
"text": "In the Jenkins dashboard, click Manage Jenkins from the left hand side menu. Then click on ‘Configure System’ from the right hand side."
},
{
"code": null,
"e": 10464,
"s": 10379,
"text": "In the Home directory, you will now see the new directory which has been configured."
},
{
"code": null,
"e": 10734,
"s": 10464,
"text": "This refers to the total number of concurrent job executions that can take place on the Jenkins machine. This can be changed based on requirements. Sometimes the recommendation is to keep this number the same as the number of CPU on the machines for better performance."
},
{
"code": null,
"e": 10901,
"s": 10734,
"text": "This is used to add custom environment variables which will apply to all the jobs. These are key-value pairs and can be accessed and used in Builds wherever required."
},
{
"code": null,
"e": 11280,
"s": 10901,
"text": "By default, the Jenkins URL points to localhost. If you have a domain name setup for your machine, set this to the domain name else overwrite localhost with IP of machine. This will help in setting up slaves and while sending out links using the email as you can directly access the Jenkins URL using the environment variable JENKINS_URL which can be accessed as ${JENKINS_URL}."
},
{
"code": null,
"e": 11479,
"s": 11280,
"text": "In the email Notification area, you can configure the SMTP settings for sending out emails. This is required for Jenkins to connect to the SMTP mail server and send out emails to the recipient list."
},
{
"code": null,
"e": 11565,
"s": 11479,
"text": "To manage Jenkins, click on the ‘Manage Jenkins’ option from the left hand menu side."
},
{
"code": null,
"e": 11696,
"s": 11565,
"text": "So one can get the various configuration options for Jenkins by clicking the ‘Manage Jenkins’ option from the left hand menu side."
},
{
"code": null,
"e": 11751,
"s": 11696,
"text": "You will then be presented with the following screen −"
},
{
"code": null,
"e": 11799,
"s": 11751,
"text": "Some of the management options are as follows −"
},
{
"code": null,
"e": 12135,
"s": 11799,
"text": "This is where one can manage paths to the various tools to use in builds, such as the JDKs, the versions of Ant and Maven, as well as security options, email servers, and other system-wide configuration details. When plugins are installed. Jenkins will add the required configuration fields dynamically after the plugins are installed."
},
{
"code": null,
"e": 12689,
"s": 12135,
"text": "Jenkins stores all its system and build job configuration details as XML files which is stored in the Jenkins home directory. Here also all of the build history is stored. If you are migrating build jobs from one Jenkins instance to another, or archiving old build jobs, you will need to add or remove the corresponding build job directories to Jenkins’s builds directory. You don’t need to take Jenkins offline to do this—you can simply use the “Reload Configuration from Disk” option to reload the Jenkins system and build job configurations directly."
},
{
"code": null,
"e": 12969,
"s": 12689,
"text": "Here one can install a wide variety of third-party plugins right from different Source code management tools such as Git, Mercurial or ClearCase, to code quality and code coverage metrics reporting. Plugins can be installed, updated and removed through the Manage Plugins screen."
},
{
"code": null,
"e": 13189,
"s": 12969,
"text": "This screen displays a list of all the current Java system properties and system environment variables. Here one can check exactly what version of Java Jenkins is running in, what user it is running under, and so forth."
},
{
"code": null,
"e": 13282,
"s": 13189,
"text": "The following screenshot shows some of the name-value information available in this section."
},
{
"code": null,
"e": 13427,
"s": 13282,
"text": "The System Log screen is a convenient way to view the Jenkins log files in real time. Again, the main use of this screen is for troubleshooting."
},
{
"code": null,
"e": 13789,
"s": 13427,
"text": "This pages displays graphical data on how busy the Jenkins instance is in terms of the number of concurrent builds and the length of the build queue which gives an idea of how long your builds need to wait before being executed. These statistics can give a good idea of whether extra capacity or extra build nodes is required from an infrastructure perspective."
},
{
"code": null,
"e": 13961,
"s": 13789,
"text": "This screen lets you run Groovy scripts on the server. It is useful for advanced troubleshooting since it requires a strong knowledge of the internal Jenkins architecture."
},
{
"code": null,
"e": 14252,
"s": 13961,
"text": "Jenkins is capable of handling parallel and distributed builds. In this screen, you can configure how many builds you want. Jenkins runs simultaneously, and, if you are using distributed builds, set up build nodes. A build node is another machine that Jenkins can use to execute its builds."
},
{
"code": null,
"e": 14614,
"s": 14252,
"text": "If there is a need to shut down Jenkins, or the server Jenkins is running on, it is best not to do so when a build is being executed. To shut down Jenkins cleanly, you can use the Prepare for Shutdown link, which prevents any new builds from being started. Eventually, when all of the current builds have finished, one will be able to shut down Jenkins cleanly."
},
{
"code": null,
"e": 14747,
"s": 14614,
"text": "For this exercise, we will create a job in Jenkins which picks up a simple HelloWorld application, builds and runs the java program."
},
{
"code": null,
"e": 14806,
"s": 14747,
"text": "Step 1 − Go to the Jenkins dashboard and Click on New Item"
},
{
"code": null,
"e": 14936,
"s": 14806,
"text": "Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’"
},
{
"code": null,
"e": 15028,
"s": 14936,
"text": "Step 3 − The following screen will come up in which you can specify the details of the job."
},
{
"code": null,
"e": 15323,
"s": 15028,
"text": "Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git repository(E:\\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of the local git repository."
},
{
"code": null,
"e": 15623,
"s": 15323,
"text": "Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository."
},
{
"code": null,
"e": 15720,
"s": 15623,
"text": "Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command"
},
{
"code": null,
"e": 15816,
"s": 15720,
"text": "Step 6 − In the command window, enter the following commands and then click on the Save button."
},
{
"code": null,
"e": 15855,
"s": 15816,
"text": "Javac HelloWorld.java\nJava HelloWorld\n"
},
{
"code": null,
"e": 15963,
"s": 15855,
"text": "Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job."
},
{
"code": null,
"e": 16085,
"s": 15963,
"text": "Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress."
},
{
"code": null,
"e": 16331,
"s": 16085,
"text": "Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has been executed successfully. Click on the #1 in the Build history to bring up the details of the build."
},
{
"code": null,
"e": 16406,
"s": 16331,
"text": "Step 10 − Click on the Console Output link to see the details of the build"
},
{
"code": null,
"e": 16592,
"s": 16406,
"text": "Apart from the steps shown above there are just so many ways to create a build job, the options available are many, which what makes Jenkins such a fantastic continuous deployment tool."
},
{
"code": null,
"e": 16901,
"s": 16592,
"text": "Jenkins provides an out of box functionality for Junit, and provides a host of plugins for unit testing for other technologies, an example being MSTest for .Net Unit tests. If you go to the link https://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin it will give the list of Unit Testing plugins available."
},
{
"code": null,
"e": 16937,
"s": 16901,
"text": "The following example will consider"
},
{
"code": null,
"e": 16983,
"s": 16937,
"text": "A simple HelloWorldTest class based on Junit."
},
{
"code": null,
"e": 17052,
"s": 16983,
"text": "Ant as the build tool within Jenkins to build the class accordingly."
},
{
"code": null,
"e": 17166,
"s": 17052,
"text": "Step 1 − Go to the Jenkins dashboard and Click on the existing HelloWorld project and choose the Configure option"
},
{
"code": null,
"e": 17254,
"s": 17166,
"text": "Step 2 − Browse to the section to Add a Build step and choose the option to Invoke Ant."
},
{
"code": null,
"e": 17293,
"s": 17254,
"text": "Step 3 − Click on the Advanced button."
},
{
"code": null,
"e": 17371,
"s": 17293,
"text": "Step 4 − In the build file section, enter the location of the build.xml file."
},
{
"code": null,
"e": 17487,
"s": 17371,
"text": "Step 5 − Next click the option to Add post-build option and choose the option of “Publish Junit test result report”"
},
{
"code": null,
"e": 17851,
"s": 17487,
"text": "Step 6 − In the Test reports XML’s, enter the location as shown below. Ensure that Reports is a folder which is created in the HelloWorld project workspace. The “*.xml” basically tells Jenkins to pick up the result xml files which are produced by the running of the Junit test cases. These xml files which then be converted into reports which can be viewed later."
},
{
"code": null,
"e": 17896,
"s": 17851,
"text": "Once done, click the Save option at the end."
},
{
"code": null,
"e": 17956,
"s": 17896,
"text": "Step 7 − Once saved, you can click on the Build Now option."
},
{
"code": null,
"e": 18243,
"s": 17956,
"text": "Once the build is completed, a status of the build will show if the build was successful or not. In the Build output information, you will now notice an additional section called Test Result. In our case, we entered a negative Test case so that the result would fail just as an example."
},
{
"code": null,
"e": 18420,
"s": 18243,
"text": "One can go to the Console output to see further information. But what’s more interesting is that if you click on Test Result, you will now see a drill down of the Test results."
},
{
"code": null,
"e": 18956,
"s": 18420,
"text": "One of the basic principles of Continuous Integration is that a build should be verifiable. You have to be able to objectively determine whether a particular build is ready to proceed to the next stage of the build process, and the most convenient way to do this is to use automated tests. Without proper automated testing, you find yourself having to retain many build artifacts and test them by hand, which is hardly in the spirit of Continuous Integration. The following example shows how to use Selenium to run automated web tests."
},
{
"code": null,
"e": 18987,
"s": 18956,
"text": "Step 1 − Go to Manage Plugins."
},
{
"code": null,
"e": 19081,
"s": 18987,
"text": "Step 2 − Find the Hudson Selenium Plugin and choose to install. Restart the Jenkins instance."
},
{
"code": null,
"e": 19114,
"s": 19081,
"text": "Step 3 − Go to Configure system."
},
{
"code": null,
"e": 19187,
"s": 19114,
"text": "Step 4 − Configure the selenium server jar and click on the Save button."
},
{
"code": null,
"e": 19263,
"s": 19187,
"text": "Note − The selenium jar file can be downloaded from the location SeleniumHQ"
},
{
"code": null,
"e": 19321,
"s": 19263,
"text": "Click on the download for the Selenium standalone server."
},
{
"code": null,
"e": 19418,
"s": 19321,
"text": "Step 5 − Go back to your dashboard and click on the Configure option for the HelloWorld project."
},
{
"code": null,
"e": 19502,
"s": 19418,
"text": "Step 6 − Click on Add build step and choose the optin of “SeleniumHQ htmlSuite Run”"
},
{
"code": null,
"e": 19747,
"s": 19502,
"text": "Step 7 − Add the necessary details for the selenium test. Here the suiteFile is the TestSuite generated by using the Selenium IDE. Click on Save and execute a build. Now the post build will launch the selenium driver, and execute the html test."
},
{
"code": null,
"e": 19839,
"s": 19747,
"text": "Jenkins comes with an out of box facility to add an email notification for a build project."
},
{
"code": null,
"e": 20020,
"s": 19839,
"text": "Step 1 − Configuring an SMTP server. Goto Manage Jenkins → Configure System. Go to the E-mail notification section and enter the required SMTP server and user email-suffix details."
},
{
"code": null,
"e": 20271,
"s": 20020,
"text": "Step 2 − Configure the recipients in the Jenkins project - When you configure any Jenkins build project, right at the end is the ability to add recipients who would get email notifications for unstable or broken builds. Then click on the Save button."
},
{
"code": null,
"e": 20551,
"s": 20271,
"text": "Apart from the default, there are also notification plugin’s available in the market. An example is the notification plugin from Tikal Knowledge which allows sending Job Status notifications in JSON and XML formats. This plugin enables end-points to be configured as shown below."
},
{
"code": null,
"e": 20589,
"s": 20551,
"text": "Here are the details of each option −"
},
{
"code": null,
"e": 20673,
"s": 20589,
"text": "\"Format\" − This is the notification payload format which can either be JSON or XML."
},
{
"code": null,
"e": 20757,
"s": 20673,
"text": "\"Format\" − This is the notification payload format which can either be JSON or XML."
},
{
"code": null,
"e": 20839,
"s": 20757,
"text": "\"Protocol\" − protocol to use for sending notification messages, HTTP, TCP or UDP."
},
{
"code": null,
"e": 20921,
"s": 20839,
"text": "\"Protocol\" − protocol to use for sending notification messages, HTTP, TCP or UDP."
},
{
"code": null,
"e": 21052,
"s": 20921,
"text": "\"Event\" − The job events that trigger notifications: Job Started, Job Completed, Job Finalized or All Events (the default option)."
},
{
"code": null,
"e": 21183,
"s": 21052,
"text": "\"Event\" − The job events that trigger notifications: Job Started, Job Completed, Job Finalized or All Events (the default option)."
},
{
"code": null,
"e": 21318,
"s": 21183,
"text": "\"URL\" − URL to send notifications to. It takes the form of \"http://host\" for HTTP protocol, and \"host:port\" for TCP and UDP protocols."
},
{
"code": null,
"e": 21453,
"s": 21318,
"text": "\"URL\" − URL to send notifications to. It takes the form of \"http://host\" for HTTP protocol, and \"host:port\" for TCP and UDP protocols."
},
{
"code": null,
"e": 21546,
"s": 21453,
"text": "\"Timeout\" − Timeout in milliseconds for sending notification request, 30 seconds by default."
},
{
"code": null,
"e": 21639,
"s": 21546,
"text": "\"Timeout\" − Timeout in milliseconds for sending notification request, 30 seconds by default."
},
{
"code": null,
"e": 21789,
"s": 21639,
"text": "As demonstrated in the earlier section, there are many reporting plugins available with the simplest one being the reports available for jUnit tests."
},
{
"code": null,
"e": 21966,
"s": 21789,
"text": "In the Post-build action for any job, you can define the reports to be created. After the builds are complete, the Test Results option will be available for further drill-down."
},
{
"code": null,
"e": 22119,
"s": 21966,
"text": "Jenkins has a host of Code Analysis plugin. The various plugins can be found at https://wiki.jenkins-ci.org/display/JENKINS/Static+Code+Analysis+Plugins"
},
{
"code": null,
"e": 22381,
"s": 22119,
"text": "This plugin provides utilities for the static code analysis plugins. Jenkins can parse the results file from various Code Analysis tools such as CheckStyle, FindBugs, PMD etc. For each corresponding code analysis tool, a plugin in Jenkins needs to be installed."
},
{
"code": null,
"e": 22541,
"s": 22381,
"text": "Additionally the add-on plugin Static Analysis Collector is available that combines the individual results of these plugins into a single trend graph and view."
},
{
"code": null,
"e": 22585,
"s": 22541,
"text": "The plugins can provide information such as"
},
{
"code": null,
"e": 22623,
"s": 22585,
"text": "The total number of warnings in a job"
},
{
"code": null,
"e": 22674,
"s": 22623,
"text": "A showing of the new and fixed warnings of a build"
},
{
"code": null,
"e": 22729,
"s": 22674,
"text": "Trend Reports showing the number of warnings per build"
},
{
"code": null,
"e": 22799,
"s": 22729,
"text": "Overview of the found warnings per module, package, category, or type"
},
{
"code": null,
"e": 22889,
"s": 22799,
"text": "Detailed reports of the found warnings optionally filtered by severity (or new and fixed)"
},
{
"code": null,
"e": 23250,
"s": 22889,
"text": "Sometimes many build machines are required if there are instances wherein there are a larger and heavier projects which get built on a regular basis. And running all of these builds on a central machine may not be the best option. In such a scenario, one can configure other Jenkins machines to be slave machines to take the load off the master Jenkins server."
},
{
"code": null,
"e": 23425,
"s": 23250,
"text": "Sometimes you might also need several different environments to test your builds. In this case using a slave to represent each of your required environments is almost a must."
},
{
"code": null,
"e": 23771,
"s": 23425,
"text": "A slave is a computer that is set up to offload build projects from the master and once setup this distribution of tasks is fairly automatic. The exact delegation behavior depends on the configuration of each project; some projects may choose to \"stick\" to a particular machine for a build, while others may choose to roam freely between slaves."
},
{
"code": null,
"e": 24126,
"s": 23771,
"text": "Since each slave runs a separate program called a \"slave agent\" there is no need to install the full Jenkins (package or compiled binaries) on a slave. There are various ways to start slave agents, but in the end the slave agent and Jenkins master needs to establish a bi-directional communication link (for example a TCP/IP socket.) in order to operate."
},
{
"code": null,
"e": 24190,
"s": 24126,
"text": "To set up slaves/nodes in Jenkins follow the steps given below."
},
{
"code": null,
"e": 24280,
"s": 24190,
"text": "Step 1 − Go to the Manage Jenkins section and scroll down to the section of Manage Nodes."
},
{
"code": null,
"e": 24307,
"s": 24280,
"text": "Step 2 − Click on New Node"
},
{
"code": null,
"e": 24388,
"s": 24307,
"text": "Step 3 − Give a name for the node, choose the Dumb slave option and click on Ok."
},
{
"code": null,
"e": 24915,
"s": 24388,
"text": "Step 4 − Enter the details of the node slave machine. In the below example, we are considering the slave machine to be a windows machine, hence the option of “Let Jenkins control this Windows slave as a Windows service” was chosen as the launch method. We also need to add the necessary details of the slave node such as the node name and the login credentials for the node machine. Click the Save button. The Labels for which the name is entered as “New_Slave” is what can be used to configure jobs to use this slave machine."
},
{
"code": null,
"e": 25171,
"s": 24915,
"text": "Once the above steps are completed, the new node machine will initially be in an offline state, but will come online if all the settings in the previous screen were entered correctly. One can at any time make the node slave machine as offline if required."
},
{
"code": null,
"e": 25407,
"s": 25171,
"text": "There are many plugins available which can be used to transfer the build files after a successful build to the respective application/web server. On example is the “Deploy to container Plugin”. To use this follow the steps given below."
},
{
"code": null,
"e": 25584,
"s": 25407,
"text": "Step 1 − Go to Manage Jenkins → Manage Plugins. Go to the Available section and find the plugin “Deploy to container Plugin” and install the plugin. Restart the Jenkins server."
},
{
"code": null,
"e": 25696,
"s": 25584,
"text": "This plugin takes a war/ear file and deploys that to a running remote application server at the end of a build."
},
{
"code": null,
"e": 25719,
"s": 25696,
"text": "Tomcat 4.x/5.x/6.x/7.x"
},
{
"code": null,
"e": 25733,
"s": 25719,
"text": "JBoss 3.x/4.x"
},
{
"code": null,
"e": 25751,
"s": 25733,
"text": "Glassfish 2.x/3.x"
},
{
"code": null,
"e": 25867,
"s": 25751,
"text": "Step 2 − Go to your Build project and click the Configure option. Choose the option “Deploy war/ear to a container”"
},
{
"code": null,
"e": 26151,
"s": 25867,
"text": "Step 3 − In the Deploy war/ear to a container section, enter the required details of the server on which the files need to be deployed and click on the Save button. These steps will now ensure that the necessary files get deployed to the necessary container after a successful build."
},
{
"code": null,
"e": 26445,
"s": 26151,
"text": "There are various plugins which are available in Jenkins to showcase metrics for builds which are carried out over a period of time. These metrics are useful to understand your builds and how frequently they fail/pass over time. As an example, let’s look at the ‘Build History Metrics plugin’."
},
{
"code": null,
"e": 26527,
"s": 26445,
"text": "This plugin calculates the following metrics for all of the builds once installed"
},
{
"code": null,
"e": 26555,
"s": 26527,
"text": "Mean Time To Failure (MTTF)"
},
{
"code": null,
"e": 26584,
"s": 26555,
"text": "Mean Time To Recovery (MTTR)"
},
{
"code": null,
"e": 26618,
"s": 26584,
"text": "Standard Deviation of Build Times"
},
{
"code": null,
"e": 26683,
"s": 26618,
"text": "Step 1 − Go to the Jenkins dashboard and click on Manage Jenkins"
},
{
"code": null,
"e": 26725,
"s": 26683,
"text": "Step 2 − Go to the Manage Plugins option."
},
{
"code": null,
"e": 26856,
"s": 26725,
"text": "Step 3 − Go to the Available tab and search for the plugin ‘Build History Metrics plugin’ and choose to ‘install without restart’."
},
{
"code": null,
"e": 26975,
"s": 26856,
"text": "Step 4 − The following screen shows up to confirm successful installation of the plugin. Restart the Jenkins instance."
},
{
"code": null,
"e": 27122,
"s": 26975,
"text": "When you go to your Job page, you will see a table with the calculated metrics. Metric’s are shown for the last 7 days, last 30 days and all time."
},
{
"code": null,
"e": 27393,
"s": 27122,
"text": "To see overall trends in Jenkins, there are plugins available to gather information from within the builds and Jenkins and display them in a graphical format. One example of such a plugin is the ‘Hudson global-build-stats plugin’. So let’s go through the steps for this."
},
{
"code": null,
"e": 27458,
"s": 27393,
"text": "Step 1 − Go to the Jenkins dashboard and click on Manage Jenkins"
},
{
"code": null,
"e": 27499,
"s": 27458,
"text": "Step 2 − Go to the Manage Plugins option"
},
{
"code": null,
"e": 27634,
"s": 27499,
"text": "Step 3 − Go to the Available tab and search for the plugin ‘Hudson global-build-stats plugin’ and choose to ‘install without restart’."
},
{
"code": null,
"e": 27753,
"s": 27634,
"text": "Step 4 − The following screen shows up to confirm successful installation of the plugin. Restart the Jenkins instance."
},
{
"code": null,
"e": 27819,
"s": 27753,
"text": "To see the Global statistics, please follow the Step 5 through 8."
},
{
"code": null,
"e": 28011,
"s": 27819,
"text": "Step 5 − Go to the Jenkins dashboard and click on Manage Jenkins. In the Manage Jenkins screen, scroll down and now you will now see an option called ‘Global Build Stats’. Click on this link."
},
{
"code": null,
"e": 28217,
"s": 28011,
"text": "Step 6 − Click on the button ‘Initialize stats’. What this does is that it gather’s all the existing records for builds which have already been carried out and charts can be created based on these results."
},
{
"code": null,
"e": 28333,
"s": 28217,
"text": "Step 7 − Once the data has been initialized, it’s time to create a new chart. Click on the ‘Create new chart’ link."
},
{
"code": null,
"e": 28460,
"s": 28333,
"text": "Step 8 − A pop-up will come to enter relevant information for the new chart details. Enter the following mandatory information"
},
{
"code": null,
"e": 28527,
"s": 28460,
"text": "Title – Any title information, for this example is given as ‘Demo’"
},
{
"code": null,
"e": 28545,
"s": 28527,
"text": "Chart Width – 800"
},
{
"code": null,
"e": 28564,
"s": 28545,
"text": "Chart Height – 600"
},
{
"code": null,
"e": 28589,
"s": 28564,
"text": "Chart time scale – Daily"
},
{
"code": null,
"e": 28617,
"s": 28589,
"text": "Chart time length – 30 days"
},
{
"code": null,
"e": 28726,
"s": 28617,
"text": "The rest of the information can remain as it is. Once the information is entered, click on Create New chart."
},
{
"code": null,
"e": 28804,
"s": 28726,
"text": "You will now see the chart which displays the trends of the builds over time."
},
{
"code": null,
"e": 28924,
"s": 28804,
"text": "If you click on any section within the chart, it will give you a drill down of the details of the job and their builds."
},
{
"code": null,
"e": 29055,
"s": 28924,
"text": "The following are some of the basic activities you will carry out, some of which are best practices for Jenkins server maintenance"
},
{
"code": null,
"e": 29181,
"s": 29055,
"text": "The following commands when appended to the Jenkins instance URL will carry out the relevant actions on the Jenkins instance."
},
{
"code": null,
"e": 29235,
"s": 29181,
"text": "http://localhost:8080/jenkins/exit − shutdown jenkins"
},
{
"code": null,
"e": 29291,
"s": 29235,
"text": "http://localhost:8080/jenkins/restart − restart jenkins"
},
{
"code": null,
"e": 29358,
"s": 29291,
"text": "http://localhost:8080/jenkins/reload − to reload the configuration"
},
{
"code": null,
"e": 29591,
"s": 29358,
"text": "The Jenkins Home directory is nothing but the location on your drive where Jenkins stores all information for the jobs, builds etc. The location of your home directory can be seen when you click on Manage Jenkins → Configure system."
},
{
"code": null,
"e": 29935,
"s": 29591,
"text": "Set up Jenkins on the partition that has the most free disk-space – Since Jenkins would be taking source code for the various jobs defined and doing continuous builds, always ensure that Jenkins is setup on a drive that has enough hard disk space. If you hard disk runs out of space, then all builds on the Jenkins instance will start failing."
},
{
"code": null,
"e": 30100,
"s": 29935,
"text": "Another best practice is to write cron jobs or maintenance tasks that can carry out clean-up operations to avoid the disk where Jenkins is setup from becoming full."
},
{
"code": null,
"e": 30279,
"s": 30100,
"text": "Jenkins provides good support for providing continuous deployment and delivery. If you look at the flow of any software development through deployment, it will be as shown below."
},
{
"code": null,
"e": 30530,
"s": 30279,
"text": "The main part of Continuous deployment is to ensure that the entire process which is shown above is automated. Jenkins achieves all of this via various plugins, one of them being the “Deploy to container Plugin” which was seen in the earlier lessons."
},
{
"code": null,
"e": 30741,
"s": 30530,
"text": "There are plugins available which can actually give you a graphical representation of the Continuous deployment process. But first lets create another project in Jenkins, so that we can see best how this works."
},
{
"code": null,
"e": 30847,
"s": 30741,
"text": "Let’s create a simple project which emulates the QA stage, and does a test of the Helloworld application."
},
{
"code": null,
"e": 31018,
"s": 30847,
"text": "Step 1 − Go to the Jenkins dashboard and click on New Item. Choose a ‘Freestyle project’ and enter the project name as ‘QA’. Click on the Ok button to create the project."
},
{
"code": null,
"e": 31155,
"s": 31018,
"text": "Step 2 − In this example, we are keeping it simple and just using this project to execute a test program for the Helloworld application."
},
{
"code": null,
"e": 31236,
"s": 31155,
"text": "So our project QA is now setup. You can do a build to see if it builds properly."
},
{
"code": null,
"e": 31312,
"s": 31236,
"text": "Step 3 − Now go to you Helloworld project and click on the Configure option"
},
{
"code": null,
"e": 31420,
"s": 31312,
"text": "Step 4 − In the project configuration, choose the ‘Add post-build action’ and choose ‘Build other projects’"
},
{
"code": null,
"e": 31603,
"s": 31420,
"text": "Step 5 − In the ‘Project to build’ section, enter QA as the project name to build. You can leave the option as default of ‘Trigger only if build is stable’. Click on the Save button."
},
{
"code": null,
"e": 31798,
"s": 31603,
"text": "Step 6 − Build the Helloworld project. Now if you see the Console output, you will also see that after the Helloworld project is successfully built, the build of the QA project will also happen."
},
{
"code": null,
"e": 32029,
"s": 31798,
"text": "Step 7 − Let now install the Delivery pipeline plugin. Go to Manage Jenkins → Manage Plugin’s. In the available tab, search for ‘Delivery Pipeline Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance."
},
{
"code": null,
"e": 32160,
"s": 32029,
"text": "Step 8 − To see the Delivery pipeline in action, in the Jenkins Dashboard, click on the + symbol in the Tab next to the ‘All’ Tab."
},
{
"code": null,
"e": 32250,
"s": 32160,
"text": "Step 9 − Enter any name for the View name and choose the option ‘Delivery Pipeline View’."
},
{
"code": null,
"e": 32355,
"s": 32250,
"text": "Step 10 − In the next screen, you can leave the default options. One can change the following settings −"
},
{
"code": null,
"e": 32416,
"s": 32355,
"text": "Ensure the option ‘Show static analysis results’ is checked."
},
{
"code": null,
"e": 32470,
"s": 32416,
"text": "Ensure the option ‘Show total build time’ is checked."
},
{
"code": null,
"e": 32558,
"s": 32470,
"text": "For the Initial job – Enter the Helloworld project as the first job which should build."
},
{
"code": null,
"e": 32590,
"s": 32558,
"text": "Enter any name for the Pipeline"
},
{
"code": null,
"e": 32611,
"s": 32590,
"text": "Click the OK button."
},
{
"code": null,
"e": 32752,
"s": 32611,
"text": "You will now see a great view of the entire delivery pipeline and you will be able to see the status of each project in the entire pipeline."
},
{
"code": null,
"e": 32831,
"s": 32752,
"text": "Another famous plugin is the build pipeline plugin. Let’s take a look at this."
},
{
"code": null,
"e": 33013,
"s": 32831,
"text": "Step 1 − Go to Manage Jenkins → Manage Plugin’s. In the available tab, search for ‘Build Pipeline Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance."
},
{
"code": null,
"e": 33141,
"s": 33013,
"text": "Step 2 − To see the Build pipeline in action, in the Jenkins Dashboard, click on the + symbol in the Tab next to the ‘All’ Tab."
},
{
"code": null,
"e": 33228,
"s": 33141,
"text": "Step 3 − Enter any name for the View name and choose the option ‘Build Pipeline View’."
},
{
"code": null,
"e": 33376,
"s": 33228,
"text": "Step 4 − Accept the default settings, just in the Selected Initial job, ensure to enter the name of the Helloworld project. Click on the Ok button."
},
{
"code": null,
"e": 33517,
"s": 33376,
"text": "You will now see a great view of the entire delivery pipeline and you will be able to see the status of each project in the entire pipeline."
},
{
"code": null,
"e": 33651,
"s": 33517,
"text": "To get the list of all plugins available within Jenkins, one can visit the link − https://wiki.jenkins-ci.org/display/JENKINS/Plugins"
},
{
"code": null,
"e": 33776,
"s": 33651,
"text": "We’ve already seen many instances for installing plugins, let’s look at some other maintenance tasks with regards to plugins"
},
{
"code": null,
"e": 34038,
"s": 33776,
"text": "To uninstall a plugin, Go to Manage Jenkins → Manage plugins. Click on the Installed tab. Some of the plugins will have the Uninstall option. You can click these buttons to uninstall the plugins. Ensure to restart your Jenkins instance after the uninstallation."
},
{
"code": null,
"e": 34273,
"s": 34038,
"text": "Sometimes it may be required to install an older version of a plugin, in such a case, you can download the plugin from the relevant plugin page on the Jenkins web site. You can then use the Upload option to upload the plugin manually."
},
{
"code": null,
"e": 34552,
"s": 34273,
"text": "In Jenkins you have the ability to setup users and their relevant permissions on the Jenkins instance. By default you will not want everyone to be able to define jobs or other administrative tasks in Jenkins. So Jenkins has the ability to have a security configuration in place."
},
{
"code": null,
"e": 34616,
"s": 34552,
"text": "To configure Security in Jenkins, follow the steps given below."
},
{
"code": null,
"e": 34700,
"s": 34616,
"text": "Step 1 − Click on Manage Jenkins and choose the ‘Configure Global Security’ option."
},
{
"code": null,
"e": 34908,
"s": 34700,
"text": "Step 2 − Click on Enable Security option. As an example, let’s assume that we want Jenkins to maintain it’s own database of users, so in the Security Realm, choose the option of ‘Jenkins’ own user database’."
},
{
"code": null,
"e": 35120,
"s": 34908,
"text": "By default you would want a central administrator to define users in the system, hence ensure the ‘Allow users to sign up’ option is unselected. You can leave the rest as it is for now and click the Save button."
},
{
"code": null,
"e": 35238,
"s": 35120,
"text": "Step 3 − You will be prompted to add your first user. As an example, we are setting up an admin users for the system."
},
{
"code": null,
"e": 35405,
"s": 35238,
"text": "Step 4 − It’s now time to setup your users in the system. Now when you go to Manage Jenkins, and scroll down, you will see a ‘Manage Users’ option. Click this option."
},
{
"code": null,
"e": 35560,
"s": 35405,
"text": "Step 5 − Just like you defined your admin user, start creating other users for the system. As an example, we are just creating another user called ‘user’."
},
{
"code": null,
"e": 35697,
"s": 35560,
"text": "Step 6 − Now it’s time to setup your authorizations, basically who has access to what. Go to Manage Jenkins → Configure Global Security."
},
{
"code": null,
"e": 35764,
"s": 35697,
"text": "Now in the Authorization section, click on ‘Matrix based security’"
},
{
"code": null,
"e": 35918,
"s": 35764,
"text": "Step 7 − If you don’t see the user in the user group list, enter the user name and add it to the list. Then give the appropriate permissions to the user."
},
{
"code": null,
"e": 35994,
"s": 35918,
"text": "Click on the Save button once you have defined the relevant authorizations."
},
{
"code": null,
"e": 36030,
"s": 35994,
"text": "Your Jenkins security is now setup."
},
{
"code": null,
"e": 36123,
"s": 36030,
"text": "Note − For Windows AD authentication, one has to add the Active Directory plugin to Jenkins."
},
{
"code": null,
"e": 36284,
"s": 36123,
"text": "Jenkins has a backup plugin which can used to backup critical configuration settings related to Jenkins. Follow the steps given below to have a backup in place."
},
{
"code": null,
"e": 36357,
"s": 36284,
"text": "Step 1 − Click on Manage Jenkins and choose the ‘Manage Plugins’ option."
},
{
"code": null,
"e": 36490,
"s": 36357,
"text": "Step 2 − In the available tab, search for ‘Backup Plugin’. Click On Install without Restart. Once done, restart the Jenkins instance"
},
{
"code": null,
"e": 36616,
"s": 36490,
"text": "Step 3 − Now when you go to Manage Jenkins, and scroll down you will see ‘Backup Manager’ as an option. Click on this option."
},
{
"code": null,
"e": 36641,
"s": 36616,
"text": "Step 4 − Click on Setup."
},
{
"code": null,
"e": 36842,
"s": 36641,
"text": "Step 5 − Here, the main field to define is the directory for your backup. Ensure it’s on another drive which is different from the drive where your Jenkins instance is setup. Click on the Save button."
},
{
"code": null,
"e": 36949,
"s": 36842,
"text": "Step 6 − Click on the ‘Backup Hudson configuration’ from the Backup manager screen to initiate the backup."
},
{
"code": null,
"e": 37000,
"s": 36949,
"text": "The next screen will show the status of the backup"
},
{
"code": null,
"e": 37098,
"s": 37000,
"text": "To recover from a backup, go to the Backup Manager screen, click on Restore Hudson configuration."
},
{
"code": null,
"e": 37230,
"s": 37098,
"text": "The list of backup’s will be shown, click on the appropriate one to click on Launch Restore to begin the restoration of the backup."
},
{
"code": null,
"e": 37435,
"s": 37230,
"text": "Web tests such as selenium tests can be run on remote slave machines via the master slave and selenium suite plugin installation. The following steps show how to run remote tests using this configuration."
},
{
"code": null,
"e": 37567,
"s": 37435,
"text": "Step 1 − Ensure your master slave configuration is in place. Go to your master Jenkins server. Go to Manage Jenkins → Manage Nodes."
},
{
"code": null,
"e": 37700,
"s": 37567,
"text": "In our node list, the DXBMEM30 label is the slave machine. In this example, both the master and slave machines are windows machines."
},
{
"code": null,
"e": 37760,
"s": 37700,
"text": "Step 2 − Click on configure for the DXBMEM30 slave machine."
},
{
"code": null,
"e": 37845,
"s": 37760,
"text": "Step 3 − Ensure the launch method is put as ‘Launch slave agents via Java Web Start’"
},
{
"code": null,
"e": 38026,
"s": 37845,
"text": "Step 4 − Now go to your slave machine and from there, open a browser instance to your Jenkins master instance. Then go to Manage Jenkins → Manage Nodes. Go to DXBMEM30 and click on"
},
{
"code": null,
"e": 38067,
"s": 38026,
"text": "Step 5 − Click on the DXBMEM30 instance."
},
{
"code": null,
"e": 38169,
"s": 38067,
"text": "Step 6 − Scroll down and you will see the Launch option which is the option to Start ‘Java Web Start’"
},
{
"code": null,
"e": 38276,
"s": 38169,
"text": "Step 7 − You will be presented with a Security Warning. Click on the Acceptance checkbox and click on run."
},
{
"code": null,
"e": 38342,
"s": 38276,
"text": "You will now see a Jenkins Slave window opened and now connected."
},
{
"code": null,
"e": 38501,
"s": 38342,
"text": "Step 8 − Configuring your tests to run on the slave. Here, you have to ensure that the job being created is meant specifically to only run the selenium tests."
},
{
"code": null,
"e": 38658,
"s": 38501,
"text": "In the job configuration, ensure the option ‘Restrict where this project can be run’ is selected and in the Label expression put the name of the slave node."
},
{
"code": null,
"e": 38835,
"s": 38658,
"text": "Step 9 − Ensure the selenium part of your job is configured. You have to ensure that the Sample.html file and the selenium-server.jar file is also present on the slave machine."
},
{
"code": null,
"e": 38976,
"s": 38835,
"text": "Once you have followed all of the above steps, and click on Build, this project will run the Selenium test on the slave machine as expected."
},
{
"code": null,
"e": 39009,
"s": 38976,
"text": "\n 38 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 39037,
"s": 39009,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 39070,
"s": 39037,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 39082,
"s": 39070,
"text": " AR Shankar"
},
{
"code": null,
"e": 39115,
"s": 39082,
"text": "\n 42 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 39135,
"s": 39115,
"text": " Chaitanya Allidona"
},
{
"code": null,
"e": 39170,
"s": 39135,
"text": "\n 37 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 39184,
"s": 39170,
"text": " Spotle Learn"
},
{
"code": null,
"e": 39191,
"s": 39184,
"text": " Print"
},
{
"code": null,
"e": 39202,
"s": 39191,
"text": " Add Notes"
}
] |
Pivot Tables — Data Aggregation Tool in Python | by Tanya Dayanand | Towards Data Science
|
Exploratory data analysis is an important phase of machine learning projects. The wonderful Pandas library is equipped with several useful functions for this purpose. One among them is pivot_table that summarizes a feature’s values in a neat two-dimensional table. The data summarization tool frequently found in data analysis software, offering a ton of flexibility. DataFrame has a pivot_table method (pandas.DataFrame.pivot_table), and additionally, there is a top-level pandas.pivot_table function(any of them can be used as per the convenience, both results in the same output). Most often we end up using pivot_table with the default parameters. This article will help you achieve more by optimal usage of the default parameters.
The pivot_table() method returns a DataFrame which is an Excel-style pivot table. The pivot table aggregates a table of data by one or more keys, arranging the data in a rectangle with some of the group keys along the rows and some along the columns into a two-dimensional table that provides a multidimensional summarization of the data.
pandas.DataFrame.pivot_table()
Let’s look into the basic level usage of this method by applying it on a dataset. Online Shopping Dataset used in the article can be downloaded from Kaggle. To get into the codes directly, an accompanying notebook is published on Kaggle.
www.kaggle.com
Let’s begin with importing the necessary libraries and loading the dataset. This is a requisite step in every data analysis process.
# Importing necessary librariesimport pandas as pdimport numpy as np# Importing and Loading the data into data framemarket_df = pd.read_csv("../input/market.csv")customer_df = pd.read_csv("../input/customer.csv")product_df = pd.read_csv("../input/product.csv")shipping_df = pd.read_csv("../input/shipping.csv")orders_df = pd.read_csv("../input/order.csv")# Merging the dataframes to create a master_dfdf_1 = pd.merge(market_df, customer_df, how='inner', on='Cust_id')df_2 = pd.merge(df_1, product_df, how='inner', on='Prod_id')df_3 = pd.merge(df_2, shipping_df, how='inner', on='Ship_id')master_df = pd.merge(df_3, orders_df, how='inner', on='Ord_id')
master_df.head()
#Identifying Missing Values in Columnmaster_df.isnull().sum()
Thus, the column Product_Base_Margin has null values.
At this point, we barely have any idea of what dataset looks like. So let’s now look into the usage of pivot_table() in multiple different ways to explore the data further.
The index is the column, grouper, array, or list we’d like to group our data by. The simplest pivot table requires a dataframe and an index . The index features will be displayed in the index column in the resultant table. By default, it will average all the numerical columns data when the value and aggfunc parameters are not specified.
I will be using the Customer_Segment column as the index here:
#a single index#Using pandas.DataFrame.pivot_tablemaster_df.pivot_table(index = 'Customer_Segment')#Same as above - results in same output#Using pandas.pivot_tablepd.pivot_table(master_df, index = 'Customer_Segment')
The function returns a pivot table with Customer_Segment as index and averages the numerical columns. We can see that the pivot table is smart enough to start aggregating the data and summarizing it by grouping based on Customer_Segment.
pivot_table can take multiple features as indexes through a list. This increases the level of granularity in the resultant table and we can get more specific with our findings:
#multiple indexesmaster_df.pivot_table(index =['Customer_Segment','Product_Category'])
Here the pivot_table is grouping the Product_Category with Customer_Segment and giving us a summarized table of the combinations. Now we start to get a glimpse of what a pivot table can do for us.
The value parameter is where we tell the function which features to aggregate on. It is an optional field and if we don’t specify this value, then the function will aggregate on all the numerical features of the dataset. In the previous example of indexes, we saw that the aggregation was done for all numerical columns. Since the value parameter was not specified, pivot_table, by default considered all numerical columns.
Below example compares average Sales across Customer_Segment:
#Single valuemaster_df.pivot_table(values = 'Sales', index = 'Customer_Segment')
The Sales column automatically averages the data but we can do a count or a sum as well( by adding a parameter aggfunc and np.sum orcount ).
Alike index parameter, the values parameter can also take multiple features via a list.
#multiple valuemaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Customer_Segment')
The pivot table aggregates data of both the features Order_Quantity and Sales and groups it with Customer_Segment.
As mentioned before, pivot_table uses mean function (numpy.mean) for aggregating or summarizing data by default. But there are other important function or list of functions to consider. aggfunc is an aggregate function that pivot_table applies to our grouped data. aggfunc (optional) accepts a function or list of functions we’d like to use in our group. The aggregation specification can be a string such as 'sum', 'mean', 'count', 'min', 'max', etc or a function that implements an aggregation (e.g. np.sum(), min(), sum(), etc). Now its time to experiment with the aggfunc parameter.
This first example aggregates values by taking the mean:
#Single aggrigate function(mean) and single valuemaster_df.pivot_table(values = 'Sales', index = 'Customer_Segment', aggfunc = 'mean')
The second example aggregates values by taking the sum. It compares the total number of orders across regions.
#Single aggrigate function(sum) and single valuemaster_df.pivot_table(values = 'Order_Quantity', index = 'Region', aggfunc = 'sum')
The following example aggregates by taking the sum across multiple columns.
#Sum aggregate function is applied to both the valuesmaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Product_Category', aggfunc='sum')
Not only we can specify what aggregating function we want, but we can also specify more than one aggregating function. For example, if we are interested in both the sum and count of Sales, we can specify the functions as a list to the argument aggfunc. Let’s try it out.
#multiple Aggregating Function applied to single columnmaster_df.pivot_table(values = 'Sales', index = 'Product_Category', aggfunc=['sum', 'count'])
We can provide a list of aggregate functions to apply to each value too. Below is the example for the same.
#Sum and Mean aggregate function is applied to both the valuesmaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Product_Category', aggfunc=[np.sum, np.mean])
We can use different aggregate functions for different features too. Just provide a dictionary mapping as an input to the aggfunc parameter with the feature name as the key and the corresponding aggregate function as the value.
In the below example, I will be using sum for the Order_Quantity feature and mean for the Sales feature. Also, notice that I’ve omitted the values keyword; when specifying a mapping for aggfunc, this is determined automatically.
#different aggregate applied to different valuesmaster_df.pivot_table(index = 'Product_Category', aggfunc = {'Order_Quantity':sum, 'Sales':'mean'})
When we give multiple aggregating functions, we would get a multi-indexed data frame as output.
The column parameter displays the values horizontally on the top of the resultant table. Most of the time there is confusion with the pivot_table related to the use of columns and values . Bear in mind, columns are optional, they provide a supplementary way to segment the actual values we care about. The aggregation functions are applied to values we list.
If we want to see Profit broken down by the Customer_Segment, the columns parameter allows us to define one or more columns. Here we are comparing the total profit across product categories and customer segments.
#Single column#Grouping by both rows and columnmaster_df.pivot_table(values = 'Profit', index = 'Product_Category', columns = 'Customer_Segment', aggfunc = 'sum')
Using multiple features as indexes is fine, but using some features as columns will help us to quickly understand the relationship between them. Also, the resultant table can always be better viewed by incorporating the columns parameter of the pivot_table.
#multiple columnsmaster_df.pivot_table(values = 'Profit', index = 'Customer_Segment', columns = ['Product_Category','Ship_Mode'], aggfunc = 'count')
Both columns and the index parameters are optional, but using them effectively will help us to intuitively understand the relationship between the features.
At times it’s useful to compute totals for each grouping. Now, if we want to see some totals of the data, margins=True does that for us. margins is type boolean that adds all rows and columns (e.g. for subtotal / grand totals) and defaults to ‘False’.
#Marginmaster_df.pivot_table(values = ‘Profit’, index = ‘Product_Category’, columns = ‘Customer_Segment’, aggfunc = ‘sum’, margins=True)
The margin label can be specified with the margins_name keyword, which defaults to "All".margins_name is of type string and accepts the name of the row/column that will contain the totals when margins equal True.
#margins_namemaster_df.pivot_table(values = 'Profit', index = 'Product_Category', columns = 'Customer_Segment', aggfunc = 'sum', margins=True, margins_name ='TOTAL')
These two parameters are both optional and often useful to improve the display.
The NaN’s are a bit distracting. pivot_table helps us to deal with it through the parameters dropna and fill_value. Two of these options, fill_value and dropna, have to do with missing data and are fairly straightforward.
dropna is type boolean, and allows us to drop the null values in the grouped table whose entries are all NaN. It defaults to True.
fill_value is type scalar, and can be used to replace the NaN values in the table with the values that we provide. It defaults to None.
#Displaying NaN values in the table#These can be imputed using fill_valuemaster_df.pivot_table(values = 'Product_Base_Margin', index = 'Customer_Name', columns = 'Customer_Segment', aggfunc = 'mean')
I will be replacing the NaN values with the mean value from the Product_Base_Margin column:
#imputing with mean using fill_valuemaster_df.pivot_table(values = 'Product_Base_Margin', index = 'Customer_Name', columns = 'Customer_Segment', aggfunc = 'mean', fill_value=np.mean(master_df['Product_Base_Margin']))
We don’t have any columns where all entries are NaN, but it’s worth knowing that if we did pivot_table would drop them by default according to dropna definition.
Thus, we can see that pivot_table() is a handy tool, and we can do some interesting analysis with this single line of code. As you build up the pivot table, I think it’s easiest to take it one step at a time. Add items and check each step to verify if you are getting the results you expect and see what presentation makes the most sense for your needs. As soon as you start playing with the data and slowly add the items, you can get a feel for how it works.
We’ve covered the powerful parameters of pivot_table , so you can get a lot out of it if you go experiment using these methods on your project.
|
[
{
"code": null,
"e": 782,
"s": 46,
"text": "Exploratory data analysis is an important phase of machine learning projects. The wonderful Pandas library is equipped with several useful functions for this purpose. One among them is pivot_table that summarizes a feature’s values in a neat two-dimensional table. The data summarization tool frequently found in data analysis software, offering a ton of flexibility. DataFrame has a pivot_table method (pandas.DataFrame.pivot_table), and additionally, there is a top-level pandas.pivot_table function(any of them can be used as per the convenience, both results in the same output). Most often we end up using pivot_table with the default parameters. This article will help you achieve more by optimal usage of the default parameters."
},
{
"code": null,
"e": 1121,
"s": 782,
"text": "The pivot_table() method returns a DataFrame which is an Excel-style pivot table. The pivot table aggregates a table of data by one or more keys, arranging the data in a rectangle with some of the group keys along the rows and some along the columns into a two-dimensional table that provides a multidimensional summarization of the data."
},
{
"code": null,
"e": 1152,
"s": 1121,
"text": "pandas.DataFrame.pivot_table()"
},
{
"code": null,
"e": 1390,
"s": 1152,
"text": "Let’s look into the basic level usage of this method by applying it on a dataset. Online Shopping Dataset used in the article can be downloaded from Kaggle. To get into the codes directly, an accompanying notebook is published on Kaggle."
},
{
"code": null,
"e": 1405,
"s": 1390,
"text": "www.kaggle.com"
},
{
"code": null,
"e": 1538,
"s": 1405,
"text": "Let’s begin with importing the necessary libraries and loading the dataset. This is a requisite step in every data analysis process."
},
{
"code": null,
"e": 2190,
"s": 1538,
"text": "# Importing necessary librariesimport pandas as pdimport numpy as np# Importing and Loading the data into data framemarket_df = pd.read_csv(\"../input/market.csv\")customer_df = pd.read_csv(\"../input/customer.csv\")product_df = pd.read_csv(\"../input/product.csv\")shipping_df = pd.read_csv(\"../input/shipping.csv\")orders_df = pd.read_csv(\"../input/order.csv\")# Merging the dataframes to create a master_dfdf_1 = pd.merge(market_df, customer_df, how='inner', on='Cust_id')df_2 = pd.merge(df_1, product_df, how='inner', on='Prod_id')df_3 = pd.merge(df_2, shipping_df, how='inner', on='Ship_id')master_df = pd.merge(df_3, orders_df, how='inner', on='Ord_id')"
},
{
"code": null,
"e": 2207,
"s": 2190,
"text": "master_df.head()"
},
{
"code": null,
"e": 2269,
"s": 2207,
"text": "#Identifying Missing Values in Columnmaster_df.isnull().sum()"
},
{
"code": null,
"e": 2323,
"s": 2269,
"text": "Thus, the column Product_Base_Margin has null values."
},
{
"code": null,
"e": 2496,
"s": 2323,
"text": "At this point, we barely have any idea of what dataset looks like. So let’s now look into the usage of pivot_table() in multiple different ways to explore the data further."
},
{
"code": null,
"e": 2835,
"s": 2496,
"text": "The index is the column, grouper, array, or list we’d like to group our data by. The simplest pivot table requires a dataframe and an index . The index features will be displayed in the index column in the resultant table. By default, it will average all the numerical columns data when the value and aggfunc parameters are not specified."
},
{
"code": null,
"e": 2898,
"s": 2835,
"text": "I will be using the Customer_Segment column as the index here:"
},
{
"code": null,
"e": 3115,
"s": 2898,
"text": "#a single index#Using pandas.DataFrame.pivot_tablemaster_df.pivot_table(index = 'Customer_Segment')#Same as above - results in same output#Using pandas.pivot_tablepd.pivot_table(master_df, index = 'Customer_Segment')"
},
{
"code": null,
"e": 3353,
"s": 3115,
"text": "The function returns a pivot table with Customer_Segment as index and averages the numerical columns. We can see that the pivot table is smart enough to start aggregating the data and summarizing it by grouping based on Customer_Segment."
},
{
"code": null,
"e": 3530,
"s": 3353,
"text": "pivot_table can take multiple features as indexes through a list. This increases the level of granularity in the resultant table and we can get more specific with our findings:"
},
{
"code": null,
"e": 3617,
"s": 3530,
"text": "#multiple indexesmaster_df.pivot_table(index =['Customer_Segment','Product_Category'])"
},
{
"code": null,
"e": 3814,
"s": 3617,
"text": "Here the pivot_table is grouping the Product_Category with Customer_Segment and giving us a summarized table of the combinations. Now we start to get a glimpse of what a pivot table can do for us."
},
{
"code": null,
"e": 4238,
"s": 3814,
"text": "The value parameter is where we tell the function which features to aggregate on. It is an optional field and if we don’t specify this value, then the function will aggregate on all the numerical features of the dataset. In the previous example of indexes, we saw that the aggregation was done for all numerical columns. Since the value parameter was not specified, pivot_table, by default considered all numerical columns."
},
{
"code": null,
"e": 4300,
"s": 4238,
"text": "Below example compares average Sales across Customer_Segment:"
},
{
"code": null,
"e": 4381,
"s": 4300,
"text": "#Single valuemaster_df.pivot_table(values = 'Sales', index = 'Customer_Segment')"
},
{
"code": null,
"e": 4522,
"s": 4381,
"text": "The Sales column automatically averages the data but we can do a count or a sum as well( by adding a parameter aggfunc and np.sum orcount )."
},
{
"code": null,
"e": 4610,
"s": 4522,
"text": "Alike index parameter, the values parameter can also take multiple features via a list."
},
{
"code": null,
"e": 4712,
"s": 4610,
"text": "#multiple valuemaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Customer_Segment')"
},
{
"code": null,
"e": 4827,
"s": 4712,
"text": "The pivot table aggregates data of both the features Order_Quantity and Sales and groups it with Customer_Segment."
},
{
"code": null,
"e": 5414,
"s": 4827,
"text": "As mentioned before, pivot_table uses mean function (numpy.mean) for aggregating or summarizing data by default. But there are other important function or list of functions to consider. aggfunc is an aggregate function that pivot_table applies to our grouped data. aggfunc (optional) accepts a function or list of functions we’d like to use in our group. The aggregation specification can be a string such as 'sum', 'mean', 'count', 'min', 'max', etc or a function that implements an aggregation (e.g. np.sum(), min(), sum(), etc). Now its time to experiment with the aggfunc parameter."
},
{
"code": null,
"e": 5471,
"s": 5414,
"text": "This first example aggregates values by taking the mean:"
},
{
"code": null,
"e": 5606,
"s": 5471,
"text": "#Single aggrigate function(mean) and single valuemaster_df.pivot_table(values = 'Sales', index = 'Customer_Segment', aggfunc = 'mean')"
},
{
"code": null,
"e": 5717,
"s": 5606,
"text": "The second example aggregates values by taking the sum. It compares the total number of orders across regions."
},
{
"code": null,
"e": 5849,
"s": 5717,
"text": "#Single aggrigate function(sum) and single valuemaster_df.pivot_table(values = 'Order_Quantity', index = 'Region', aggfunc = 'sum')"
},
{
"code": null,
"e": 5925,
"s": 5849,
"text": "The following example aggregates by taking the sum across multiple columns."
},
{
"code": null,
"e": 6080,
"s": 5925,
"text": "#Sum aggregate function is applied to both the valuesmaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Product_Category', aggfunc='sum')"
},
{
"code": null,
"e": 6351,
"s": 6080,
"text": "Not only we can specify what aggregating function we want, but we can also specify more than one aggregating function. For example, if we are interested in both the sum and count of Sales, we can specify the functions as a list to the argument aggfunc. Let’s try it out."
},
{
"code": null,
"e": 6500,
"s": 6351,
"text": "#multiple Aggregating Function applied to single columnmaster_df.pivot_table(values = 'Sales', index = 'Product_Category', aggfunc=['sum', 'count'])"
},
{
"code": null,
"e": 6608,
"s": 6500,
"text": "We can provide a list of aggregate functions to apply to each value too. Below is the example for the same."
},
{
"code": null,
"e": 6784,
"s": 6608,
"text": "#Sum and Mean aggregate function is applied to both the valuesmaster_df.pivot_table(values = ['Order_Quantity','Sales'], index = 'Product_Category', aggfunc=[np.sum, np.mean])"
},
{
"code": null,
"e": 7012,
"s": 6784,
"text": "We can use different aggregate functions for different features too. Just provide a dictionary mapping as an input to the aggfunc parameter with the feature name as the key and the corresponding aggregate function as the value."
},
{
"code": null,
"e": 7241,
"s": 7012,
"text": "In the below example, I will be using sum for the Order_Quantity feature and mean for the Sales feature. Also, notice that I’ve omitted the values keyword; when specifying a mapping for aggfunc, this is determined automatically."
},
{
"code": null,
"e": 7389,
"s": 7241,
"text": "#different aggregate applied to different valuesmaster_df.pivot_table(index = 'Product_Category', aggfunc = {'Order_Quantity':sum, 'Sales':'mean'})"
},
{
"code": null,
"e": 7485,
"s": 7389,
"text": "When we give multiple aggregating functions, we would get a multi-indexed data frame as output."
},
{
"code": null,
"e": 7844,
"s": 7485,
"text": "The column parameter displays the values horizontally on the top of the resultant table. Most of the time there is confusion with the pivot_table related to the use of columns and values . Bear in mind, columns are optional, they provide a supplementary way to segment the actual values we care about. The aggregation functions are applied to values we list."
},
{
"code": null,
"e": 8057,
"s": 7844,
"text": "If we want to see Profit broken down by the Customer_Segment, the columns parameter allows us to define one or more columns. Here we are comparing the total profit across product categories and customer segments."
},
{
"code": null,
"e": 8286,
"s": 8057,
"text": "#Single column#Grouping by both rows and columnmaster_df.pivot_table(values = 'Profit', index = 'Product_Category', columns = 'Customer_Segment', aggfunc = 'sum')"
},
{
"code": null,
"e": 8544,
"s": 8286,
"text": "Using multiple features as indexes is fine, but using some features as columns will help us to quickly understand the relationship between them. Also, the resultant table can always be better viewed by incorporating the columns parameter of the pivot_table."
},
{
"code": null,
"e": 8759,
"s": 8544,
"text": "#multiple columnsmaster_df.pivot_table(values = 'Profit', index = 'Customer_Segment', columns = ['Product_Category','Ship_Mode'], aggfunc = 'count')"
},
{
"code": null,
"e": 8916,
"s": 8759,
"text": "Both columns and the index parameters are optional, but using them effectively will help us to intuitively understand the relationship between the features."
},
{
"code": null,
"e": 9168,
"s": 8916,
"text": "At times it’s useful to compute totals for each grouping. Now, if we want to see some totals of the data, margins=True does that for us. margins is type boolean that adds all rows and columns (e.g. for subtotal / grand totals) and defaults to ‘False’."
},
{
"code": null,
"e": 9308,
"s": 9168,
"text": "#Marginmaster_df.pivot_table(values = ‘Profit’, index = ‘Product_Category’, columns = ‘Customer_Segment’, aggfunc = ‘sum’, margins=True)"
},
{
"code": null,
"e": 9521,
"s": 9308,
"text": "The margin label can be specified with the margins_name keyword, which defaults to \"All\".margins_name is of type string and accepts the name of the row/column that will contain the totals when margins equal True."
},
{
"code": null,
"e": 9796,
"s": 9521,
"text": "#margins_namemaster_df.pivot_table(values = 'Profit', index = 'Product_Category', columns = 'Customer_Segment', aggfunc = 'sum', margins=True, margins_name ='TOTAL')"
},
{
"code": null,
"e": 9876,
"s": 9796,
"text": "These two parameters are both optional and often useful to improve the display."
},
{
"code": null,
"e": 10098,
"s": 9876,
"text": "The NaN’s are a bit distracting. pivot_table helps us to deal with it through the parameters dropna and fill_value. Two of these options, fill_value and dropna, have to do with missing data and are fairly straightforward."
},
{
"code": null,
"e": 10229,
"s": 10098,
"text": "dropna is type boolean, and allows us to drop the null values in the grouped table whose entries are all NaN. It defaults to True."
},
{
"code": null,
"e": 10365,
"s": 10229,
"text": "fill_value is type scalar, and can be used to replace the NaN values in the table with the values that we provide. It defaults to None."
},
{
"code": null,
"e": 10630,
"s": 10365,
"text": "#Displaying NaN values in the table#These can be imputed using fill_valuemaster_df.pivot_table(values = 'Product_Base_Margin', index = 'Customer_Name', columns = 'Customer_Segment', aggfunc = 'mean')"
},
{
"code": null,
"e": 10722,
"s": 10630,
"text": "I will be replacing the NaN values with the mean value from the Product_Base_Margin column:"
},
{
"code": null,
"e": 11004,
"s": 10722,
"text": "#imputing with mean using fill_valuemaster_df.pivot_table(values = 'Product_Base_Margin', index = 'Customer_Name', columns = 'Customer_Segment', aggfunc = 'mean', fill_value=np.mean(master_df['Product_Base_Margin']))"
},
{
"code": null,
"e": 11166,
"s": 11004,
"text": "We don’t have any columns where all entries are NaN, but it’s worth knowing that if we did pivot_table would drop them by default according to dropna definition."
},
{
"code": null,
"e": 11626,
"s": 11166,
"text": "Thus, we can see that pivot_table() is a handy tool, and we can do some interesting analysis with this single line of code. As you build up the pivot table, I think it’s easiest to take it one step at a time. Add items and check each step to verify if you are getting the results you expect and see what presentation makes the most sense for your needs. As soon as you start playing with the data and slowly add the items, you can get a feel for how it works."
}
] |
Create, Append and Modify List in R - GeeksforGeeks
|
30 Jun, 2021
In R Programming Language, the list is a one dimensional data structure which can hold multiple data type elements. In this article, we are going to create a list and append data into the list and modify the list elements.
List can be created by using list() function.
Syntax:
list(value1,value2,.............,valuen)
where values are the inputs to the list.
Example :
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("kakumanu","hyd","hyd","hyd") # pass these vectors as inputs to the list# address vectorstudent=list(names,marks,address)print(student)
Output:
Appending to a list means adding a value to the last of an already existing list. We are going to append two lists by using append() function
Syntax:
append(list1,list2)
Example:
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("kakumanu","hyd","hyd","hyd") # college valuescollege=c("vignan","vignan","vignan","vignan") # pass these vectors as inputs to the liststudent1=list(student1_names=names,student1_marks=marks, student1_address=address,student1_college=college) # vector with namesnames=c("ravi","devi","siree","priyank") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("hyd","hyd","hyd","hyd") # college valuescollege=c("vvit","vvit","vvit","vvit") # pass these vectors as inputs to the list# address vectorstudent2=list(student2_names=names,student2_marks=marks, student2_address=address,student2_college=college) # append list 1 and list 2print(append(student1,student2))
Output:
We can also append single column in one dataframe to another using $ operator.
Syntax:
append(dataframe1$columnname,dataframe2$columnname)
Program:
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("kakumanu","hyd","hyd","hyd") # college valuescollege=c("vignan","vignan","vignan","vignan") # pass these vectors as inputs to the liststudent1=list(student1_names=names,student1_marks=marks, student1_address=address,student1_college=college) # vector with namesnames=c("ravi","devi","siree","priyank") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("hyd","hyd","hyd","hyd") # college valuescollege=c("vvit","vvit","vvit","vvit") # pass these vectors as inputs to the list# address vectorstudent2=list(student2_names=names,student2_marks=marks, student2_address=address,student2_college=college) # append list 1 - student marks and list 2 - student marksprint(append(student1$student1_marks,student2$student2_marks))
Output:
[1] 78 90 100 100 78 90 100 100
Modifying a list means changing the initial representation of the list that can include operations like changing or updating values and deleting. We can modify the list elements using index operator.
index operator:
[[]]
Syntax:
list_name[[n]]=”new_element_name
where n is the index value
Example:
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("kakumanu","hyd","hyd","hyd") # college valuescollege=c("vignan","vignan","vignan","vignan") # pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # display 1 st row 2 nd elementprint(paste("1 st one - 2 nd element is : ",student1[[1]][2])) # modify pinky to gajjistudent1[[1]][2]="gajji"print(paste("Modified 1 st one - 2 nd element is : ",student1[[1]][2]))
Output:
[1] "1 st one - 2 nd element is : pinkey"
[1] "Modified 1 st one - 2 nd element is : gajji"
We can also modify whole index at a time,
Example:
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu")# vector with marksmarks=c(78,90,100,100)# address vectoraddress=c("kakumanu","hyd","hyd","hyd")# college valuescollege=c("vignan","vignan","vignan","vignan")# pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # display 2 nd indexprint(paste("2 nd index elements are : ",student1[[2]]))# modify the whole content of 2 nd indexstudent1[[2]]=c(45,56,54,45) print(paste("Modified 2 nd index elements are : ",student1[[2]]))
Output:
Modification includes deletion also. We can delete particular element from the list by assigning list index with NULL operator.
Syntax:
list_name[[index_number]]=NULL
Example:
R
# vector with namesnames=c("bobby","pinkey","rohith","gnanu") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c("kakumanu","hyd","hyd","hyd") # college valuescollege=c("vignan","vignan","vignan","vignan") # pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # deleting first item IE names vectorstudent1[[1]]=NULL # display listprint(student1)
Output:
sweetyty
Picked
R-List
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?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 25074,
"s": 24851,
"text": "In R Programming Language, the list is a one dimensional data structure which can hold multiple data type elements. In this article, we are going to create a list and append data into the list and modify the list elements."
},
{
"code": null,
"e": 25120,
"s": 25074,
"text": "List can be created by using list() function."
},
{
"code": null,
"e": 25128,
"s": 25120,
"text": "Syntax:"
},
{
"code": null,
"e": 25169,
"s": 25128,
"text": "list(value1,value2,.............,valuen)"
},
{
"code": null,
"e": 25210,
"s": 25169,
"text": "where values are the inputs to the list."
},
{
"code": null,
"e": 25220,
"s": 25210,
"text": "Example :"
},
{
"code": null,
"e": 25222,
"s": 25220,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\") # pass these vectors as inputs to the list# address vectorstudent=list(names,marks,address)print(student)",
"e": 25488,
"s": 25222,
"text": null
},
{
"code": null,
"e": 25496,
"s": 25488,
"text": "Output:"
},
{
"code": null,
"e": 25638,
"s": 25496,
"text": "Appending to a list means adding a value to the last of an already existing list. We are going to append two lists by using append() function"
},
{
"code": null,
"e": 25646,
"s": 25638,
"text": "Syntax:"
},
{
"code": null,
"e": 25666,
"s": 25646,
"text": "append(list1,list2)"
},
{
"code": null,
"e": 25675,
"s": 25666,
"text": "Example:"
},
{
"code": null,
"e": 25677,
"s": 25675,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vignan\",\"vignan\",\"vignan\",\"vignan\") # pass these vectors as inputs to the liststudent1=list(student1_names=names,student1_marks=marks, student1_address=address,student1_college=college) # vector with namesnames=c(\"ravi\",\"devi\",\"siree\",\"priyank\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"hyd\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vvit\",\"vvit\",\"vvit\",\"vvit\") # pass these vectors as inputs to the list# address vectorstudent2=list(student2_names=names,student2_marks=marks, student2_address=address,student2_college=college) # append list 1 and list 2print(append(student1,student2))",
"e": 26509,
"s": 25677,
"text": null
},
{
"code": null,
"e": 26517,
"s": 26509,
"text": "Output:"
},
{
"code": null,
"e": 26596,
"s": 26517,
"text": "We can also append single column in one dataframe to another using $ operator."
},
{
"code": null,
"e": 26604,
"s": 26596,
"text": "Syntax:"
},
{
"code": null,
"e": 26656,
"s": 26604,
"text": "append(dataframe1$columnname,dataframe2$columnname)"
},
{
"code": null,
"e": 26665,
"s": 26656,
"text": "Program:"
},
{
"code": null,
"e": 26667,
"s": 26665,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vignan\",\"vignan\",\"vignan\",\"vignan\") # pass these vectors as inputs to the liststudent1=list(student1_names=names,student1_marks=marks, student1_address=address,student1_college=college) # vector with namesnames=c(\"ravi\",\"devi\",\"siree\",\"priyank\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"hyd\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vvit\",\"vvit\",\"vvit\",\"vvit\") # pass these vectors as inputs to the list# address vectorstudent2=list(student2_names=names,student2_marks=marks, student2_address=address,student2_college=college) # append list 1 - student marks and list 2 - student marksprint(append(student1$student1_marks,student2$student2_marks))",
"e": 27561,
"s": 26667,
"text": null
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "Output:"
},
{
"code": null,
"e": 27605,
"s": 27569,
"text": "[1] 78 90 100 100 78 90 100 100"
},
{
"code": null,
"e": 27805,
"s": 27605,
"text": "Modifying a list means changing the initial representation of the list that can include operations like changing or updating values and deleting. We can modify the list elements using index operator."
},
{
"code": null,
"e": 27821,
"s": 27805,
"text": "index operator:"
},
{
"code": null,
"e": 27827,
"s": 27821,
"text": " [[]]"
},
{
"code": null,
"e": 27835,
"s": 27827,
"text": "Syntax:"
},
{
"code": null,
"e": 27868,
"s": 27835,
"text": "list_name[[n]]=”new_element_name"
},
{
"code": null,
"e": 27895,
"s": 27868,
"text": "where n is the index value"
},
{
"code": null,
"e": 27904,
"s": 27895,
"text": "Example:"
},
{
"code": null,
"e": 27906,
"s": 27904,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vignan\",\"vignan\",\"vignan\",\"vignan\") # pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # display 1 st row 2 nd elementprint(paste(\"1 st one - 2 nd element is : \",student1[[1]][2])) # modify pinky to gajjistudent1[[1]][2]=\"gajji\"print(paste(\"Modified 1 st one - 2 nd element is : \",student1[[1]][2]))",
"e": 28427,
"s": 27906,
"text": null
},
{
"code": null,
"e": 28435,
"s": 28427,
"text": "Output:"
},
{
"code": null,
"e": 28529,
"s": 28435,
"text": "[1] \"1 st one - 2 nd element is : pinkey\"\n[1] \"Modified 1 st one - 2 nd element is : gajji\""
},
{
"code": null,
"e": 28571,
"s": 28529,
"text": "We can also modify whole index at a time,"
},
{
"code": null,
"e": 28580,
"s": 28571,
"text": "Example:"
},
{
"code": null,
"e": 28582,
"s": 28580,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\")# vector with marksmarks=c(78,90,100,100)# address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\")# college valuescollege=c(\"vignan\",\"vignan\",\"vignan\",\"vignan\")# pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # display 2 nd indexprint(paste(\"2 nd index elements are : \",student1[[2]]))# modify the whole content of 2 nd indexstudent1[[2]]=c(45,56,54,45) print(paste(\"Modified 2 nd index elements are : \",student1[[2]]))",
"e": 29097,
"s": 28582,
"text": null
},
{
"code": null,
"e": 29105,
"s": 29097,
"text": "Output:"
},
{
"code": null,
"e": 29233,
"s": 29105,
"text": "Modification includes deletion also. We can delete particular element from the list by assigning list index with NULL operator."
},
{
"code": null,
"e": 29241,
"s": 29233,
"text": "Syntax:"
},
{
"code": null,
"e": 29272,
"s": 29241,
"text": "list_name[[index_number]]=NULL"
},
{
"code": null,
"e": 29281,
"s": 29272,
"text": "Example:"
},
{
"code": null,
"e": 29283,
"s": 29281,
"text": "R"
},
{
"code": "# vector with namesnames=c(\"bobby\",\"pinkey\",\"rohith\",\"gnanu\") # vector with marksmarks=c(78,90,100,100) # address vectoraddress=c(\"kakumanu\",\"hyd\",\"hyd\",\"hyd\") # college valuescollege=c(\"vignan\",\"vignan\",\"vignan\",\"vignan\") # pass these vectors as inputs to the liststudent1=list(names,marks,address,college) # deleting first item IE names vectorstudent1[[1]]=NULL # display listprint(student1)",
"e": 29677,
"s": 29283,
"text": null
},
{
"code": null,
"e": 29685,
"s": 29677,
"text": "Output:"
},
{
"code": null,
"e": 29694,
"s": 29685,
"text": "sweetyty"
},
{
"code": null,
"e": 29701,
"s": 29694,
"text": "Picked"
},
{
"code": null,
"e": 29708,
"s": 29701,
"text": "R-List"
},
{
"code": null,
"e": 29719,
"s": 29708,
"text": "R Language"
},
{
"code": null,
"e": 29817,
"s": 29719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29826,
"s": 29817,
"text": "Comments"
},
{
"code": null,
"e": 29839,
"s": 29826,
"text": "Old Comments"
},
{
"code": null,
"e": 29891,
"s": 29839,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29929,
"s": 29891,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29964,
"s": 29929,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30022,
"s": 29964,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30071,
"s": 30022,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30114,
"s": 30071,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30164,
"s": 30114,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30181,
"s": 30164,
"text": "R - if statement"
},
{
"code": null,
"e": 30218,
"s": 30181,
"text": "How to import an Excel File into R ?"
}
] |
Selection Sort | Practice | GeeksforGeeks
|
Given an unsorted array of size N, use selection sort to sort arr[] in increasing order.
Example 1:
Input:
N = 5
arr[] = {4, 1, 3, 9, 7}
Output:
1 3 4 7 9
Explanation:
Maintain sorted (in bold) and unsorted subarrays.
Select 1. Array becomes 1 4 3 9 7.
Select 3. Array becomes 1 3 4 9 7.
Select 4. Array becomes 1 3 4 9 7.
Select 7. Array becomes 1 3 4 7 9.
Select 9. Array becomes 1 3 4 7 9.
Example 2:
Input:
N = 10
arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}
Output:
1 2 3 4 5 6 7 8 9 10
Your Task:
You dont need to read input or print anything. Complete the functions select() and selectionSort() ,where select() takes arr[] and starting point of unsorted array i as input parameters and returns the selected element for each iteration in selection sort, and selectionSort() takes the array and it's size and sorts the array.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10^3
0
debasishtewary51 day ago
static int select(int arr[], int i){ // code here such that selectionSort() sorts arr[] int in=0;int min=arr[i];for(int j=i+1;j<arr.length;j++) { if(arr[j]<min) { min=arr[j]; in=j; } }return in;}void selectionSort(int arr[], int n){ //code here for(int i=0;i<n;i++){ int j=Solution.select(arr,i); if(j!=0){ int a=arr[j]; arr[j]=arr[i]; arr[i]=a; } }}
0
angelettamorgan14 days ago
Eeee
0
sangrambachu4 days ago
class Solution
{
select(arr,i){
// code here such that selectionSort() sorts arr[]
}
//Function to sort the array using selection sort algorithm.
selectionSort(arr,n){
//code here
for(let i=0; i<n-1; i++) {
let minIndex = i;
for(let j=i+1; j<n; j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if(minIndex != i) {
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
0
koulikmaity1 week ago
int select(int arr[], int i) { // code here such that selectionSort() sorts arr[] } void selectionSort(int arr[], int n) { for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(arr[j] < arr[i] ) { swap(arr[i], arr[j]); } } } }
0
shashwatchaurasia833 weeks ago
int select(int arr[], int i){ // leave as it is }
void selectionSort(int arr[], int n){ for(int i=0;i<n-2;i++) { int Min_Idx=i; for(int j=i+1;j<n-1;j++) { if(arr[j]<arr[Min_Idx]) Min_Idx=j; } swap(&arr[Min_Idx],&arr[i]); }}
0
mitradiptamoy4 weeks ago
void selectionSort(int arr[], int n) { //code here for(int i=0;i<=n-2;i++) { int min_ind=i; for(int j=i+1;j<=n-1;j++) { if(arr[j]<arr[min_ind]) { min_ind=j; } } swap(arr[min_ind],arr[i]); } }
0
ramasaimohanakhil1 month ago
//mohanakhildenduluri
class Solution{int select(int a[],int i){ int min=a[i],index=0; boolean flag=false; for(int j=i+1;j<a.length;j++) { if(a[j]<min) { min=a[j]; index=j; flag=true; } } if(flag) { return index; } return -1; // code here such that selectionSort() sorts arr[]}void selectionSort(int a[], int n){ //code here int temp=0; for(int i=0;i<n;i++) { int index=select(a,i); if(index!=-1) { temp=a[i]; a[i]=a[index]; a[index]=temp; } }}}
0
codewithshoaib191 month ago
// int select(int arr[], int i)// {// // code here such that selectionSort() sorts arr[]// }void selectionSort(int arr[], int n){ //code here for(int i=0;i<n;i++){ int last=n-i-1; int max=getMax(arr,0,last); swap(arr,max,last); }} public static void swap(int[] arr, int s, int e) { int temp = arr[s]; arr[s] = arr[e]; arr[e] = temp; }
public static int getMax(int[] arr, int s, int e) { int max = s; for (int i = s; i <= e; i++) { if (arr[i] > arr[max]) { max = i; } } return max; }
0
yash7raut1 month ago
class Solution: def select(self, arr, i): # code here pass def selectionSort(self, arr,n): #code here n = len(arr) for i in range(n-1): min_idx = i for j in range(min_idx+1,n): if(arr[j]<arr[min_idx]): min_idx = j if(i!=min_idx): arr[i],arr[min_idx] = arr[min_idx],arr[i]
+1
vishesh__jhaPremium1 month ago
Time Complexity: 0.0 /2.9
C++
int select(int arr[], int i) { //You can AVoid this Function } void selectionSort(int arr[], int n) { for(int i=0;i<n-1;i++) { int Min_Idx=i; for(int j=i+1;j<n;j++) { if(arr[j]<arr[Min_Idx]) Min_Idx=j; } swap(&arr[Min_Idx],&arr[i]); } }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 327,
"s": 238,
"text": "Given an unsorted array of size N, use selection sort to sort arr[] in increasing order."
},
{
"code": null,
"e": 339,
"s": 327,
"text": "\nExample 1:"
},
{
"code": null,
"e": 632,
"s": 339,
"text": "Input:\nN = 5\narr[] = {4, 1, 3, 9, 7}\nOutput:\n1 3 4 7 9\nExplanation:\nMaintain sorted (in bold) and unsorted subarrays.\nSelect 1. Array becomes 1 4 3 9 7.\nSelect 3. Array becomes 1 3 4 9 7.\nSelect 4. Array becomes 1 3 4 9 7.\nSelect 7. Array becomes 1 3 4 7 9.\nSelect 9. Array becomes 1 3 4 7 9."
},
{
"code": null,
"e": 643,
"s": 632,
"text": "Example 2:"
},
{
"code": null,
"e": 726,
"s": 643,
"text": "Input:\nN = 10\narr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}\nOutput:\n1 2 3 4 5 6 7 8 9 10"
},
{
"code": null,
"e": 1068,
"s": 726,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the functions select() and selectionSort() ,where select() takes arr[] and starting point of unsorted array i as input parameters and returns the selected element for each iteration in selection sort, and selectionSort() takes the array and it's size and sorts the array."
},
{
"code": null,
"e": 1132,
"s": 1068,
"text": "\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1159,
"s": 1132,
"text": "\nConstraints:\n1 ≤ N ≤ 10^3"
},
{
"code": null,
"e": 1161,
"s": 1159,
"text": "0"
},
{
"code": null,
"e": 1186,
"s": 1161,
"text": "debasishtewary51 day ago"
},
{
"code": null,
"e": 1593,
"s": 1186,
"text": "static int select(int arr[], int i){ // code here such that selectionSort() sorts arr[] int in=0;int min=arr[i];for(int j=i+1;j<arr.length;j++) { if(arr[j]<min) { min=arr[j]; in=j; } }return in;}void selectionSort(int arr[], int n){ //code here for(int i=0;i<n;i++){ int j=Solution.select(arr,i); if(j!=0){ int a=arr[j]; arr[j]=arr[i]; arr[i]=a; } }}"
},
{
"code": null,
"e": 1595,
"s": 1593,
"text": "0"
},
{
"code": null,
"e": 1622,
"s": 1595,
"text": "angelettamorgan14 days ago"
},
{
"code": null,
"e": 1627,
"s": 1622,
"text": "Eeee"
},
{
"code": null,
"e": 1629,
"s": 1627,
"text": "0"
},
{
"code": null,
"e": 1652,
"s": 1629,
"text": "sangrambachu4 days ago"
},
{
"code": null,
"e": 2188,
"s": 1652,
"text": "class Solution\n{\n select(arr,i){\n // code here such that selectionSort() sorts arr[]\n }\n\n //Function to sort the array using selection sort algorithm.\n selectionSort(arr,n){\n //code here\n for(let i=0; i<n-1; i++) {\n let minIndex = i;\n \n for(let j=i+1; j<n; j++) {\n if(arr[j] < arr[minIndex]) {\n minIndex = j;\n }\n }\n \n if(minIndex != i) {\n let temp = arr[i];\n arr[i] = arr[minIndex];\n arr[minIndex] = temp;\n }\n }\n }"
},
{
"code": null,
"e": 2190,
"s": 2188,
"text": "0"
},
{
"code": null,
"e": 2212,
"s": 2190,
"text": "koulikmaity1 week ago"
},
{
"code": null,
"e": 2560,
"s": 2212,
"text": "int select(int arr[], int i) { // code here such that selectionSort() sorts arr[] } void selectionSort(int arr[], int n) { for(int i=0; i<n-1; i++) { for(int j=i+1; j<n; j++) { if(arr[j] < arr[i] ) { swap(arr[i], arr[j]); } } } }"
},
{
"code": null,
"e": 2562,
"s": 2560,
"text": "0"
},
{
"code": null,
"e": 2593,
"s": 2562,
"text": "shashwatchaurasia833 weeks ago"
},
{
"code": null,
"e": 2645,
"s": 2593,
"text": "int select(int arr[], int i){ // leave as it is }"
},
{
"code": null,
"e": 2915,
"s": 2645,
"text": "void selectionSort(int arr[], int n){ for(int i=0;i<n-2;i++) { int Min_Idx=i; for(int j=i+1;j<n-1;j++) { if(arr[j]<arr[Min_Idx]) Min_Idx=j; } swap(&arr[Min_Idx],&arr[i]); }}"
},
{
"code": null,
"e": 2917,
"s": 2915,
"text": "0"
},
{
"code": null,
"e": 2942,
"s": 2917,
"text": "mitradiptamoy4 weeks ago"
},
{
"code": null,
"e": 3259,
"s": 2942,
"text": "void selectionSort(int arr[], int n) { //code here for(int i=0;i<=n-2;i++) { int min_ind=i; for(int j=i+1;j<=n-1;j++) { if(arr[j]<arr[min_ind]) { min_ind=j; } } swap(arr[min_ind],arr[i]); } }"
},
{
"code": null,
"e": 3261,
"s": 3259,
"text": "0"
},
{
"code": null,
"e": 3290,
"s": 3261,
"text": "ramasaimohanakhil1 month ago"
},
{
"code": null,
"e": 3312,
"s": 3290,
"text": "//mohanakhildenduluri"
},
{
"code": null,
"e": 3986,
"s": 3312,
"text": "class Solution{int select(int a[],int i){ int min=a[i],index=0; boolean flag=false; for(int j=i+1;j<a.length;j++) { if(a[j]<min) { min=a[j]; index=j; flag=true; } } if(flag) { return index; } return -1; // code here such that selectionSort() sorts arr[]}void selectionSort(int a[], int n){ //code here int temp=0; for(int i=0;i<n;i++) { int index=select(a,i); if(index!=-1) { temp=a[i]; a[i]=a[index]; a[index]=temp; } }}}"
},
{
"code": null,
"e": 3988,
"s": 3986,
"text": "0"
},
{
"code": null,
"e": 4016,
"s": 3988,
"text": "codewithshoaib191 month ago"
},
{
"code": null,
"e": 4413,
"s": 4016,
"text": "// int select(int arr[], int i)// {// // code here such that selectionSort() sorts arr[]// }void selectionSort(int arr[], int n){ //code here for(int i=0;i<n;i++){ int last=n-i-1; int max=getMax(arr,0,last); swap(arr,max,last); }} public static void swap(int[] arr, int s, int e) { int temp = arr[s]; arr[s] = arr[e]; arr[e] = temp; }"
},
{
"code": null,
"e": 4624,
"s": 4413,
"text": " public static int getMax(int[] arr, int s, int e) { int max = s; for (int i = s; i <= e; i++) { if (arr[i] > arr[max]) { max = i; } } return max; }"
},
{
"code": null,
"e": 4626,
"s": 4624,
"text": "0"
},
{
"code": null,
"e": 4647,
"s": 4626,
"text": "yash7raut1 month ago"
},
{
"code": null,
"e": 5045,
"s": 4647,
"text": "class Solution: def select(self, arr, i): # code here pass def selectionSort(self, arr,n): #code here n = len(arr) for i in range(n-1): min_idx = i for j in range(min_idx+1,n): if(arr[j]<arr[min_idx]): min_idx = j if(i!=min_idx): arr[i],arr[min_idx] = arr[min_idx],arr[i] "
},
{
"code": null,
"e": 5048,
"s": 5045,
"text": "+1"
},
{
"code": null,
"e": 5079,
"s": 5048,
"text": "vishesh__jhaPremium1 month ago"
},
{
"code": null,
"e": 5105,
"s": 5079,
"text": "Time Complexity: 0.0 /2.9"
},
{
"code": null,
"e": 5109,
"s": 5105,
"text": "C++"
},
{
"code": null,
"e": 5482,
"s": 5111,
"text": " int select(int arr[], int i) { //You can AVoid this Function } void selectionSort(int arr[], int n) { for(int i=0;i<n-1;i++) { int Min_Idx=i; for(int j=i+1;j<n;j++) { if(arr[j]<arr[Min_Idx]) Min_Idx=j; } swap(&arr[Min_Idx],&arr[i]); } }"
},
{
"code": null,
"e": 5628,
"s": 5482,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5664,
"s": 5628,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5674,
"s": 5664,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5684,
"s": 5674,
"text": "\nContest\n"
},
{
"code": null,
"e": 5747,
"s": 5684,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5895,
"s": 5747,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6103,
"s": 5895,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6209,
"s": 6103,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Find common values between two NumPy arrays - GeeksforGeeks
|
29 Aug, 2020
In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear.
Syntax: numpy.intersect1d(array1,array2)
Parameter :Two arrays.
Return :An array in which all the common element will appear.
Example 1:
Python
import numpy as np ar1 = np.array([0, 1, 2, 3, 4])ar2 = [1, 3, 4] # Common values between two arraysprint(np.intersect1d(ar1, ar2))
Output:
[1,3,4]
Example 2:
Python
import numpy as np ar1 = np.array([12, 14, 15, 16, 17])ar2 = [2, 4, 5, 6, 7, 8, 9, 12] # Common values between two arraysprint(np.intersect1d(ar1, ar2))
Output:
[12]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24484,
"s": 24292,
"text": "In NumPy, we can find common values between two arrays with the help intersect1d(). It will take parameter two arrays and it will return an array in which all the common elements will appear."
},
{
"code": null,
"e": 24525,
"s": 24484,
"text": "Syntax: numpy.intersect1d(array1,array2)"
},
{
"code": null,
"e": 24548,
"s": 24525,
"text": "Parameter :Two arrays."
},
{
"code": null,
"e": 24610,
"s": 24548,
"text": "Return :An array in which all the common element will appear."
},
{
"code": null,
"e": 24621,
"s": 24610,
"text": "Example 1:"
},
{
"code": null,
"e": 24628,
"s": 24621,
"text": "Python"
},
{
"code": "import numpy as np ar1 = np.array([0, 1, 2, 3, 4])ar2 = [1, 3, 4] # Common values between two arraysprint(np.intersect1d(ar1, ar2))",
"e": 24764,
"s": 24628,
"text": null
},
{
"code": null,
"e": 24772,
"s": 24764,
"text": "Output:"
},
{
"code": null,
"e": 24781,
"s": 24772,
"text": "[1,3,4]\n"
},
{
"code": null,
"e": 24792,
"s": 24781,
"text": "Example 2:"
},
{
"code": null,
"e": 24799,
"s": 24792,
"text": "Python"
},
{
"code": "import numpy as np ar1 = np.array([12, 14, 15, 16, 17])ar2 = [2, 4, 5, 6, 7, 8, 9, 12] # Common values between two arraysprint(np.intersect1d(ar1, ar2))",
"e": 24956,
"s": 24799,
"text": null
},
{
"code": null,
"e": 24964,
"s": 24956,
"text": "Output:"
},
{
"code": null,
"e": 24970,
"s": 24964,
"text": "[12]\n"
},
{
"code": null,
"e": 25001,
"s": 24970,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 25014,
"s": 25001,
"text": "Python-numpy"
},
{
"code": null,
"e": 25021,
"s": 25014,
"text": "Python"
},
{
"code": null,
"e": 25119,
"s": 25021,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25151,
"s": 25119,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25207,
"s": 25151,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25249,
"s": 25207,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25291,
"s": 25249,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25313,
"s": 25291,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25352,
"s": 25313,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25383,
"s": 25352,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25438,
"s": 25383,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25467,
"s": 25438,
"text": "Create a directory in Python"
}
] |
Is something better than pandas when the dataset fits the memory? | by Vaclav Dekanovsky | Medium | Towards Data Science
|
The tabular format is still the most typical way how to store data and there’s arguably no better tool how to explore data-tables than python’s pandas. Despite its broad range of capabilities, pandas has limits. In those cases, you have to opt for an alternative. Though, does it make sense to abandon pandas and use another tool, if the dataset fits comfortably into your memory?
Pandas is a convenient tabular data processor offering a variety of methods for loading, processing, and exporting datasets to many output formats. Pandas can handle a sizeable amount of data, but it’s limited by the memory of your PC. There was a golden rule of data science. If the data fits into the memory, use pandas. Is this rule still valid?
Use pandas when data fits your PC’s memory
Pandas alternatives were only recommended in these cases:
processing in pandas is slow
data doesn’t fit available memory
Let’s explore a few of these alternatives on a medium-size dataset to see if we can get any benefit or to confirm that you simply use pandas and sleep without doubts.
You can review complete code on GitHub
pandas_alternatives_POC.ipynb — exploring dask, spark, vaex and modin
julia_POC.ipynb — exploring julia and julia performance test
Performance_test.py — run python perf. tests in console
Results_and_Charts.ipynb — processing performance tests logs and creating the charts
Let’s first explore the arguments against the pandas alternatives.
they are not as universal as pandasdocumentation, tutorial, and community support is smaller
they are not as universal as pandas
documentation, tutorial, and community support is smaller
We will review several of the alternatives one by one and compare their syntax, computational approach, and performance. We will look at Dask, Vaex, PySpark, Modin (all in python) and Julia. These tools can be split into three categories:
Parallel/Cloud computing — Dask, PySpark, and Modin
Memory efficient — Vaex
Different programming language — Julia
For each of the tools, we will compare the speed of the basic operations using Kaggle fraud detection dataset. It contains two files train_transaction.csv (~700MB) and train_identity.csv (~30MB) which we will load, merge, aggregate, and sort to see how fast is the performance. I’ll do these operations on my 4 core notebook with 16MB RAM.
We will load, merge, sort and aggregate the data
Dask’s primary purpose is to parallelize any type of python computations — data processing, parallel message handling, or machine learning. The way how to spread up the calculations is to use the power of a cluster of computers. Even on a single PC, the computation can run faster, leveraging multiple processing cores.
Dask’s module way to work with the dataframes is prosaically called DataFrame. Its power originates in parallelism, which comes at a cost you must be aware:
Dask API is not so rich as pandas’sThe results must be materialized
Dask API is not so rich as pandas’s
The results must be materialized
Dask’s syntax is very similar to pandas.
As you can see, many methods are exactly the same in both libraries. You notice that dask basically lacks options for sorting. That’s because parallel sorting is special. Dask offers just one method, and that’s set_index. Index is sorted by definition.
The idea is to use the Dask to do the heavy lifting and then move the reduced and thus smaller dataset to pandas for final polishing. That brings us to the second caveat. Dask results must be materialized with .compute() command.
As you will see in the PySpark introduction, dask doesn’t calculate anything until it’s prompted to do so. All the steps are prepared and waiting for your command to start the work which comes with .compute() call.
You may wonder why don’t we get the results immediately, like when you run a pandas operation? The reason is simple. Dask is mainly used in case the data doesn't fit your memory and for that reason, results of the initial operations, like a load of the huge data frame cannot be materialized, because you don’t have enough memory to do so.
That’s why you prepare the computational steps, then let the cluster calculate and bring back a much smaller set containing only the results.
# the dask code goes for example like this:df = dd.read_csv(path)d2 = dd.read_csv(path2)re = df.merge(d2, on="col")re = re.groupby(cols).agg(params).compute()
It’s not straightforward how to compare the speed of two platforms meant for different purposes. The results might be skewed by the data as well. One tool can merge string columns very fast, while the other can excel in integer merging.
To show how fast these libraries can be, I’ve picked 5 operations, and I compared their speed. I repeated the performance test 7 times and I’ve measured that my cpu and memory usage never exceeded 50% of the PC (i7–5600 @ 2.60Ghz, 16GB Ram, SSD disk). No other process was running, besides the operational system and the performance test.
load_transactions — reading ~700MB CSV file
load_identity — reading ~30MB CSV file
merge — joining these two dataset on a string column
aggregation — grouping over 6 columns and calculating sum and mean
sorting — sort the merge dataset 3 times (if the library allows)
It looks that Dask loads the CSV files very fast, but the reason is the lazy operation mode of Dask. The loads are postponed until I materialize the results during the aggregation. It means that Dask only prepares for loading and merging, but performs it together with the aggregation.
Dask has very little support for sorting. Even the official guidelines say to run parallel computations and then pass the calculated (and much smaller results) to pandas.
Even if I try to compute the read_csv results, Dask was about 30% slower on my test datasets. That only confirms the original assumption, that Dask is beneficial mainly when your dataset doesn’t fit into the memory.
It’s python API for Spark, an analytic big data engine. Spark has evolved on the top of the Hadoop platform and might be the most popular cloud computing tool. It’s written in Scala, but many methods in the pySpark API let you compute without losing speed for python interpretation.
Similarly like Dask, you first define all the operations, and then you run .collect() command to materialize the results. There are more options than collect and you can read about them in the spark documentation — Actions.
Spark is using resilient distributed datasets (RDD) to perform the calculation and the syntax to operate them is quite similar to pandas. Often there are alternatives that yield the same or similar results like sort or orderBy methods.
In the beginning, you must initialize the Spark session. Then you prepare the steps using python API or you can benefit from Spark SQL and write the code in SQL.
You don’t have to install spark if you want to try it, because PySpark package comes with a spark instance. You must install java on your PC nevertheless.
The same performance tests were run using pySpark that I’ve described in the Dask section and the results were similar.
The difference is that spark reads part of the csv in order to infer the schema of the dataframe. It takes more time than to load the whole dataset to pandas in this case.
Spark is a great platform for massive computations leveraging the power of big clusters to get insights from a huge dataset. To employ spark on relatively small data won’t produce desired speed increase.
So far we have seen the platforms which split the work between more computer cores and often many computers in the cluster. They usually can not beat pandas for the dataset which fit the memory. Vaex aims to do that though.
The library was created to make the basic analysis of a dataset blazingly fast. Vaex doesn’t support the full range of pandas functionalities, but it can calculate basic statistics and create some chart types very quickly.
There are not many differences between pandas and vaex syntax.
Unlike the previous two tools, Vaex speed is similar to pandas on the example dataset, and in some areas, it’s even faster.
Often you will do well with pandas, but there can be cases when you struggle and that’s the time to try vaex. In this article, Jonathan Alexander did a bigger performance test to find out that Vaex can beat other approaches. It mainly masters join.
Julia is somewhat popular in the data science community. It was predicted to have a grand future, though the break-through did not happen yet. There are however many people who fell in love with the way Julia deals with things. I’m one of them.
Contrary to python, Julia is a compiled language. That often results in better performance. Both languages run in Jupyter notebook and that’s why Julia is popular for data science proof of concepts.
Julia was developed especially for mathematicians and data scientists. You can read what benefits of many existing programming languages Julia combines in the Why we created Julia article.
Despite Julia being a different language it does many things the pythonic way. On top of that, it uses its own tricks when suitable. I love the bang ! sign determining that it’s a mutable operation. It’s elegant and compact (compared to pandas’s inplace=True).
On the other hand, in python, many things have developed a preferred way of conding overtime. Julia often offers several ways how to do even the basic things like reading the csv. The syntax is quite stable since 1.0 release, but it can still happen that your favorite approach will be deprecated in the future.
Let’s compare how data loading, merging, aggregating and sorting look in pandas and julia.
Let’s see if Julia’s DataFrames can beat pandas.
Considering the speed of Julia isn’t that straightforward. When you first run any Julia code, the Just-in-Time compiler needs to translate it to a computer language, and that takes some time. That’s why the first run of any code takes longer than the follow-up runs.
On the chart below you can see that the first run is significantly longer than the average of the remaining six measurements. I’ve also tried to run Julia on a single core (julia) and on 4 processor cores (julia-4).
You can run julia with more cores by setting environmental variable JULIA_NUM_THREADS to the number of cores you want to use. Since 1.5 you can start julia by julia -t n or julia --threads n where n is the desired number of cores.
Processing using more cores is usually faster and julia has very good support for out-of-the-box parallelization. You might be concerned by the compiling speed, but you don’t have to be. The code is compiled once and changing the parameters won’t force the recompilation. After you compile CSV.read(joinpath(folder,file), DataFrame) the following calls are processed without compilation even in case you change the path to the source file. That is why you don’t see any delay in load_identity step because CSV reading was already compiled before.
Before we close our discussion about pandas alternatives, I must mention the Modin library. Its authors claim modin leverage parallelism to speed up 80% of pandas functions. I have unfortunately struggled to see these benefits. Sometimes it breaks during the initial import command. On other occasions modin said: “not supported, defaulting to pandas”, though the operation eventually crashed leaving 4 python processes each consuming a significant amount of memory. It took some time to kill these processes afterward.
I must say I like the idea behind modin and I hope one day these gaps will be covered which would elevate modin to a position of an alternative worth considering.
We have explored several popular pandas alternatives to find out whether it makes sense to use something else if the dataset is small enough to fit into the memory.
None of the parallel computing platforms was able to beat pandas in speed. Considering their more complex syntax, additional installation requirements and lack of some data processing capabilities eliminated these tools as an ideal alternative to pandas.
Vaex shows the potential to speed up some tasks during data exploration. The benefit can become more significant with the larger datasets.
Julia was developed with data scientists’ needs in mind. It might not be as popular as pandas and probably doesn't offer all the tricks pandas does. For some operations, it can provide a performance boost and I must say that some code is more elegant in julia. Even though Julia doesn’t get into the top 20 most popular programming languages, I guess it has a future and you won’t make a mistake if you keep an eye on its development.
Did you like this article, check other tutorials I wrote:
Alternative ways how to persist pandas dataframe
Demonstrative way how to use line charts
Turn a list of addresses into a map
|
[
{
"code": null,
"e": 553,
"s": 172,
"text": "The tabular format is still the most typical way how to store data and there’s arguably no better tool how to explore data-tables than python’s pandas. Despite its broad range of capabilities, pandas has limits. In those cases, you have to opt for an alternative. Though, does it make sense to abandon pandas and use another tool, if the dataset fits comfortably into your memory?"
},
{
"code": null,
"e": 902,
"s": 553,
"text": "Pandas is a convenient tabular data processor offering a variety of methods for loading, processing, and exporting datasets to many output formats. Pandas can handle a sizeable amount of data, but it’s limited by the memory of your PC. There was a golden rule of data science. If the data fits into the memory, use pandas. Is this rule still valid?"
},
{
"code": null,
"e": 945,
"s": 902,
"text": "Use pandas when data fits your PC’s memory"
},
{
"code": null,
"e": 1003,
"s": 945,
"text": "Pandas alternatives were only recommended in these cases:"
},
{
"code": null,
"e": 1032,
"s": 1003,
"text": "processing in pandas is slow"
},
{
"code": null,
"e": 1066,
"s": 1032,
"text": "data doesn’t fit available memory"
},
{
"code": null,
"e": 1233,
"s": 1066,
"text": "Let’s explore a few of these alternatives on a medium-size dataset to see if we can get any benefit or to confirm that you simply use pandas and sleep without doubts."
},
{
"code": null,
"e": 1272,
"s": 1233,
"text": "You can review complete code on GitHub"
},
{
"code": null,
"e": 1342,
"s": 1272,
"text": "pandas_alternatives_POC.ipynb — exploring dask, spark, vaex and modin"
},
{
"code": null,
"e": 1403,
"s": 1342,
"text": "julia_POC.ipynb — exploring julia and julia performance test"
},
{
"code": null,
"e": 1459,
"s": 1403,
"text": "Performance_test.py — run python perf. tests in console"
},
{
"code": null,
"e": 1544,
"s": 1459,
"text": "Results_and_Charts.ipynb — processing performance tests logs and creating the charts"
},
{
"code": null,
"e": 1611,
"s": 1544,
"text": "Let’s first explore the arguments against the pandas alternatives."
},
{
"code": null,
"e": 1704,
"s": 1611,
"text": "they are not as universal as pandasdocumentation, tutorial, and community support is smaller"
},
{
"code": null,
"e": 1740,
"s": 1704,
"text": "they are not as universal as pandas"
},
{
"code": null,
"e": 1798,
"s": 1740,
"text": "documentation, tutorial, and community support is smaller"
},
{
"code": null,
"e": 2037,
"s": 1798,
"text": "We will review several of the alternatives one by one and compare their syntax, computational approach, and performance. We will look at Dask, Vaex, PySpark, Modin (all in python) and Julia. These tools can be split into three categories:"
},
{
"code": null,
"e": 2089,
"s": 2037,
"text": "Parallel/Cloud computing — Dask, PySpark, and Modin"
},
{
"code": null,
"e": 2113,
"s": 2089,
"text": "Memory efficient — Vaex"
},
{
"code": null,
"e": 2152,
"s": 2113,
"text": "Different programming language — Julia"
},
{
"code": null,
"e": 2492,
"s": 2152,
"text": "For each of the tools, we will compare the speed of the basic operations using Kaggle fraud detection dataset. It contains two files train_transaction.csv (~700MB) and train_identity.csv (~30MB) which we will load, merge, aggregate, and sort to see how fast is the performance. I’ll do these operations on my 4 core notebook with 16MB RAM."
},
{
"code": null,
"e": 2541,
"s": 2492,
"text": "We will load, merge, sort and aggregate the data"
},
{
"code": null,
"e": 2861,
"s": 2541,
"text": "Dask’s primary purpose is to parallelize any type of python computations — data processing, parallel message handling, or machine learning. The way how to spread up the calculations is to use the power of a cluster of computers. Even on a single PC, the computation can run faster, leveraging multiple processing cores."
},
{
"code": null,
"e": 3018,
"s": 2861,
"text": "Dask’s module way to work with the dataframes is prosaically called DataFrame. Its power originates in parallelism, which comes at a cost you must be aware:"
},
{
"code": null,
"e": 3086,
"s": 3018,
"text": "Dask API is not so rich as pandas’sThe results must be materialized"
},
{
"code": null,
"e": 3122,
"s": 3086,
"text": "Dask API is not so rich as pandas’s"
},
{
"code": null,
"e": 3155,
"s": 3122,
"text": "The results must be materialized"
},
{
"code": null,
"e": 3196,
"s": 3155,
"text": "Dask’s syntax is very similar to pandas."
},
{
"code": null,
"e": 3449,
"s": 3196,
"text": "As you can see, many methods are exactly the same in both libraries. You notice that dask basically lacks options for sorting. That’s because parallel sorting is special. Dask offers just one method, and that’s set_index. Index is sorted by definition."
},
{
"code": null,
"e": 3679,
"s": 3449,
"text": "The idea is to use the Dask to do the heavy lifting and then move the reduced and thus smaller dataset to pandas for final polishing. That brings us to the second caveat. Dask results must be materialized with .compute() command."
},
{
"code": null,
"e": 3894,
"s": 3679,
"text": "As you will see in the PySpark introduction, dask doesn’t calculate anything until it’s prompted to do so. All the steps are prepared and waiting for your command to start the work which comes with .compute() call."
},
{
"code": null,
"e": 4234,
"s": 3894,
"text": "You may wonder why don’t we get the results immediately, like when you run a pandas operation? The reason is simple. Dask is mainly used in case the data doesn't fit your memory and for that reason, results of the initial operations, like a load of the huge data frame cannot be materialized, because you don’t have enough memory to do so."
},
{
"code": null,
"e": 4376,
"s": 4234,
"text": "That’s why you prepare the computational steps, then let the cluster calculate and bring back a much smaller set containing only the results."
},
{
"code": null,
"e": 4535,
"s": 4376,
"text": "# the dask code goes for example like this:df = dd.read_csv(path)d2 = dd.read_csv(path2)re = df.merge(d2, on=\"col\")re = re.groupby(cols).agg(params).compute()"
},
{
"code": null,
"e": 4772,
"s": 4535,
"text": "It’s not straightforward how to compare the speed of two platforms meant for different purposes. The results might be skewed by the data as well. One tool can merge string columns very fast, while the other can excel in integer merging."
},
{
"code": null,
"e": 5111,
"s": 4772,
"text": "To show how fast these libraries can be, I’ve picked 5 operations, and I compared their speed. I repeated the performance test 7 times and I’ve measured that my cpu and memory usage never exceeded 50% of the PC (i7–5600 @ 2.60Ghz, 16GB Ram, SSD disk). No other process was running, besides the operational system and the performance test."
},
{
"code": null,
"e": 5155,
"s": 5111,
"text": "load_transactions — reading ~700MB CSV file"
},
{
"code": null,
"e": 5194,
"s": 5155,
"text": "load_identity — reading ~30MB CSV file"
},
{
"code": null,
"e": 5247,
"s": 5194,
"text": "merge — joining these two dataset on a string column"
},
{
"code": null,
"e": 5314,
"s": 5247,
"text": "aggregation — grouping over 6 columns and calculating sum and mean"
},
{
"code": null,
"e": 5379,
"s": 5314,
"text": "sorting — sort the merge dataset 3 times (if the library allows)"
},
{
"code": null,
"e": 5665,
"s": 5379,
"text": "It looks that Dask loads the CSV files very fast, but the reason is the lazy operation mode of Dask. The loads are postponed until I materialize the results during the aggregation. It means that Dask only prepares for loading and merging, but performs it together with the aggregation."
},
{
"code": null,
"e": 5836,
"s": 5665,
"text": "Dask has very little support for sorting. Even the official guidelines say to run parallel computations and then pass the calculated (and much smaller results) to pandas."
},
{
"code": null,
"e": 6052,
"s": 5836,
"text": "Even if I try to compute the read_csv results, Dask was about 30% slower on my test datasets. That only confirms the original assumption, that Dask is beneficial mainly when your dataset doesn’t fit into the memory."
},
{
"code": null,
"e": 6335,
"s": 6052,
"text": "It’s python API for Spark, an analytic big data engine. Spark has evolved on the top of the Hadoop platform and might be the most popular cloud computing tool. It’s written in Scala, but many methods in the pySpark API let you compute without losing speed for python interpretation."
},
{
"code": null,
"e": 6559,
"s": 6335,
"text": "Similarly like Dask, you first define all the operations, and then you run .collect() command to materialize the results. There are more options than collect and you can read about them in the spark documentation — Actions."
},
{
"code": null,
"e": 6795,
"s": 6559,
"text": "Spark is using resilient distributed datasets (RDD) to perform the calculation and the syntax to operate them is quite similar to pandas. Often there are alternatives that yield the same or similar results like sort or orderBy methods."
},
{
"code": null,
"e": 6957,
"s": 6795,
"text": "In the beginning, you must initialize the Spark session. Then you prepare the steps using python API or you can benefit from Spark SQL and write the code in SQL."
},
{
"code": null,
"e": 7112,
"s": 6957,
"text": "You don’t have to install spark if you want to try it, because PySpark package comes with a spark instance. You must install java on your PC nevertheless."
},
{
"code": null,
"e": 7232,
"s": 7112,
"text": "The same performance tests were run using pySpark that I’ve described in the Dask section and the results were similar."
},
{
"code": null,
"e": 7404,
"s": 7232,
"text": "The difference is that spark reads part of the csv in order to infer the schema of the dataframe. It takes more time than to load the whole dataset to pandas in this case."
},
{
"code": null,
"e": 7608,
"s": 7404,
"text": "Spark is a great platform for massive computations leveraging the power of big clusters to get insights from a huge dataset. To employ spark on relatively small data won’t produce desired speed increase."
},
{
"code": null,
"e": 7832,
"s": 7608,
"text": "So far we have seen the platforms which split the work between more computer cores and often many computers in the cluster. They usually can not beat pandas for the dataset which fit the memory. Vaex aims to do that though."
},
{
"code": null,
"e": 8055,
"s": 7832,
"text": "The library was created to make the basic analysis of a dataset blazingly fast. Vaex doesn’t support the full range of pandas functionalities, but it can calculate basic statistics and create some chart types very quickly."
},
{
"code": null,
"e": 8118,
"s": 8055,
"text": "There are not many differences between pandas and vaex syntax."
},
{
"code": null,
"e": 8242,
"s": 8118,
"text": "Unlike the previous two tools, Vaex speed is similar to pandas on the example dataset, and in some areas, it’s even faster."
},
{
"code": null,
"e": 8491,
"s": 8242,
"text": "Often you will do well with pandas, but there can be cases when you struggle and that’s the time to try vaex. In this article, Jonathan Alexander did a bigger performance test to find out that Vaex can beat other approaches. It mainly masters join."
},
{
"code": null,
"e": 8736,
"s": 8491,
"text": "Julia is somewhat popular in the data science community. It was predicted to have a grand future, though the break-through did not happen yet. There are however many people who fell in love with the way Julia deals with things. I’m one of them."
},
{
"code": null,
"e": 8935,
"s": 8736,
"text": "Contrary to python, Julia is a compiled language. That often results in better performance. Both languages run in Jupyter notebook and that’s why Julia is popular for data science proof of concepts."
},
{
"code": null,
"e": 9124,
"s": 8935,
"text": "Julia was developed especially for mathematicians and data scientists. You can read what benefits of many existing programming languages Julia combines in the Why we created Julia article."
},
{
"code": null,
"e": 9385,
"s": 9124,
"text": "Despite Julia being a different language it does many things the pythonic way. On top of that, it uses its own tricks when suitable. I love the bang ! sign determining that it’s a mutable operation. It’s elegant and compact (compared to pandas’s inplace=True)."
},
{
"code": null,
"e": 9697,
"s": 9385,
"text": "On the other hand, in python, many things have developed a preferred way of conding overtime. Julia often offers several ways how to do even the basic things like reading the csv. The syntax is quite stable since 1.0 release, but it can still happen that your favorite approach will be deprecated in the future."
},
{
"code": null,
"e": 9788,
"s": 9697,
"text": "Let’s compare how data loading, merging, aggregating and sorting look in pandas and julia."
},
{
"code": null,
"e": 9837,
"s": 9788,
"text": "Let’s see if Julia’s DataFrames can beat pandas."
},
{
"code": null,
"e": 10104,
"s": 9837,
"text": "Considering the speed of Julia isn’t that straightforward. When you first run any Julia code, the Just-in-Time compiler needs to translate it to a computer language, and that takes some time. That’s why the first run of any code takes longer than the follow-up runs."
},
{
"code": null,
"e": 10320,
"s": 10104,
"text": "On the chart below you can see that the first run is significantly longer than the average of the remaining six measurements. I’ve also tried to run Julia on a single core (julia) and on 4 processor cores (julia-4)."
},
{
"code": null,
"e": 10551,
"s": 10320,
"text": "You can run julia with more cores by setting environmental variable JULIA_NUM_THREADS to the number of cores you want to use. Since 1.5 you can start julia by julia -t n or julia --threads n where n is the desired number of cores."
},
{
"code": null,
"e": 11098,
"s": 10551,
"text": "Processing using more cores is usually faster and julia has very good support for out-of-the-box parallelization. You might be concerned by the compiling speed, but you don’t have to be. The code is compiled once and changing the parameters won’t force the recompilation. After you compile CSV.read(joinpath(folder,file), DataFrame) the following calls are processed without compilation even in case you change the path to the source file. That is why you don’t see any delay in load_identity step because CSV reading was already compiled before."
},
{
"code": null,
"e": 11618,
"s": 11098,
"text": "Before we close our discussion about pandas alternatives, I must mention the Modin library. Its authors claim modin leverage parallelism to speed up 80% of pandas functions. I have unfortunately struggled to see these benefits. Sometimes it breaks during the initial import command. On other occasions modin said: “not supported, defaulting to pandas”, though the operation eventually crashed leaving 4 python processes each consuming a significant amount of memory. It took some time to kill these processes afterward."
},
{
"code": null,
"e": 11781,
"s": 11618,
"text": "I must say I like the idea behind modin and I hope one day these gaps will be covered which would elevate modin to a position of an alternative worth considering."
},
{
"code": null,
"e": 11946,
"s": 11781,
"text": "We have explored several popular pandas alternatives to find out whether it makes sense to use something else if the dataset is small enough to fit into the memory."
},
{
"code": null,
"e": 12201,
"s": 11946,
"text": "None of the parallel computing platforms was able to beat pandas in speed. Considering their more complex syntax, additional installation requirements and lack of some data processing capabilities eliminated these tools as an ideal alternative to pandas."
},
{
"code": null,
"e": 12340,
"s": 12201,
"text": "Vaex shows the potential to speed up some tasks during data exploration. The benefit can become more significant with the larger datasets."
},
{
"code": null,
"e": 12775,
"s": 12340,
"text": "Julia was developed with data scientists’ needs in mind. It might not be as popular as pandas and probably doesn't offer all the tricks pandas does. For some operations, it can provide a performance boost and I must say that some code is more elegant in julia. Even though Julia doesn’t get into the top 20 most popular programming languages, I guess it has a future and you won’t make a mistake if you keep an eye on its development."
},
{
"code": null,
"e": 12833,
"s": 12775,
"text": "Did you like this article, check other tutorials I wrote:"
},
{
"code": null,
"e": 12882,
"s": 12833,
"text": "Alternative ways how to persist pandas dataframe"
},
{
"code": null,
"e": 12923,
"s": 12882,
"text": "Demonstrative way how to use line charts"
}
] |
JavaScript - Debugging
|
Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug.
The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks..
The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.
Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs.
To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the "Display a Notification About Every Script Error" box option as shown below −
Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development.
Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes.
Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred.
If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error.
There are various ways to debug your JavaScript −
One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors.
The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which is available for free at Douglas Crockford's JavaScript Lint.
Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format
You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −
var debugging = true;
var whichImage = "widget";
if( debugging )
alert( "Calls swapImage() with argument: " + whichImage );
var swapStatus = swapImage( whichImage );
if( debugging )
alert( "Exits swapImage() with swapStatus=" + swapStatus );
By examining the content and order of the alert() as they appear, you can examine the health of your program very easily.
A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution.
Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values.
The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/~ginda/venkman
You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −
Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code.
Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.
Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements.
Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.
Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort.
Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.
Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function.
Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently.
Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code.
Use descriptive variable and function names and avoid using single-character names.
Use descriptive variable and function names and avoid using single-character names.
Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double).
Watch your equal signs. You should not used a single = for comparison purpose.
Watch your equal signs. You should not used a single = for comparison purpose.
Declare variables explicitly using the var keyword.
Declare variables explicitly using the var keyword.
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2587,
"s": 2466,
"text": "Every now and then, developers commit mistakes while coding. A mistake in a program or a script is referred to as a bug."
},
{
"code": null,
"e": 2777,
"s": 2587,
"text": "The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks.."
},
{
"code": null,
"e": 2971,
"s": 2777,
"text": "The most basic way to track down errors is by turning on error information in your browser. By default, Internet Explorer shows an error icon in the status bar when an error occurs on the page."
},
{
"code": null,
"e": 3083,
"s": 2971,
"text": "Double-clicking this icon takes you to a dialog box showing information about the specific error that occurred."
},
{
"code": null,
"e": 3228,
"s": 3083,
"text": "Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show the Error dialog box whenever an error occurs."
},
{
"code": null,
"e": 3404,
"s": 3228,
"text": "To enable this option, select Tools → Internet Options → Advanced tab. and then finally check the \"Display a Notification About Every Script Error\" box option as shown below −"
},
{
"code": null,
"e": 3611,
"s": 3404,
"text": "Other browsers like Firefox, Netscape, and Mozilla send error messages to a special window called the JavaScript Console or Error Consol. To view the console, select Tools → Error Consol or Web Development."
},
{
"code": null,
"e": 3772,
"s": 3611,
"text": "Unfortunately, since these browsers give no visual indication when an error occurs, you must keep the Console open and watch for errors as your script executes."
},
{
"code": null,
"e": 3986,
"s": 3772,
"text": "Error notifications that show up on Console or through Internet Explorer dialog boxes are the result of both syntax and runtime errors. These error notification include the line number at which the error occurred."
},
{
"code": null,
"e": 4127,
"s": 3986,
"text": "If you are using Firefox, then you can click on the error available in the error console to go to the exact line in the script having error."
},
{
"code": null,
"e": 4177,
"s": 4127,
"text": "There are various ways to debug your JavaScript −"
},
{
"code": null,
"e": 4501,
"s": 4177,
"text": "One way to check your JavaScript code for strange bugs is to run it through a program that checks it to make sure it is valid and that it follows the official syntax rules of the language. These programs are called validating parsers or just validators for short, and often come with commercial HTML and JavaScript editors."
},
{
"code": null,
"e": 4654,
"s": 4501,
"text": "The most convenient validator for JavaScript is Douglas Crockford's JavaScript Lint, which is available for free at Douglas Crockford's JavaScript Lint."
},
{
"code": null,
"e": 5031,
"s": 4654,
"text": "Simply visit that web page, paste your JavaScript (Only JavaScript) code into the text area provided, and click the jslint button. This program will parse through your JavaScript code, ensuring that all the variable and function definitions follow the correct syntax. It will also check JavaScript statements, such as if and while, to ensure they too follow the correct format"
},
{
"code": null,
"e": 5171,
"s": 5031,
"text": "You can use the alert() or document.write() methods in your program to debug your code. For example, you might write something as follows −"
},
{
"code": null,
"e": 5424,
"s": 5171,
"text": "var debugging = true;\nvar whichImage = \"widget\";\n\nif( debugging )\n alert( \"Calls swapImage() with argument: \" + whichImage );\n var swapStatus = swapImage( whichImage );\n\nif( debugging )\n alert( \"Exits swapImage() with swapStatus=\" + swapStatus );"
},
{
"code": null,
"e": 5546,
"s": 5424,
"text": "By examining the content and order of the alert() as they appear, you can examine the health of your program very easily."
},
{
"code": null,
"e": 5829,
"s": 5546,
"text": "A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution."
},
{
"code": null,
"e": 6153,
"s": 5829,
"text": "Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values."
},
{
"code": null,
"e": 6327,
"s": 6153,
"text": "The latest version of the Mozilla JavaScript Debugger (code-named Venkman) for both Mozilla and Netscape browsers can be downloaded at http://www.hacksrus.com/~ginda/venkman"
},
{
"code": null,
"e": 6451,
"s": 6327,
"text": "You can keep the following tips in mind to reduce the number of errors in your scripts and simplify the debugging process −"
},
{
"code": null,
"e": 6603,
"s": 6451,
"text": "Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code."
},
{
"code": null,
"e": 6755,
"s": 6603,
"text": "Use plenty of comments. Comments enable you to explain why you wrote the script the way you did and to explain particularly difficult sections of code."
},
{
"code": null,
"e": 6949,
"s": 6755,
"text": "Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements."
},
{
"code": null,
"e": 7143,
"s": 6949,
"text": "Always use indentation to make your code easy to read. Indenting statements also makes it easier for you to match up beginning and ending tags, curly braces, and other HTML and script elements."
},
{
"code": null,
"e": 7321,
"s": 7143,
"text": "Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort."
},
{
"code": null,
"e": 7499,
"s": 7321,
"text": "Write modular code. Whenever possible, group your statements into functions. Functions let you group related statements, and test and reuse portions of code with minimal effort."
},
{
"code": null,
"e": 7696,
"s": 7499,
"text": "Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function."
},
{
"code": null,
"e": 7893,
"s": 7696,
"text": "Be consistent in the way you name your variables and functions. Try using names that are long enough to be meaningful and that describe the contents of the variable or the purpose of the function."
},
{
"code": null,
"e": 8066,
"s": 7893,
"text": "Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently."
},
{
"code": null,
"e": 8239,
"s": 8066,
"text": "Use consistent syntax when naming variables and functions. In other words, keep them all lowercase or all uppercase; if you prefer Camel-Back notation, use it consistently."
},
{
"code": null,
"e": 8440,
"s": 8239,
"text": "Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code."
},
{
"code": null,
"e": 8641,
"s": 8440,
"text": "Test long scripts in a modular fashion. In other words, do not try to write the entire script before testing any portion of it. Write a piece and get it to work before adding the next portion of code."
},
{
"code": null,
"e": 8725,
"s": 8641,
"text": "Use descriptive variable and function names and avoid using single-character names."
},
{
"code": null,
"e": 8809,
"s": 8725,
"text": "Use descriptive variable and function names and avoid using single-character names."
},
{
"code": null,
"e": 8983,
"s": 8809,
"text": "Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double)."
},
{
"code": null,
"e": 9157,
"s": 8983,
"text": "Watch your quotation marks. Remember that quotation marks are used in pairs around strings and that both quotation marks must be of the same style (either single or double)."
},
{
"code": null,
"e": 9236,
"s": 9157,
"text": "Watch your equal signs. You should not used a single = for comparison purpose."
},
{
"code": null,
"e": 9315,
"s": 9236,
"text": "Watch your equal signs. You should not used a single = for comparison purpose."
},
{
"code": null,
"e": 9367,
"s": 9315,
"text": "Declare variables explicitly using the var keyword."
},
{
"code": null,
"e": 9419,
"s": 9367,
"text": "Declare variables explicitly using the var keyword."
},
{
"code": null,
"e": 9454,
"s": 9419,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9468,
"s": 9454,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 9502,
"s": 9468,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 9516,
"s": 9502,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9551,
"s": 9516,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9568,
"s": 9551,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9603,
"s": 9568,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 9620,
"s": 9603,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9653,
"s": 9620,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9681,
"s": 9653,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9715,
"s": 9681,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 9743,
"s": 9715,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9750,
"s": 9743,
"text": " Print"
},
{
"code": null,
"e": 9761,
"s": 9750,
"text": " Add Notes"
}
] |
C program to print a string without any quote in the program
|
This is another tricky problem. In this program, we will see how to print a string using C where no quotation marks are used.
Here we are using macro function. We are defining a macro function like
#define getString(x) #x
The getString() is a macro function. It returns x by converting it into a string. The # before x is denoting that the function will convert x into a string.
Input: Take one string without quote
Output: Print that string into console
Step 1:Take a string without quote
Step 2: Use macro function to print it into a string
Step 3: End
Live Demo
#include<stdio.h>
#define getString(x) #x
//The # will convert x into a string
main() {
printf(getString(Hello World));
}
Hello World
|
[
{
"code": null,
"e": 1188,
"s": 1062,
"text": "This is another tricky problem. In this program, we will see how to print a string using C where no quotation marks are used."
},
{
"code": null,
"e": 1260,
"s": 1188,
"text": "Here we are using macro function. We are defining a macro function like"
},
{
"code": null,
"e": 1284,
"s": 1260,
"text": "#define getString(x) #x"
},
{
"code": null,
"e": 1441,
"s": 1284,
"text": "The getString() is a macro function. It returns x by converting it into a string. The # before x is denoting that the function will convert x into a string."
},
{
"code": null,
"e": 1517,
"s": 1441,
"text": "Input: Take one string without quote\nOutput: Print that string into console"
},
{
"code": null,
"e": 1617,
"s": 1517,
"text": "Step 1:Take a string without quote\nStep 2: Use macro function to print it into a string\nStep 3: End"
},
{
"code": null,
"e": 1628,
"s": 1617,
"text": " Live Demo"
},
{
"code": null,
"e": 1753,
"s": 1628,
"text": "#include<stdio.h>\n#define getString(x) #x\n//The # will convert x into a string\nmain() {\n printf(getString(Hello World));\n}"
},
{
"code": null,
"e": 1765,
"s": 1753,
"text": "Hello World"
}
] |
Computer Arithmetic | Set - 1 - GeeksforGeeks
|
07 Apr, 2021
Negative Number Representation
Sign Magnitude
Sign magnitude is a very simple representation of negative numbers. In sign magnitude the first bit is dedicated to represent the sign and hence it is called sign bit.
Sign bit ‘1’ represents negative sign.
Sign bit ‘0’ represents positive sign.
In sign magnitude representation of a n – bit number, the first bit will represent sign and rest n-1 bits represent magnitude of number.
For example,
+25 = 011001
Where 11001 = 25
And 0 for ‘+’
-25 = 111001
Where 11001 = 25
And 1 for ‘-‘.
Range of number represented by sign magnitude method = -(2n-1-1) to +(2n-1-1) (for n bit number)
But there is one problem in sign magnitude and that is we have two representations of 0
+0 = 000000
– 0 = 100000
2’s complement method
To represent a negative number in this form, first we need to take the 1’s complement of the number represented in simple positive binary form and then add 1 to it.
For example:
(-8)10 = (1000)2
1’s complement of 1000 = 0111
Adding 1 to it, 0111 + 1 = 1000
So, (-8)10 = (1000)2
Please don’t get confused with (8)10 =1000 and (-8)10=1000 as with 4 bits, we can’t represent a positive number more than 7. So, 1000 is representing -8 only.
Range of number represented by 2’s complement = (-2n-1 to 2n-1 – 1)
Floating point representation of numbers
32-bit representation floating point numbers IEEE standard
Normalization
Floating point numbers are usually normalized
Exponent is adjusted so that leading bit (MSB) of mantissa is 1
Since it is always 1 there is no need to store it
Scientific notation where numbers are normalized to give a single digit before the decimal point like in decimal system e.g. 3.123 x 103
For example, we represent 3.625 in 32 bit format.
Changing 3 in binary=11
Changing .625 in binary
.625 X 2 1
.25 X 2 0
.5 X 2 1
.625 X 2 1
.25 X 2 0
.5 X 2 1
Writing in binary exponent form
3.625=11.101 X 20
On normalizing
11.101 X 20=1.1101 X 21
On biasing exponent = 127 + 1 = 128
(128)10=(10000000) 2
For getting significand
Digits after decimal = 1101
Expanding to 23 bit = 11010000000000000000000
Setting sign bit
As it is a positive number, sign bit = 0
Finally we arrange according to representation
Sign bit exponent significand
0 10000000 11010000000000000000000
64-bit representation floating point numbers IEEE standard
Again we follow the same procedure upto normalization. After that, we add 1023 to bias the exponent.
For example, we represent -3.625 in 64 bit format.
Changing 3 in binary = 11
Changing .625 in binary
.625 X 2 1
.25 X 2 0
.5 X 2 1
Writing in binary exponent form
3.625 = 11.101 X 20
On normalizing
11.101 X 20 = 1.1101 X 21
On biasing exponent 1023 + 1 = 1024
(1024)10 = (10000000000)2
So 11 bit exponent = 10000000000
52 bit significand = 110100000000 ............. making total 52 bits
Setting sign bit = 1 (number is negative)
So, final representation
1 10000000000 110100000000 ............. making total 52 bits by adding further 0’s
Converting floating point into decimal
Let’s convert a FP number into decimal
1 01111100 11000000000000000000000
The decimal value of an IEEE number is given by the formula:
(1 -2s) * (1 + f) * 2( e – bias )
where
s, f and e fields are taken as decimal here.
(1 -2s) is 1 or -1, depending upon sign bit 0 and 1
add an implicit 1 to the significand (fraction field f), as in formula
Again, the bias is either 127 or 1023, for single or double precision respectively.
First convert each individual field to decimal.
The sign bit s is 1
The e field contains 01111100 = (124)10
The mantissa is 0.11000 ... = (0.75)10
Putting these values in formula
(1 – 2) * (1 + 0.75) * 2124 – 127 = ( – 1.75 * 2-3 ) = – 0.21875
This article has been contributed by Anuj Batham.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
sachinsinghbisht5
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cache Memory in Computer Organization
Addressing Modes
Architecture of 8086
Logical and Physical Address in Operating System
Random Access Memory (RAM) and Read Only Memory (ROM)
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Addressing modes in 8085 microprocessor
Computer Organization | RISC and CISC
8085 program to add two 8 bit numbers
Architecture of 8085 microprocessor
|
[
{
"code": null,
"e": 26443,
"s": 26415,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26476,
"s": 26445,
"text": "Negative Number Representation"
},
{
"code": null,
"e": 26491,
"s": 26476,
"text": "Sign Magnitude"
},
{
"code": null,
"e": 26659,
"s": 26491,
"text": "Sign magnitude is a very simple representation of negative numbers. In sign magnitude the first bit is dedicated to represent the sign and hence it is called sign bit."
},
{
"code": null,
"e": 26698,
"s": 26659,
"text": "Sign bit ‘1’ represents negative sign."
},
{
"code": null,
"e": 26737,
"s": 26698,
"text": "Sign bit ‘0’ represents positive sign."
},
{
"code": null,
"e": 26874,
"s": 26737,
"text": "In sign magnitude representation of a n – bit number, the first bit will represent sign and rest n-1 bits represent magnitude of number."
},
{
"code": null,
"e": 26889,
"s": 26876,
"text": "For example,"
},
{
"code": null,
"e": 26902,
"s": 26889,
"text": "+25 = 011001"
},
{
"code": null,
"e": 26919,
"s": 26902,
"text": "Where 11001 = 25"
},
{
"code": null,
"e": 26933,
"s": 26919,
"text": "And 0 for ‘+’"
},
{
"code": null,
"e": 26946,
"s": 26933,
"text": "-25 = 111001"
},
{
"code": null,
"e": 26963,
"s": 26946,
"text": "Where 11001 = 25"
},
{
"code": null,
"e": 26978,
"s": 26963,
"text": "And 1 for ‘-‘."
},
{
"code": null,
"e": 27075,
"s": 26978,
"text": "Range of number represented by sign magnitude method = -(2n-1-1) to +(2n-1-1) (for n bit number)"
},
{
"code": null,
"e": 27163,
"s": 27075,
"text": "But there is one problem in sign magnitude and that is we have two representations of 0"
},
{
"code": null,
"e": 27177,
"s": 27165,
"text": "+0 = 000000"
},
{
"code": null,
"e": 27190,
"s": 27177,
"text": "– 0 = 100000"
},
{
"code": null,
"e": 27214,
"s": 27192,
"text": "2’s complement method"
},
{
"code": null,
"e": 27379,
"s": 27214,
"text": "To represent a negative number in this form, first we need to take the 1’s complement of the number represented in simple positive binary form and then add 1 to it."
},
{
"code": null,
"e": 27392,
"s": 27379,
"text": "For example:"
},
{
"code": null,
"e": 27409,
"s": 27392,
"text": "(-8)10 = (1000)2"
},
{
"code": null,
"e": 27439,
"s": 27409,
"text": "1’s complement of 1000 = 0111"
},
{
"code": null,
"e": 27471,
"s": 27439,
"text": "Adding 1 to it, 0111 + 1 = 1000"
},
{
"code": null,
"e": 27492,
"s": 27471,
"text": "So, (-8)10 = (1000)2"
},
{
"code": null,
"e": 27651,
"s": 27492,
"text": "Please don’t get confused with (8)10 =1000 and (-8)10=1000 as with 4 bits, we can’t represent a positive number more than 7. So, 1000 is representing -8 only."
},
{
"code": null,
"e": 27721,
"s": 27653,
"text": "Range of number represented by 2’s complement = (-2n-1 to 2n-1 – 1)"
},
{
"code": null,
"e": 27764,
"s": 27723,
"text": "Floating point representation of numbers"
},
{
"code": null,
"e": 27823,
"s": 27764,
"text": "32-bit representation floating point numbers IEEE standard"
},
{
"code": null,
"e": 27837,
"s": 27823,
"text": "Normalization"
},
{
"code": null,
"e": 27883,
"s": 27837,
"text": "Floating point numbers are usually normalized"
},
{
"code": null,
"e": 27947,
"s": 27883,
"text": "Exponent is adjusted so that leading bit (MSB) of mantissa is 1"
},
{
"code": null,
"e": 27997,
"s": 27947,
"text": "Since it is always 1 there is no need to store it"
},
{
"code": null,
"e": 28134,
"s": 27997,
"text": "Scientific notation where numbers are normalized to give a single digit before the decimal point like in decimal system e.g. 3.123 x 103"
},
{
"code": null,
"e": 28184,
"s": 28134,
"text": "For example, we represent 3.625 in 32 bit format."
},
{
"code": null,
"e": 28208,
"s": 28184,
"text": "Changing 3 in binary=11"
},
{
"code": null,
"e": 28232,
"s": 28208,
"text": "Changing .625 in binary"
},
{
"code": null,
"e": 28286,
"s": 28232,
"text": ".625 X 2 1\n.25 X 2 0\n.5 X 2 1"
},
{
"code": null,
"e": 28304,
"s": 28286,
"text": ".625 X 2 1\n"
},
{
"code": null,
"e": 28323,
"s": 28304,
"text": ".25 X 2 0\n"
},
{
"code": null,
"e": 28342,
"s": 28323,
"text": ".5 X 2 1"
},
{
"code": null,
"e": 28374,
"s": 28342,
"text": "Writing in binary exponent form"
},
{
"code": null,
"e": 28392,
"s": 28374,
"text": "3.625=11.101 X 20"
},
{
"code": null,
"e": 28407,
"s": 28392,
"text": "On normalizing"
},
{
"code": null,
"e": 28431,
"s": 28407,
"text": "11.101 X 20=1.1101 X 21"
},
{
"code": null,
"e": 28467,
"s": 28431,
"text": "On biasing exponent = 127 + 1 = 128"
},
{
"code": null,
"e": 28488,
"s": 28467,
"text": "(128)10=(10000000) 2"
},
{
"code": null,
"e": 28512,
"s": 28488,
"text": "For getting significand"
},
{
"code": null,
"e": 28540,
"s": 28512,
"text": "Digits after decimal = 1101"
},
{
"code": null,
"e": 28586,
"s": 28540,
"text": "Expanding to 23 bit = 11010000000000000000000"
},
{
"code": null,
"e": 28603,
"s": 28586,
"text": "Setting sign bit"
},
{
"code": null,
"e": 28644,
"s": 28603,
"text": "As it is a positive number, sign bit = 0"
},
{
"code": null,
"e": 28691,
"s": 28644,
"text": "Finally we arrange according to representation"
},
{
"code": null,
"e": 28783,
"s": 28691,
"text": "Sign bit exponent significand\n\n0 10000000 11010000000000000000000"
},
{
"code": null,
"e": 28844,
"s": 28785,
"text": "64-bit representation floating point numbers IEEE standard"
},
{
"code": null,
"e": 28945,
"s": 28844,
"text": "Again we follow the same procedure upto normalization. After that, we add 1023 to bias the exponent."
},
{
"code": null,
"e": 28996,
"s": 28945,
"text": "For example, we represent -3.625 in 64 bit format."
},
{
"code": null,
"e": 29022,
"s": 28996,
"text": "Changing 3 in binary = 11"
},
{
"code": null,
"e": 29046,
"s": 29022,
"text": "Changing .625 in binary"
},
{
"code": null,
"e": 29097,
"s": 29046,
"text": "\n.625 X 2 1\n\n.25 X 2 0\n\n.5 X 2 1"
},
{
"code": null,
"e": 29131,
"s": 29099,
"text": "Writing in binary exponent form"
},
{
"code": null,
"e": 29151,
"s": 29131,
"text": "3.625 = 11.101 X 20"
},
{
"code": null,
"e": 29166,
"s": 29151,
"text": "On normalizing"
},
{
"code": null,
"e": 29192,
"s": 29166,
"text": "11.101 X 20 = 1.1101 X 21"
},
{
"code": null,
"e": 29228,
"s": 29192,
"text": "On biasing exponent 1023 + 1 = 1024"
},
{
"code": null,
"e": 29254,
"s": 29228,
"text": "(1024)10 = (10000000000)2"
},
{
"code": null,
"e": 29287,
"s": 29254,
"text": "So 11 bit exponent = 10000000000"
},
{
"code": null,
"e": 29356,
"s": 29287,
"text": "52 bit significand = 110100000000 ............. making total 52 bits"
},
{
"code": null,
"e": 29398,
"s": 29356,
"text": "Setting sign bit = 1 (number is negative)"
},
{
"code": null,
"e": 29423,
"s": 29398,
"text": "So, final representation"
},
{
"code": null,
"e": 29507,
"s": 29423,
"text": "1 10000000000 110100000000 ............. making total 52 bits by adding further 0’s"
},
{
"code": null,
"e": 29548,
"s": 29509,
"text": "Converting floating point into decimal"
},
{
"code": null,
"e": 29587,
"s": 29548,
"text": "Let’s convert a FP number into decimal"
},
{
"code": null,
"e": 29622,
"s": 29587,
"text": "1 01111100 11000000000000000000000"
},
{
"code": null,
"e": 29683,
"s": 29622,
"text": "The decimal value of an IEEE number is given by the formula:"
},
{
"code": null,
"e": 29717,
"s": 29683,
"text": "(1 -2s) * (1 + f) * 2( e – bias )"
},
{
"code": null,
"e": 29723,
"s": 29717,
"text": "where"
},
{
"code": null,
"e": 29768,
"s": 29723,
"text": "s, f and e fields are taken as decimal here."
},
{
"code": null,
"e": 29820,
"s": 29768,
"text": "(1 -2s) is 1 or -1, depending upon sign bit 0 and 1"
},
{
"code": null,
"e": 29891,
"s": 29820,
"text": "add an implicit 1 to the significand (fraction field f), as in formula"
},
{
"code": null,
"e": 29975,
"s": 29891,
"text": "Again, the bias is either 127 or 1023, for single or double precision respectively."
},
{
"code": null,
"e": 30025,
"s": 29977,
"text": "First convert each individual field to decimal."
},
{
"code": null,
"e": 30045,
"s": 30025,
"text": "The sign bit s is 1"
},
{
"code": null,
"e": 30085,
"s": 30045,
"text": "The e field contains 01111100 = (124)10"
},
{
"code": null,
"e": 30124,
"s": 30085,
"text": "The mantissa is 0.11000 ... = (0.75)10"
},
{
"code": null,
"e": 30156,
"s": 30124,
"text": "Putting these values in formula"
},
{
"code": null,
"e": 30221,
"s": 30156,
"text": "(1 – 2) * (1 + 0.75) * 2124 – 127 = ( – 1.75 * 2-3 ) = – 0.21875"
},
{
"code": null,
"e": 30275,
"s": 30225,
"text": "This article has been contributed by Anuj Batham."
},
{
"code": null,
"e": 30401,
"s": 30277,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 30419,
"s": 30401,
"text": "sachinsinghbisht5"
},
{
"code": null,
"e": 30456,
"s": 30419,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 30554,
"s": 30456,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30563,
"s": 30554,
"text": "Comments"
},
{
"code": null,
"e": 30576,
"s": 30563,
"text": "Old Comments"
},
{
"code": null,
"e": 30614,
"s": 30576,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 30631,
"s": 30614,
"text": "Addressing Modes"
},
{
"code": null,
"e": 30652,
"s": 30631,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 30701,
"s": 30652,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 30755,
"s": 30701,
"text": "Random Access Memory (RAM) and Read Only Memory (ROM)"
},
{
"code": null,
"e": 30850,
"s": 30755,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 30890,
"s": 30850,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 30928,
"s": 30890,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 30966,
"s": 30928,
"text": "8085 program to add two 8 bit numbers"
}
] |
Tryit Editor v3.7
|
Tryit: HTML style attribute
|
[] |
Math Operations on BigInteger in Java
|
Let us apply the following operations on BigInteger using the in-built methods in Java.
Addition: add() method
Subtraction: subtract() method
Multiplication: multiply() method
Division: divide() method
Let us create three BigInteger objects.
BigInteger one = new BigInteger("98765432123456789");
BigInteger two = new BigInteger("94353687526754387");
BigInteger three = new BigInteger("96489687526737667");
Apply mathematical operations on them.
one = one.add(two);
System.out.println("Addition Operation = " + one);
one = one.multiply(two);
System.out.println("Multiplication Operation = " + one);
The following is an example −
Live Demo
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
BigInteger one = new BigInteger("98765432123456789");
BigInteger two = new BigInteger("94353687526754387");
BigInteger three = new BigInteger("96489687526737667");
one = one.add(two);
System.out.println("Addition Operation = " + one);
one = one.multiply(two);
System.out.println("Multiplication Operation = " + one);
two = three.subtract(two);
System.out.println("Subtract Operation = " + two);
two = three.divide(two);
System.out.println("Division Operation = " + two);
}
}
Addition Operation = 193119119650211176
Multiplication Operation = 18221501070917918273532554434429112
Subtract Operation = 2135999999983280
Division Operation = 45
|
[
{
"code": null,
"e": 1150,
"s": 1062,
"text": "Let us apply the following operations on BigInteger using the in-built methods in Java."
},
{
"code": null,
"e": 1264,
"s": 1150,
"text": "Addition: add() method\nSubtraction: subtract() method\nMultiplication: multiply() method\nDivision: divide() method"
},
{
"code": null,
"e": 1304,
"s": 1264,
"text": "Let us create three BigInteger objects."
},
{
"code": null,
"e": 1468,
"s": 1304,
"text": "BigInteger one = new BigInteger(\"98765432123456789\");\nBigInteger two = new BigInteger(\"94353687526754387\");\nBigInteger three = new BigInteger(\"96489687526737667\");"
},
{
"code": null,
"e": 1507,
"s": 1468,
"text": "Apply mathematical operations on them."
},
{
"code": null,
"e": 1660,
"s": 1507,
"text": "one = one.add(two);\nSystem.out.println(\"Addition Operation = \" + one);\none = one.multiply(two);\nSystem.out.println(\"Multiplication Operation = \" + one);"
},
{
"code": null,
"e": 1690,
"s": 1660,
"text": "The following is an example −"
},
{
"code": null,
"e": 1701,
"s": 1690,
"text": " Live Demo"
},
{
"code": null,
"e": 2338,
"s": 1701,
"text": "import java.math.BigInteger;\npublic class Main {\n public static void main(String[] args) {\n BigInteger one = new BigInteger(\"98765432123456789\");\n BigInteger two = new BigInteger(\"94353687526754387\");\n BigInteger three = new BigInteger(\"96489687526737667\");\n one = one.add(two);\n System.out.println(\"Addition Operation = \" + one);\n one = one.multiply(two);\n System.out.println(\"Multiplication Operation = \" + one);\n two = three.subtract(two);\n System.out.println(\"Subtract Operation = \" + two);\n two = three.divide(two);\n System.out.println(\"Division Operation = \" + two);\n }\n}"
},
{
"code": null,
"e": 2503,
"s": 2338,
"text": "Addition Operation = 193119119650211176\nMultiplication Operation = 18221501070917918273532554434429112\nSubtract Operation = 2135999999983280\nDivision Operation = 45"
}
] |
Convert a Mobile Numeric Keypad sequence to equivalent sentence - GeeksforGeeks
|
28 Jan, 2022
Given a string S of size N, consisting of digits [0 – 9] and character ‘.’, the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence.
Note: ‘.’ represents a break while typing.
Below is the image to represent the characters associated with each number in the keypad.
Examples:
Input: S = “234”Output: ADGExplanation:Pressing the keys 2, 3, and 4 once gives the resultant string as “ADG”.
Input: S = “22.22”Output: BBExplanation:Pressing the key 2 twice gives B, and then again pressing the key twice gives B. Therefore, the resultant string is “BB”.
Approach: The given problem can be solved by storing the mobile keypad mappings in an array and then traverse the string S and convert it into its equivalent string. Follow the steps below to solve the problem:
Initialize an empty string, say ans to store the required result.
Store the string associated to each key in the mobile keypad in an array nums[] such that nums[i] represent the set of characters on pressing the digit i.
Traverse the given string S using the variable i and perform the following steps:If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration.Otherwise, initialize a variable cnt as 0 to store the count of the same characters.Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.Increment the value of cnt and i by 1.If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans.Otherwise, add the character nums[str[i]][cnt%3] to the string ans.Increment the value of i by 1.
If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration.
Otherwise, initialize a variable cnt as 0 to store the count of the same characters.
Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.Increment the value of cnt and i by 1.
If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.
If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.
Increment the value of cnt and i by 1.
If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans.
Otherwise, add the character nums[str[i]][cnt%3] to the string ans.
Increment the value of i by 1.
After completing the above steps, print the value string ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to convert mobile numeric// keypad sequence into its equivalent// stringvoid printSentence(string str){ // Store the mobile keypad mappings char nums[][5] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; // Traverse the string str int i = 0; while (str[i] != '\0') { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (str[i + 1] && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (str[i] == '\0') break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { cout << nums[str[i] - 48][count % 4]; } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { cout << nums[str[i] - 48][count % 3]; } i++; }} // Driver Codeint main(){ string str = "234"; printSentence(str); return 0;}
// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(String S) { // Store the mobile keypad mappings String nums[] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; char str[] = S.toCharArray(); // Traverse the string str int i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { System.out.print( nums[str[i] - 48].charAt(count % 4)); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { System.out.print( nums[str[i] - 48].charAt(count % 3)); } i++; } } // Driver Code public static void main(String[] args) { String str = "234"; printSentence(str); }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to convert mobile numeric# keypad sequence into its equivalent# stringdef printSentence(str1): # Store the mobile keypad mappings nums = [ "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" ] # Traverse the string str1 i = 0 while (i < len(str1)): # If the current character is # '.', then continue to the # next iteration if (str1[i] == '.'): i += 1 continue # Stores the number of # continuous clicks count = 0 # Iterate a loop to find the # count of same characters while (i + 1 < len(str1) and str1[i + 1] and str1[i] == str1[i + 1]): # 2, 3, 4, 5, 6 and 8 keys will # have maximum of 3 letters if (count == 2 and ((str1[i] >= '2' and str1[i] <= '6') or (str1[i] == '8'))): break # 7 and 9 keys will have # maximum of 4 keys elif (count == 3 and (str1[i] == '7' or str1[i] == '9')): break count += 1 i += 1 # Handle the end condition if (i < len(str)): break # Check if the current pressed # key is 7 or 9 if (str1[i] == '7' or str1[i] == '9'): print(nums[ord(str1[i]) - 48][count % 4], end = "") # Else, the key pressed is # either 2, 3, 4, 5, 6 or 8 else: print(nums[ord(str1[i]) - 48][count % 3], end = "") i += 1 # Driver Codeif __name__ == '__main__': str1 = "234" printSentence(str1) # This code is contributed by bgangwar59
// C# program for the above approachusing System;public class GFG{ // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(string S) { // Store the mobile keypad mappings string[] nums = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; char[] str = S.ToCharArray(); // Traverse the string str int i = 0; while (i < str.Length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.Length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.Length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { Console.Write(nums[str[i] - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { Console.Write(nums[str[i] - 48][count % 3]); } i++; } } // Driver Code public static void Main(string[] args) { string str = "234"; printSentence(str); }} // This code is contributed by ukasp.
<script> // Javascript program for the above approach // Function to convert mobile numeric// keypad sequence into its equivalent// stringfunction printSentence(S){ // Store the mobile keypad mappings let nums = [ "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]; let str = S.split(""); // Traverse the string str let i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks let count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { document.write( nums[str[i].charCodeAt(0) - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { document.write( nums[str[i].charCodeAt(0) - 48][count % 3]); } i++; }} // Driver Codelet str = "234"; printSentence(str); // This code is contributed by _saurabh_jaiswal. </script>
ADG
Time Complexity: O(N)Auxiliary Space: O(1)
Kingash
ukasp
bgangwar59
_saurabh_jaiswal
surinderdawra388
Amazon
interview-preparation
Backtracking
Hash
Mathematical
Strings
Amazon
Hash
Strings
Mathematical
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
The Knight's tour problem | Backtracking-1
Backtracking | Introduction
m Coloring Problem | Backtracking-5
Print all paths from a given source to a destination
Hamiltonian Cycle | Backtracking-6
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum
Hashing | Set 2 (Separate Chaining)
|
[
{
"code": null,
"e": 24904,
"s": 24876,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 25087,
"s": 24904,
"text": "Given a string S of size N, consisting of digits [0 – 9] and character ‘.’, the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence. "
},
{
"code": null,
"e": 25130,
"s": 25087,
"text": "Note: ‘.’ represents a break while typing."
},
{
"code": null,
"e": 25220,
"s": 25130,
"text": "Below is the image to represent the characters associated with each number in the keypad."
},
{
"code": null,
"e": 25231,
"s": 25220,
"text": "Examples: "
},
{
"code": null,
"e": 25342,
"s": 25231,
"text": "Input: S = “234”Output: ADGExplanation:Pressing the keys 2, 3, and 4 once gives the resultant string as “ADG”."
},
{
"code": null,
"e": 25504,
"s": 25342,
"text": "Input: S = “22.22”Output: BBExplanation:Pressing the key 2 twice gives B, and then again pressing the key twice gives B. Therefore, the resultant string is “BB”."
},
{
"code": null,
"e": 25715,
"s": 25504,
"text": "Approach: The given problem can be solved by storing the mobile keypad mappings in an array and then traverse the string S and convert it into its equivalent string. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 25781,
"s": 25715,
"text": "Initialize an empty string, say ans to store the required result."
},
{
"code": null,
"e": 25936,
"s": 25781,
"text": "Store the string associated to each key in the mobile keypad in an array nums[] such that nums[i] represent the set of characters on pressing the digit i."
},
{
"code": null,
"e": 26800,
"s": 25936,
"text": "Traverse the given string S using the variable i and perform the following steps:If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration.Otherwise, initialize a variable cnt as 0 to store the count of the same characters.Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.Increment the value of cnt and i by 1.If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans.Otherwise, add the character nums[str[i]][cnt%3] to the string ans.Increment the value of i by 1."
},
{
"code": null,
"e": 26884,
"s": 26800,
"text": "If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration."
},
{
"code": null,
"e": 26969,
"s": 26884,
"text": "Otherwise, initialize a variable cnt as 0 to store the count of the same characters."
},
{
"code": null,
"e": 27401,
"s": 26969,
"text": "Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.Increment the value of cnt and i by 1."
},
{
"code": null,
"e": 27565,
"s": 27401,
"text": "If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3."
},
{
"code": null,
"e": 27703,
"s": 27565,
"text": "If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4."
},
{
"code": null,
"e": 27742,
"s": 27703,
"text": "Increment the value of cnt and i by 1."
},
{
"code": null,
"e": 27830,
"s": 27742,
"text": "If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans."
},
{
"code": null,
"e": 27898,
"s": 27830,
"text": "Otherwise, add the character nums[str[i]][cnt%3] to the string ans."
},
{
"code": null,
"e": 27929,
"s": 27898,
"text": "Increment the value of i by 1."
},
{
"code": null,
"e": 28005,
"s": 27929,
"text": "After completing the above steps, print the value string ans as the result."
},
{
"code": null,
"e": 28056,
"s": 28005,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28060,
"s": 28056,
"text": "C++"
},
{
"code": null,
"e": 28065,
"s": 28060,
"text": "Java"
},
{
"code": null,
"e": 28073,
"s": 28065,
"text": "Python3"
},
{
"code": null,
"e": 28076,
"s": 28073,
"text": "C#"
},
{
"code": null,
"e": 28087,
"s": 28076,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to convert mobile numeric// keypad sequence into its equivalent// stringvoid printSentence(string str){ // Store the mobile keypad mappings char nums[][5] = { \"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\" }; // Traverse the string str int i = 0; while (str[i] != '\\0') { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (str[i + 1] && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (str[i] == '\\0') break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { cout << nums[str[i] - 48][count % 4]; } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { cout << nums[str[i] - 48][count % 3]; } i++; }} // Driver Codeint main(){ string str = \"234\"; printSentence(str); return 0;}",
"e": 29913,
"s": 28087,
"text": null
},
{
"code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; public class GFG { // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(String S) { // Store the mobile keypad mappings String nums[] = { \"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\" }; char str[] = S.toCharArray(); // Traverse the string str int i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { System.out.print( nums[str[i] - 48].charAt(count % 4)); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { System.out.print( nums[str[i] - 48].charAt(count % 3)); } i++; } } // Driver Code public static void main(String[] args) { String str = \"234\"; printSentence(str); }} // This code is contributed by Kingash.",
"e": 32180,
"s": 29913,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to convert mobile numeric# keypad sequence into its equivalent# stringdef printSentence(str1): # Store the mobile keypad mappings nums = [ \"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\" ] # Traverse the string str1 i = 0 while (i < len(str1)): # If the current character is # '.', then continue to the # next iteration if (str1[i] == '.'): i += 1 continue # Stores the number of # continuous clicks count = 0 # Iterate a loop to find the # count of same characters while (i + 1 < len(str1) and str1[i + 1] and str1[i] == str1[i + 1]): # 2, 3, 4, 5, 6 and 8 keys will # have maximum of 3 letters if (count == 2 and ((str1[i] >= '2' and str1[i] <= '6') or (str1[i] == '8'))): break # 7 and 9 keys will have # maximum of 4 keys elif (count == 3 and (str1[i] == '7' or str1[i] == '9')): break count += 1 i += 1 # Handle the end condition if (i < len(str)): break # Check if the current pressed # key is 7 or 9 if (str1[i] == '7' or str1[i] == '9'): print(nums[ord(str1[i]) - 48][count % 4], end = \"\") # Else, the key pressed is # either 2, 3, 4, 5, 6 or 8 else: print(nums[ord(str1[i]) - 48][count % 3], end = \"\") i += 1 # Driver Codeif __name__ == '__main__': str1 = \"234\" printSentence(str1) # This code is contributed by bgangwar59",
"e": 33960,
"s": 32180,
"text": null
},
{
"code": "// C# program for the above approachusing System;public class GFG{ // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(string S) { // Store the mobile keypad mappings string[] nums = { \"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\" }; char[] str = S.ToCharArray(); // Traverse the string str int i = 0; while (i < str.Length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.Length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.Length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { Console.Write(nums[str[i] - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { Console.Write(nums[str[i] - 48][count % 3]); } i++; } } // Driver Code public static void Main(string[] args) { string str = \"234\"; printSentence(str); }} // This code is contributed by ukasp.",
"e": 36126,
"s": 33960,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to convert mobile numeric// keypad sequence into its equivalent// stringfunction printSentence(S){ // Store the mobile keypad mappings let nums = [ \"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\"]; let str = S.split(\"\"); // Traverse the string str let i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks let count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { document.write( nums[str[i].charCodeAt(0) - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { document.write( nums[str[i].charCodeAt(0) - 48][count % 3]); } i++; }} // Driver Codelet str = \"234\"; printSentence(str); // This code is contributed by _saurabh_jaiswal. </script>",
"e": 38060,
"s": 36126,
"text": null
},
{
"code": null,
"e": 38064,
"s": 38060,
"text": "ADG"
},
{
"code": null,
"e": 38109,
"s": 38066,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38117,
"s": 38109,
"text": "Kingash"
},
{
"code": null,
"e": 38123,
"s": 38117,
"text": "ukasp"
},
{
"code": null,
"e": 38134,
"s": 38123,
"text": "bgangwar59"
},
{
"code": null,
"e": 38151,
"s": 38134,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 38168,
"s": 38151,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38175,
"s": 38168,
"text": "Amazon"
},
{
"code": null,
"e": 38197,
"s": 38175,
"text": "interview-preparation"
},
{
"code": null,
"e": 38210,
"s": 38197,
"text": "Backtracking"
},
{
"code": null,
"e": 38215,
"s": 38210,
"text": "Hash"
},
{
"code": null,
"e": 38228,
"s": 38215,
"text": "Mathematical"
},
{
"code": null,
"e": 38236,
"s": 38228,
"text": "Strings"
},
{
"code": null,
"e": 38243,
"s": 38236,
"text": "Amazon"
},
{
"code": null,
"e": 38248,
"s": 38243,
"text": "Hash"
},
{
"code": null,
"e": 38256,
"s": 38248,
"text": "Strings"
},
{
"code": null,
"e": 38269,
"s": 38256,
"text": "Mathematical"
},
{
"code": null,
"e": 38282,
"s": 38269,
"text": "Backtracking"
},
{
"code": null,
"e": 38380,
"s": 38282,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38423,
"s": 38380,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 38451,
"s": 38423,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 38487,
"s": 38451,
"text": "m Coloring Problem | Backtracking-5"
},
{
"code": null,
"e": 38540,
"s": 38487,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 38575,
"s": 38540,
"text": "Hamiltonian Cycle | Backtracking-6"
},
{
"code": null,
"e": 38611,
"s": 38575,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 38642,
"s": 38611,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 38676,
"s": 38642,
"text": "Hashing | Set 3 (Open Addressing)"
},
{
"code": null,
"e": 38703,
"s": 38676,
"text": "Count pairs with given sum"
}
] |
How to pass data between Activities on an Android application using Kotlin?
|
This example demonstrates how to pass data between Activities on an Android application using Kotlin.
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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnPassData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/btnReturnData"
android:layout_marginBottom="16dp"
android:text="Pass Data" />
<Button
android:id="@+id/btnReturnData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Pass Data And Get back data!" />
<TextView
android:id="@+id/resultDataTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnReturnData"
android:layout_marginTop="16dp"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private val myRequestCode = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
val button: Button = findViewById(R.id.btnPassData)
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra(
"message",
"Hi, there.."
)
startActivity(intent)
}
val passDataBack: Button = findViewById(R.id.btnReturnData)
passDataBack.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("message", "How are you?")
startActivityForResult(intent, myRequestCode)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
myRequestCode -> {
val textView: TextView = findViewById(R.id.resultDataTextView)
if (resultCode == RESULT_OK) {
val messageReturn = data!!.getStringExtra("messageReturn")
textView.text = messageReturn
}
}
}
}
}
Step 4 − Create a new empty Activity and add the following code −
activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:background="#008080"
android:padding="5dp"
android:text="TutorialsPoint"
android:textColor="#fff"
android:textSize="24sp"
android:textStyle="bold" />
<Button
android:id="@+id/btnReturnData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Pass Data Back To Main Activity" />
<TextView
android:id="@+id/tvReturnData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnReturnData"
android:layout_marginTop="8dp"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
SecondActivity.kt
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
title = "KotlinApp"
val intent = intent
val message = intent.getStringExtra("message")
val textView: TextView = findViewById(R.id.tvReturnData)
textView.text = message
val passDataTargetReturnDataButton: Button = findViewById(R.id.btnReturnData)
passDataTargetReturnDataButton.setOnClickListener {
val intent = Intent()
intent.putExtra(
"messageReturn",
"Doing good."
)
setResult(RESULT_OK, intent)
finish()
}
}
override fun onBackPressed() {
val intent = Intent()
intent.putExtra(
"messageReturn",
"You too have a nice day."
)
setResult(RESULT_OK, intent)
finish()
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the 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": 1164,
"s": 1062,
"text": "This example demonstrates how to pass data between Activities on an Android application using Kotlin."
},
{
"code": null,
"e": 1293,
"s": 1164,
"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": 1358,
"s": 1293,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2951,
"s": 1358,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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:padding=\"4dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/btnPassData\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/btnReturnData\"\n android:layout_marginBottom=\"16dp\"\n android:text=\"Pass Data\" />\n <Button\n android:id=\"@+id/btnReturnData\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Pass Data And Get back data!\" />\n <TextView\n android:id=\"@+id/resultDataTextView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnReturnData\"\n android:layout_marginTop=\"16dp\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3006,
"s": 2951,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4459,
"s": 3006,
"text": "import android.content.Intent\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n private val myRequestCode = 1\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n val button: Button = findViewById(R.id.btnPassData)\n button.setOnClickListener {\n val intent = Intent(this, SecondActivity::class.java)\n intent.putExtra(\n \"message\",\n \"Hi, there..\"\n )\n startActivity(intent)\n }\n val passDataBack: Button = findViewById(R.id.btnReturnData)\n passDataBack.setOnClickListener {\n val intent = Intent(this, SecondActivity::class.java)\n intent.putExtra(\"message\", \"How are you?\")\n startActivityForResult(intent, myRequestCode)\n }\n }\n override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {\n super.onActivityResult(requestCode, resultCode, data)\n when (requestCode) {\n myRequestCode -> {\n val textView: TextView = findViewById(R.id.resultDataTextView)\n if (resultCode == RESULT_OK) {\n val messageReturn = data!!.getStringExtra(\"messageReturn\")\n textView.text = messageReturn\n }\n }\n }\n }\n}"
},
{
"code": null,
"e": 4525,
"s": 4459,
"text": "Step 4 − Create a new empty Activity and add the following code −"
},
{
"code": null,
"e": 4545,
"s": 4525,
"text": "activity_second.xml"
},
{
"code": null,
"e": 5857,
"s": 4545,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout 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 tools:context=\".SecondActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/btnReturnData\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Pass Data Back To Main Activity\" />\n <TextView\n android:id=\"@+id/tvReturnData\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/btnReturnData\"\n android:layout_marginTop=\"8dp\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 5875,
"s": 5857,
"text": "SecondActivity.kt"
},
{
"code": null,
"e": 6971,
"s": 5875,
"text": "import android.content.Intent\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass SecondActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_second)\n title = \"KotlinApp\"\n val intent = intent\n val message = intent.getStringExtra(\"message\")\n val textView: TextView = findViewById(R.id.tvReturnData)\n textView.text = message\n val passDataTargetReturnDataButton: Button = findViewById(R.id.btnReturnData)\n passDataTargetReturnDataButton.setOnClickListener {\n val intent = Intent()\n intent.putExtra(\n \"messageReturn\",\n \"Doing good.\"\n )\n setResult(RESULT_OK, intent)\n finish()\n }\n }\n override fun onBackPressed() {\n val intent = Intent()\n intent.putExtra(\n \"messageReturn\",\n \"You too have a nice day.\"\n )\n setResult(RESULT_OK, intent)\n finish()\n }\n}"
},
{
"code": null,
"e": 7026,
"s": 6971,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 7700,
"s": 7026,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 8049,
"s": 7700,
"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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen."
}
] |
Bellman–Ford Algorithm for Shortest Paths
|
Bellman-Ford algorithm is used to find minimum distance from the source vertex to any other vertex. The main difference between this algorithm with Dijkstra’s the algorithm is, in Dijkstra’s algorithm we cannot handle the negative weight, but here we can handle it easily.
Bellman-Ford algorithm finds the distance in a bottom-up manner. At first, it finds those distances which have only one edge in the path. After that increase the path length to find all possible solutions.
Input:
The cost matrix of the graph:
0 6 ∞ 7 ∞
∞ 0 5 8 -4
∞ -2 0 ∞ ∞
∞ ∞ -3 0 9
2 ∞ 7 ∞ 0
Output:
Source Vertex: 2
Vert: 0 1 2 3 4
Dist: -4 -2 0 3 -6
Pred: 4 2 -1 0 1
The graph has no negative edge cycle
bellmanFord(dist, pred, source)
Input − Distance list, the predecessor list, and the source vertex.Output − True, when a negative cycle is found.
Begin
iCount := 1
maxEdge := n * (n - 1) / 2 //n is number of vertices
for all vertices v of the graph, do
dist[v] := ∞
pred[v] := φ
done
dist[source] := 0
eCount := number of edges present in the graph
create edge list named edgeList
while iCount < n, do
for i := 0 to eCount, do
if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i) dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i) pred[edgeList[i].v] := edgeList[i].u
done
done
iCount := iCount + 1
for all vertices i in the graph, do
if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i),
then return true
done
return false
End
#include<iostream>
#include<iomanip>
#define V 5
#define INF 999
using namespace std;
//Cost matrix of the graph (directed) vertex 5
int costMat[V][V] = {
{0, 6, INF, 7, INF},
{INF, 0, 5, 8, -4},
{INF, -2, 0, INF, INF},
{INF, INF, -3, 0, 9},
{2, INF, 7, INF, 0}
};
typedef struct {
int u, v, cost;
}edge;
int isDiagraph() {
//check the graph is directed graph or not
int i, j;
for(i = 0; i<V; i++) {
for(j = 0; j<V; j++) {
if(costMat[i][j] != costMat[j][i]) {
return 1; //graph is directed
}
}
}
return 0;//graph is undirected
}
int makeEdgeList(edge *eList) {
//create edgelist from the edges of graph
int count = -1;
if(isDiagraph()) {
for(int i = 0; i<V; i++) {
for(int j = 0; j<V; j++) {
if(costMat[i][j] != 0 && costMat[i][j] != INF) {
count++; //edge find when graph is directed
eList[count].u = i; eList[count].v = j;
eList[count].cost = costMat[i][j];
}
}
}
}else {
for(int i = 0; i<V; i++) {
for(int j = 0; j<i; j++) {
if(costMat[i][j] != INF) {
count++; //edge find when graph is undirected
eList[count].u = i; eList[count].v = j;
eList[count].cost = costMat[i][j];
}
}
}
}
return count+1;
}
int bellmanFord(int *dist, int *pred,int src) {
int icount = 1, ecount, max = V*(V-1)/2;
edge edgeList[max];
for(int i = 0; i<V; i++) {
dist[i] = INF; //initialize with infinity
pred[i] = -1; //no predecessor found.
}
dist[src] = 0;//for starting vertex, distance is 0
ecount = makeEdgeList(edgeList); //edgeList formation
while(icount < V) { //number of iteration is (Vertex - 1)
for(int i = 0; i<ecount; i++) {
if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]) { //relax edge and set predecessor
dist[edgeList[i].v] = dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v];
pred[edgeList[i].v] = edgeList[i].u;
}
}
icount++;
}
//test for negative cycle
for(int i = 0; i<ecount; i++) {
if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]) {
return 1; //indicates the graph has negative cycle
}
}
return 0; //no negative cycle
}
void display(int *dist, int *pred) {
cout << "Vert: ";
for(int i = 0; i<V; i++)
cout <<setw(3) << i << " ";
cout << endl;
cout << "Dist: ";
for(int i = 0; i<V; i++)
cout << setw(3) << dist[i] << " ";
cout << endl;
cout << "Pred: ";
for(int i = 0; i<V; i++)
cout << setw(3) << pred[i] << " ";
cout << endl;
}
int main() {
int dist[V], pred[V], source, report;
source = 2;
report = bellmanFord(dist, pred, source);
cout << "Source Vertex: " << source<<endl;
display(dist, pred);
if(report)
cout << "The graph has a negative edge cycle" << endl;
else
cout << "The graph has no negative edge cycle" << endl;
}
Source Vertex: 2
Vert: 0 1 2 3 4
Dist: -4 -2 0 3 -6
Pred: 4 2 -1 0 1
The graph has no negative edge cycle
|
[
{
"code": null,
"e": 1335,
"s": 1062,
"text": "Bellman-Ford algorithm is used to find minimum distance from the source vertex to any other vertex. The main difference between this algorithm with Dijkstra’s the algorithm is, in Dijkstra’s algorithm we cannot handle the negative weight, but here we can handle it easily."
},
{
"code": null,
"e": 1541,
"s": 1335,
"text": "Bellman-Ford algorithm finds the distance in a bottom-up manner. At first, it finds those distances which have only one edge in the path. After that increase the path length to find all possible solutions."
},
{
"code": null,
"e": 1784,
"s": 1541,
"text": "Input:\nThe cost matrix of the graph:\n0 6 ∞ 7 ∞\n∞ 0 5 8 -4\n∞ -2 0 ∞ ∞\n∞ ∞ -3 0 9\n2 ∞ 7 ∞ 0\n\nOutput:\nSource Vertex: 2\nVert: 0 1 2 3 4\nDist: -4 -2 0 3 -6\nPred: 4 2 -1 0 1\nThe graph has no negative edge cycle"
},
{
"code": null,
"e": 1816,
"s": 1784,
"text": "bellmanFord(dist, pred, source)"
},
{
"code": null,
"e": 1930,
"s": 1816,
"text": "Input − Distance list, the predecessor list, and the source vertex.Output − True, when a negative cycle is found."
},
{
"code": null,
"e": 2658,
"s": 1930,
"text": "Begin\n iCount := 1\n maxEdge := n * (n - 1) / 2 //n is number of vertices\n\n for all vertices v of the graph, do\n dist[v] := ∞\n pred[v] := φ\n done\n\n dist[source] := 0\n eCount := number of edges present in the graph\n create edge list named edgeList\n\n while iCount < n, do\n for i := 0 to eCount, do\n if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i) dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i) pred[edgeList[i].v] := edgeList[i].u\n done\n done\n\n iCount := iCount + 1\n for all vertices i in the graph, do\n if dist[edgeList[i].v] > dist[edgeList[i].u] + (cost[u,v] for edge i),\n then return true\n done\n\n return false\nEnd"
},
{
"code": null,
"e": 5840,
"s": 2658,
"text": "#include<iostream>\n#include<iomanip>\n#define V 5\n#define INF 999\nusing namespace std;\n//Cost matrix of the graph (directed) vertex 5\n\nint costMat[V][V] = {\n {0, 6, INF, 7, INF},\n {INF, 0, 5, 8, -4},\n {INF, -2, 0, INF, INF},\n {INF, INF, -3, 0, 9},\n {2, INF, 7, INF, 0}\n};\n\ntypedef struct {\n int u, v, cost;\n}edge;\n\nint isDiagraph() {\n\n //check the graph is directed graph or not\n\n int i, j;\n for(i = 0; i<V; i++) {\n for(j = 0; j<V; j++) {\n if(costMat[i][j] != costMat[j][i]) {\n return 1; //graph is directed\n }\n }\n }\n return 0;//graph is undirected\n}\n\nint makeEdgeList(edge *eList) {\n //create edgelist from the edges of graph\n int count = -1;\n if(isDiagraph()) {\n for(int i = 0; i<V; i++) {\n for(int j = 0; j<V; j++) {\n if(costMat[i][j] != 0 && costMat[i][j] != INF) {\n count++; //edge find when graph is directed\n eList[count].u = i; eList[count].v = j;\n eList[count].cost = costMat[i][j];\n }\n }\n }\n }else {\n for(int i = 0; i<V; i++) {\n for(int j = 0; j<i; j++) {\n if(costMat[i][j] != INF) {\n count++; //edge find when graph is undirected\n eList[count].u = i; eList[count].v = j;\n eList[count].cost = costMat[i][j];\n }\n }\n }\n }\n return count+1;\n}\n\nint bellmanFord(int *dist, int *pred,int src) {\n int icount = 1, ecount, max = V*(V-1)/2;\n edge edgeList[max];\n\n for(int i = 0; i<V; i++) {\n dist[i] = INF; //initialize with infinity\n pred[i] = -1; //no predecessor found.\n }\n\n dist[src] = 0;//for starting vertex, distance is 0\n\n ecount = makeEdgeList(edgeList); //edgeList formation\n\n while(icount < V) { //number of iteration is (Vertex - 1)\n for(int i = 0; i<ecount; i++) {\n if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]) { //relax edge and set predecessor\n dist[edgeList[i].v] = dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v];\n pred[edgeList[i].v] = edgeList[i].u;\n }\n }\n icount++;\n }\n\n //test for negative cycle\n for(int i = 0; i<ecount; i++) {\n if(dist[edgeList[i].v] > dist[edgeList[i].u] + costMat[edgeList[i].u][edgeList[i].v]) {\n return 1; //indicates the graph has negative cycle\n }\n }\n\n return 0; //no negative cycle\n}\n\nvoid display(int *dist, int *pred) {\n cout << \"Vert: \";\n for(int i = 0; i<V; i++)\n cout <<setw(3) << i << \" \";\n cout << endl;\n cout << \"Dist: \";\n\n for(int i = 0; i<V; i++)\n cout << setw(3) << dist[i] << \" \";\n cout << endl;\n cout << \"Pred: \";\n\n for(int i = 0; i<V; i++)\n cout << setw(3) << pred[i] << \" \";\n cout << endl;\n}\n\nint main() {\n int dist[V], pred[V], source, report;\n source = 2;\n report = bellmanFord(dist, pred, source);\n cout << \"Source Vertex: \" << source<<endl;\n display(dist, pred);\n\n if(report)\n cout << \"The graph has a negative edge cycle\" << endl;\n else\n cout << \"The graph has no negative edge cycle\" << endl;\n}"
},
{
"code": null,
"e": 5972,
"s": 5840,
"text": "Source Vertex: 2\nVert: 0 1 2 3 4\nDist: -4 -2 0 3 -6\nPred: 4 2 -1 0 1\nThe graph has no negative edge cycle"
}
] |
Display multiple lines of text in a component’s tooltip with Java
|
Let’s first see how we set text in a components tooltip −
JLabel label3 = new JLabel("Password", SwingConstants.CENTER);
label3.setToolTipText("Enter Password");
To display multiple lines of text in a tooltip, use <html>. Here, we have used the HTML <br> tag for new
line and that would create multiple lines of text in the tooltip −
label3.setToolTipText("<html>" + "This will create multiple lines for the" + "<br>" + "component! Yay!" + "</html>");
The following is an example to display multiple lines of text in a component’s tooltip −
package my;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.ToolTipManager;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Register!");
JLabel label1, label2, label3;
frame.setLayout(new GridLayout(2, 2));
label1 = new JLabel("Id", SwingConstants.CENTER);
label1.setToolTipText("<html>" + "Add the id given to you" + "<br>" + "in the beginning!" + "</html>");
label2 = new JLabel("Rank", SwingConstants.CENTER);
label2.setToolTipText("Enter rank");
label3 = new JLabel("Password", SwingConstants.CENTER);
label3.setToolTipText("Enter Password");
ToolTipManager.sharedInstance().setEnabled(false);
JTextField emailId = new JTextField(20);
JTextField rank = new JTextField(20);
JPasswordField passwd = new JPasswordField();
passwd.setEchoChar('*');
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(emailId);
frame.add(rank);
frame.add(passwd);
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
int width = 500;
int height = 200;
frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);
frame.setVisible(true);
}
}
The output is as follows. Here, we are displaying the multi-line tooltip text visible on mouse hover −
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Let’s first see how we set text in a components tooltip −"
},
{
"code": null,
"e": 1224,
"s": 1120,
"text": "JLabel label3 = new JLabel(\"Password\", SwingConstants.CENTER);\nlabel3.setToolTipText(\"Enter Password\");"
},
{
"code": null,
"e": 1396,
"s": 1224,
"text": "To display multiple lines of text in a tooltip, use <html>. Here, we have used the HTML <br> tag for new\nline and that would create multiple lines of text in the tooltip −"
},
{
"code": null,
"e": 1514,
"s": 1396,
"text": "label3.setToolTipText(\"<html>\" + \"This will create multiple lines for the\" + \"<br>\" + \"component! Yay!\" + \"</html>\");"
},
{
"code": null,
"e": 1603,
"s": 1514,
"text": "The following is an example to display multiple lines of text in a component’s tooltip −"
},
{
"code": null,
"e": 3171,
"s": 1603,
"text": "package my;\nimport java.awt.GraphicsEnvironment;\nimport java.awt.GridLayout;\nimport java.awt.Point;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPasswordField;\nimport javax.swing.JTextField;\nimport javax.swing.SwingConstants;\nimport javax.swing.ToolTipManager;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame.setDefaultLookAndFeelDecorated(true);\n JFrame frame = new JFrame(\"Register!\");\n JLabel label1, label2, label3;\n frame.setLayout(new GridLayout(2, 2));\n label1 = new JLabel(\"Id\", SwingConstants.CENTER);\n label1.setToolTipText(\"<html>\" + \"Add the id given to you\" + \"<br>\" + \"in the beginning!\" + \"</html>\");\n label2 = new JLabel(\"Rank\", SwingConstants.CENTER);\n label2.setToolTipText(\"Enter rank\");\n label3 = new JLabel(\"Password\", SwingConstants.CENTER);\n label3.setToolTipText(\"Enter Password\");\n ToolTipManager.sharedInstance().setEnabled(false);\n JTextField emailId = new JTextField(20);\n JTextField rank = new JTextField(20);\n JPasswordField passwd = new JPasswordField();\n passwd.setEchoChar('*');\n frame.add(label1);\n frame.add(label2);\n frame.add(label3);\n frame.add(emailId);\n frame.add(rank);\n frame.add(passwd);\n Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();\n int width = 500;\n int height = 200;\n frame.setBounds(center.x - width / 2, center.y - height / 2, width, height);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3274,
"s": 3171,
"text": "The output is as follows. Here, we are displaying the multi-line tooltip text visible on mouse hover −"
}
] |
Tilt of Binary Tree | Practice | GeeksforGeeks
|
Given a binary tree of size N+1, your task is to complete the function tiltTree(), that return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.
Examples 1:
Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
Example 2:
Input:
4
/ \
2 9
/ \ \
3 5 7
Output: 15
Explanation:
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15
Your Task:
You don't need to read input or print anything. Your task is to complete the function tiltTree() which takes root node of the tree as input parameter and returns an integer denoting the tilt of the tree. If the tree is empty, return 0.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1<=T<=100
0<=N<=500
0
rampurnaveen91 month ago
int solve(Node *root) { if(root==NULL) { return 0; } int s; s = root->data + solve(root->left) +solve(root->right); return s; } int check(Node *root,int &sum) { if(root == NULL) return 0; sum = sum + abs(solve(root->left)-solve(root->right)); check(root->left,sum); check(root->right,sum); } int tiltTree(Node *root) { int sum = 0; check(root,sum); return sum; }
0
tarun2002ts0212 months ago
int c(Node * root,int &ans){ if(!root) return NULL; int lsum = c(root->left,ans); int rsum = c(root->right,ans); ans+=abs(lsum-rsum); return root->data + lsum + rsum; } int tiltTree(Node *root) { int ans=0; c(root,ans); return ans; }
+2
rdm1233 months ago
int hel(Node *root,int &a){ if(!root) return 0; int l=hel(root->left,a); int r=hel(root->right,a); a+=abs(r-l); return l+r+root->data; } int tiltTree(Node *root) { int a=0; hel(root,a); return a; //code here }
0
nekhatperveen3 months ago
JAVA
public int tiltTree(Node root) { if(root==null)return 0; int rootNode_tilt = nodetilt(root); int tree_tilt= rootNode_tilt+tiltTree(root.left)+tiltTree(root.right); return tree_tilt; } static int nodetilt(Node root) { if(root==null)return 0; int node_tilt = Math.abs(sum_subtree(root.left)-sum_subtree(root.right)); return node_tilt; } static int sum_subtree(Node root) { if(root==null)return 0; int sum = root.data+sum_subtree(root.left)+sum_subtree(root.right); return sum; }
+1
hydracody454 months ago
int ans=0; int s(Node* root){ if(root==NULL){ return 0; } int x=s(root->left); int y=s(root->right); ans+=abs(x-y); return root->data+x+y; } int tiltTree(Node *root) { //code here s(root); return ans; }
0
kake13375 months ago
int tilt(Node *root, int &s) { if(root==NULL) return 0; int x=tilt(root->left,s); int y=tilt(root->right,s); s+=abs(x-y); return x+y+root->data; } int tiltTree(Node *root) { int tsum=0; tilt(root,tsum); return tsum; }
+1
amitkumar3004206 months ago
class Solution{public: // Your are required to complete this function // function should return the tilt of the tree int sumTree(Node *root) { if(root==NULL) return 0; return sumTree(root->left)+sumTree(root->right)+root->data; } int tiltTree(Node *root) { int sum=0; if(root==NULL) return 0; sum +=abs(sumTree(root->left)-sumTree(root->right)); int l = tiltTree(root->left); int r = tiltTree(root->right); return sum+r+l; //code here }};
0
Abhijit roy7 months ago
Abhijit roy
So, recursive function we will write like this...
Step1) If there is no parent, what the hell we are talking bout children then...Return 0
Step2) Make two children, indicating the two children of the dad(parent)...Now, trust in the recursion leap of faith and just recur to the left and right and store in their respective variables...We trust recursion and assume that both children(left and right child) have got their values...
Step3) Now we find the absolute difference of left and right values and store it.
Step4) Well...Now when each child is going to return the value he got to his dad....well he's gonna return his own two childrens+himself since he is also the child of the root...
int helper(Node* root, int &ans){ if(root==NULL){ return 0; } int leftsubtree=helper(root->left,ans); int rightsubtree=helper(root->right,ans); ans+= abs(leftsubtree-rightsubtree); return root->data+rightsubtree+leftsubtree; } int tiltTree(Node *root) { int ans=0; helper(root,ans); return ans; }
https://media2.giphy.com/me...
0
Abhijit roy7 months ago
Abhijit roy
..
0
jasmeen kaur8 months ago
jasmeen kaur
int c(Node * root,int &ans){ if(!root) return NULL; int lsum = c(root->left,ans); int rsum = c(root->right,ans); ans+=abs(lsum-rsum); return root->data + lsum + rsum; } int tiltTree(Node *root) { int ans=0; c(root,ans); return ans; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 634,
"s": 238,
"text": "Given a binary tree of size N+1, your task is to complete the function tiltTree(), that return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt."
},
{
"code": null,
"e": 646,
"s": 634,
"text": "Examples 1:"
},
{
"code": null,
"e": 809,
"s": 646,
"text": "Input: \n 1\n / \\\n 2 3\nOutput: 1\nExplanation:\nTilt of node 2 : 0\nTilt of node 3 : 0\nTilt of node 1 : |2-3| = 1\nTilt of binary tree : 0 + 0 + 1 = 1\n"
},
{
"code": null,
"e": 820,
"s": 809,
"text": "Example 2:"
},
{
"code": null,
"e": 1118,
"s": 820,
"text": "Input:\n 4 \n / \\\n 2 9 \n / \\ \\\n 3 5 7 \nOutput: 15 \nExplanation:\nTilt of node 3 : 0 \nTilt of node 5 : 0 \nTilt of node 7 : 0\nTilt of node 2 : |3-5| = 2 \nTilt of node 9 : |0-7| = 7 \nTilt of node 4 : |(3+5+2)-(9+7)| = 6 \nTilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15\n"
},
{
"code": null,
"e": 1366,
"s": 1118,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function tiltTree() which takes root node of the tree as input parameter and returns an integer denoting the tilt of the tree. If the tree is empty, return 0. "
},
{
"code": null,
"e": 1463,
"s": 1366,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\nConstraints:\n1<=T<=100\n0<=N<=500\n "
},
{
"code": null,
"e": 1465,
"s": 1463,
"text": "0"
},
{
"code": null,
"e": 1490,
"s": 1465,
"text": "rampurnaveen91 month ago"
},
{
"code": null,
"e": 1979,
"s": 1490,
"text": "int solve(Node *root) { if(root==NULL) { return 0; } int s; s = root->data + solve(root->left) +solve(root->right); return s; } int check(Node *root,int &sum) { if(root == NULL) return 0; sum = sum + abs(solve(root->left)-solve(root->right)); check(root->left,sum); check(root->right,sum); } int tiltTree(Node *root) { int sum = 0; check(root,sum); return sum; }"
},
{
"code": null,
"e": 1981,
"s": 1979,
"text": "0"
},
{
"code": null,
"e": 2008,
"s": 1981,
"text": "tarun2002ts0212 months ago"
},
{
"code": null,
"e": 2320,
"s": 2008,
"text": " int c(Node * root,int &ans){ if(!root) return NULL; int lsum = c(root->left,ans); int rsum = c(root->right,ans); ans+=abs(lsum-rsum); return root->data + lsum + rsum; } int tiltTree(Node *root) { int ans=0; c(root,ans); return ans; }"
},
{
"code": null,
"e": 2323,
"s": 2320,
"text": "+2"
},
{
"code": null,
"e": 2342,
"s": 2323,
"text": "rdm1233 months ago"
},
{
"code": null,
"e": 2614,
"s": 2342,
"text": "int hel(Node *root,int &a){ if(!root) return 0; int l=hel(root->left,a); int r=hel(root->right,a); a+=abs(r-l); return l+r+root->data; } int tiltTree(Node *root) { int a=0; hel(root,a); return a; //code here }"
},
{
"code": null,
"e": 2616,
"s": 2614,
"text": "0"
},
{
"code": null,
"e": 2642,
"s": 2616,
"text": "nekhatperveen3 months ago"
},
{
"code": null,
"e": 2647,
"s": 2642,
"text": "JAVA"
},
{
"code": null,
"e": 3216,
"s": 2647,
"text": " public int tiltTree(Node root) { if(root==null)return 0; int rootNode_tilt = nodetilt(root); int tree_tilt= rootNode_tilt+tiltTree(root.left)+tiltTree(root.right); return tree_tilt; } static int nodetilt(Node root) { if(root==null)return 0; int node_tilt = Math.abs(sum_subtree(root.left)-sum_subtree(root.right)); return node_tilt; } static int sum_subtree(Node root) { if(root==null)return 0; int sum = root.data+sum_subtree(root.left)+sum_subtree(root.right); return sum; }"
},
{
"code": null,
"e": 3219,
"s": 3216,
"text": "+1"
},
{
"code": null,
"e": 3243,
"s": 3219,
"text": "hydracody454 months ago"
},
{
"code": null,
"e": 3520,
"s": 3243,
"text": "int ans=0; int s(Node* root){ if(root==NULL){ return 0; } int x=s(root->left); int y=s(root->right); ans+=abs(x-y); return root->data+x+y; } int tiltTree(Node *root) { //code here s(root); return ans; }"
},
{
"code": null,
"e": 3522,
"s": 3520,
"text": "0"
},
{
"code": null,
"e": 3543,
"s": 3522,
"text": "kake13375 months ago"
},
{
"code": null,
"e": 3827,
"s": 3543,
"text": " int tilt(Node *root, int &s) { if(root==NULL) return 0; int x=tilt(root->left,s); int y=tilt(root->right,s); s+=abs(x-y); return x+y+root->data; } int tiltTree(Node *root) { int tsum=0; tilt(root,tsum); return tsum; }"
},
{
"code": null,
"e": 3830,
"s": 3827,
"text": "+1"
},
{
"code": null,
"e": 3858,
"s": 3830,
"text": "amitkumar3004206 months ago"
},
{
"code": null,
"e": 4406,
"s": 3858,
"text": "class Solution{public: // Your are required to complete this function // function should return the tilt of the tree int sumTree(Node *root) { if(root==NULL) return 0; return sumTree(root->left)+sumTree(root->right)+root->data; } int tiltTree(Node *root) { int sum=0; if(root==NULL) return 0; sum +=abs(sumTree(root->left)-sumTree(root->right)); int l = tiltTree(root->left); int r = tiltTree(root->right); return sum+r+l; //code here }};"
},
{
"code": null,
"e": 4408,
"s": 4406,
"text": "0"
},
{
"code": null,
"e": 4432,
"s": 4408,
"text": "Abhijit roy7 months ago"
},
{
"code": null,
"e": 4444,
"s": 4432,
"text": "Abhijit roy"
},
{
"code": null,
"e": 4494,
"s": 4444,
"text": "So, recursive function we will write like this..."
},
{
"code": null,
"e": 4583,
"s": 4494,
"text": "Step1) If there is no parent, what the hell we are talking bout children then...Return 0"
},
{
"code": null,
"e": 4875,
"s": 4583,
"text": "Step2) Make two children, indicating the two children of the dad(parent)...Now, trust in the recursion leap of faith and just recur to the left and right and store in their respective variables...We trust recursion and assume that both children(left and right child) have got their values..."
},
{
"code": null,
"e": 4957,
"s": 4875,
"text": "Step3) Now we find the absolute difference of left and right values and store it."
},
{
"code": null,
"e": 5136,
"s": 4957,
"text": "Step4) Well...Now when each child is going to return the value he got to his dad....well he's gonna return his own two childrens+himself since he is also the child of the root..."
},
{
"code": null,
"e": 5524,
"s": 5136,
"text": "int helper(Node* root, int &ans){ if(root==NULL){ return 0; } int leftsubtree=helper(root->left,ans); int rightsubtree=helper(root->right,ans); ans+= abs(leftsubtree-rightsubtree); return root->data+rightsubtree+leftsubtree; } int tiltTree(Node *root) { int ans=0; helper(root,ans); return ans; }"
},
{
"code": null,
"e": 5555,
"s": 5524,
"text": "https://media2.giphy.com/me..."
},
{
"code": null,
"e": 5557,
"s": 5555,
"text": "0"
},
{
"code": null,
"e": 5581,
"s": 5557,
"text": "Abhijit roy7 months ago"
},
{
"code": null,
"e": 5593,
"s": 5581,
"text": "Abhijit roy"
},
{
"code": null,
"e": 5596,
"s": 5593,
"text": ".."
},
{
"code": null,
"e": 5598,
"s": 5596,
"text": "0"
},
{
"code": null,
"e": 5623,
"s": 5598,
"text": "jasmeen kaur8 months ago"
},
{
"code": null,
"e": 5636,
"s": 5623,
"text": "jasmeen kaur"
},
{
"code": null,
"e": 5963,
"s": 5636,
"text": " int c(Node * root,int &ans){ if(!root) return NULL; int lsum = c(root->left,ans); int rsum = c(root->right,ans); ans+=abs(lsum-rsum); return root->data + lsum + rsum; } int tiltTree(Node *root) { int ans=0; c(root,ans); return ans; }"
},
{
"code": null,
"e": 6109,
"s": 5963,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6145,
"s": 6109,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6155,
"s": 6145,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6165,
"s": 6155,
"text": "\nContest\n"
},
{
"code": null,
"e": 6228,
"s": 6165,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6376,
"s": 6228,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6584,
"s": 6376,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6690,
"s": 6584,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Connection getClientInfo() method with example
|
The getClientInfo() method of the Connection interface returns the name and values of the client info properties of the current connection. This method returns a properties object.
To retrieve the values of the client info properties file.
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Create a properties object as −
Properties properties = new Properties();
Add the required key-value pairs to the above created Properties object as −
properties.put("user_name", "new_user");
properties.put("password", "password");
Set the above created properties to the client-info using the setClientInfo() method as −
//Setting the Client Info
con.setClientInfo(properties);
Retrieve the Properties file (object) using the getClientInfo() method and get properties from it by invoking the getProperty() method as −
Properties prop = con.getClientInfo();
prop.getProperty("user_name");
prop.getProperty("password");
You can also directly get the properties as:
con.getClientInfo("user_name");
con.getClientInfo("password");
Following JDBC program establishes connection with the MYSQL database and sets the credentials of a new user to the client info properties file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connection_getClientInfo {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("Connection established......");
//Adding the credentials of another user to the properties file
Properties properties = new Properties();
properties.put("user_name", "new_user");
properties.put("password", "my_password");
//Setting the ClientInfo
con.setClientInfo(properties);
//Retrieving the values in the ClientInfo properties file
Properties prop = con.getClientInfo();
System.out.println("user name: "+prop.getProperty("user_name"));
System.out.println("password: "+prop.getProperty("password"));
}
}
Connection established......
user name: new_user
password: my_password
|
[
{
"code": null,
"e": 1243,
"s": 1062,
"text": "The getClientInfo() method of the Connection interface returns the name and values of the client info properties of the current connection. This method returns a properties object."
},
{
"code": null,
"e": 1302,
"s": 1243,
"text": "To retrieve the values of the client info properties file."
},
{
"code": null,
"e": 1388,
"s": 1302,
"text": "Register the driver using the registerDriver() method of the DriverManager class as −"
},
{
"code": null,
"e": 1472,
"s": 1388,
"text": "//Registering the Driver\nDriverManager.registerDriver(new com.mysql.jdbc.Driver());"
},
{
"code": null,
"e": 1556,
"s": 1472,
"text": "Get the connection using the getConnection() method of the DriverManager class as −"
},
{
"code": null,
"e": 1702,
"s": 1556,
"text": "//Getting the connection\nString url = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(url, \"root\", \"password\");"
},
{
"code": null,
"e": 1734,
"s": 1702,
"text": "Create a properties object as −"
},
{
"code": null,
"e": 1776,
"s": 1734,
"text": "Properties properties = new Properties();"
},
{
"code": null,
"e": 1853,
"s": 1776,
"text": "Add the required key-value pairs to the above created Properties object as −"
},
{
"code": null,
"e": 1934,
"s": 1853,
"text": "properties.put(\"user_name\", \"new_user\");\nproperties.put(\"password\", \"password\");"
},
{
"code": null,
"e": 2024,
"s": 1934,
"text": "Set the above created properties to the client-info using the setClientInfo() method as −"
},
{
"code": null,
"e": 2081,
"s": 2024,
"text": "//Setting the Client Info\ncon.setClientInfo(properties);"
},
{
"code": null,
"e": 2221,
"s": 2081,
"text": "Retrieve the Properties file (object) using the getClientInfo() method and get properties from it by invoking the getProperty() method as −"
},
{
"code": null,
"e": 2429,
"s": 2221,
"text": "Properties prop = con.getClientInfo();\nprop.getProperty(\"user_name\");\nprop.getProperty(\"password\");\nYou can also directly get the properties as:\ncon.getClientInfo(\"user_name\");\ncon.getClientInfo(\"password\");"
},
{
"code": null,
"e": 2574,
"s": 2429,
"text": "Following JDBC program establishes connection with the MYSQL database and sets the credentials of a new user to the client info properties file."
},
{
"code": null,
"e": 3652,
"s": 2574,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.Properties;\npublic class Connection_getClientInfo {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Adding the credentials of another user to the properties file\n Properties properties = new Properties();\n properties.put(\"user_name\", \"new_user\");\n properties.put(\"password\", \"my_password\");\n //Setting the ClientInfo\n con.setClientInfo(properties);\n //Retrieving the values in the ClientInfo properties file\n Properties prop = con.getClientInfo();\n System.out.println(\"user name: \"+prop.getProperty(\"user_name\"));\n System.out.println(\"password: \"+prop.getProperty(\"password\"));\n }\n}"
},
{
"code": null,
"e": 3723,
"s": 3652,
"text": "Connection established......\nuser name: new_user\npassword: my_password"
}
] |
Query to find Nth maximum value in MySQL
|
Let us first create a table −
mysql> create table DemoTable
-> (
-> Value int
-> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(85);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output−
+-------+
| Value |
+-------+
| 40 |
| 60 |
| 45 |
| 85 |
| 78 |
+-------+
5 rows in set (0.00 sec)
Following is the query to find Nth maximum value in MySQL −
mysql> select * from DemoTable order by Value desc limit 2,1;
This will produce the following output −
+-------+
| Value |
+-------+
| 60 |
+-------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1192,
"s": 1092,
"text": "mysql> create table DemoTable\n -> (\n -> Value int\n -> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1248,
"s": 1192,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1633,
"s": 1248,
"text": "mysql> insert into DemoTable values(40);\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into DemoTable values(60);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values(45);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values(85);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values(78);\nQuery OK, 1 row affected (0.10 sec)"
},
{
"code": null,
"e": 1693,
"s": 1633,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1725,
"s": 1693,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1765,
"s": 1725,
"text": "This will produce the following output−"
},
{
"code": null,
"e": 1880,
"s": 1765,
"text": "+-------+\n| Value |\n+-------+\n| 40 |\n| 60 |\n| 45 |\n| 85 |\n| 78 |\n+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1940,
"s": 1880,
"text": "Following is the query to find Nth maximum value in MySQL −"
},
{
"code": null,
"e": 2002,
"s": 1940,
"text": "mysql> select * from DemoTable order by Value desc limit 2,1;"
},
{
"code": null,
"e": 2043,
"s": 2002,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2117,
"s": 2043,
"text": "+-------+\n| Value |\n+-------+\n| 60 |\n+-------+\n1 row in set (0.00 sec)"
}
] |
Serving ML Models in Production with FastAPI and Celery | by Jonathan Readshaw | Towards Data Science
|
There is an abundance of material online related to building and training all kinds of machine learning models. However once a high performance model has been trained there is significantly less material for how to put it into production.
This post walks through a working example for serving a ML model using Celery and FastAPI. All code can be found in the repository here.
We won’t specifically discuss the ML model used for this example however it was trained using example Bank customer churn data (https://www.kaggle.com/sakshigoyal7/credit-card-customers). There is a notebook in the repository outlining the training for a LightGBM model including hyperparameter optimization and performance evaluation.
Below is a summary of potential approaches for deploying your trained models to production:
Load model directly in application: this option involves having the pretrained model directly in the main application code. For small models this might be feasible however large models may introduce memory issues. This option also introduces a direct dependency on the model within the main application (coupled).Offline batch prediction: Use cases that do not require near real-time predictions can make use of this option. The model can be used the make predictions for a batch of data in a process that runs at defined intervals (e.g. overnight). The predictions can then be utilized by the application once the batch job is complete. Resource for prediction is only required when the batch process runs which can be beneficial.API: The third option is to deploy the model as its own microservice and communicate with it via an API. This decouples the application from the model and allows it to be utilized from multiple other services. The ML service can serve requests in one of the two ways described below.
Load model directly in application: this option involves having the pretrained model directly in the main application code. For small models this might be feasible however large models may introduce memory issues. This option also introduces a direct dependency on the model within the main application (coupled).
Offline batch prediction: Use cases that do not require near real-time predictions can make use of this option. The model can be used the make predictions for a batch of data in a process that runs at defined intervals (e.g. overnight). The predictions can then be utilized by the application once the batch job is complete. Resource for prediction is only required when the batch process runs which can be beneficial.
API: The third option is to deploy the model as its own microservice and communicate with it via an API. This decouples the application from the model and allows it to be utilized from multiple other services. The ML service can serve requests in one of the two ways described below.
Synchronous: the client requests a prediction and must wait for the model service to return a prediction. This is suitable for small models that require a small number of computations, or where the client cannot continue other processing steps without a prediction.
Asynchronous: instead of directly returning a prediction the model service will return a unique identifier for a task. Whilst the prediction task is being completed by the model service the client is free to continue other processing. The result can then be fetched via a results endpoint using the unique task id.
The steps below describe the actions taken to handle a prediction request:
Client sends a POST request to the FastAPI prediction endpoint, with the relevant feature information contained in the request body (JSON).The request body is validated by FastAPI against a defined model (i.e. checks if the expected features have been provided). If the validation is successful then a Celery prediction task is created and passed to the configured broker (e.g. RabbitMQ).The unique id is returned to the client if a task is created successfully.The prediction task is delivered to an available worker by the broker. Once delivered the worker generates a prediction using the pretrained ML model.Once a prediction has been generated the result is stored using the Celery backend (e.g. Redis).At any point after step 3 the client can begin to poll the FastAPI results endpoint using the unique task id. Once the prediction is ready it will be returned to the client.
Client sends a POST request to the FastAPI prediction endpoint, with the relevant feature information contained in the request body (JSON).
The request body is validated by FastAPI against a defined model (i.e. checks if the expected features have been provided). If the validation is successful then a Celery prediction task is created and passed to the configured broker (e.g. RabbitMQ).
The unique id is returned to the client if a task is created successfully.
The prediction task is delivered to an available worker by the broker. Once delivered the worker generates a prediction using the pretrained ML model.
Once a prediction has been generated the result is stored using the Celery backend (e.g. Redis).
At any point after step 3 the client can begin to poll the FastAPI results endpoint using the unique task id. Once the prediction is ready it will be returned to the client.
Now let’s look at some example code that implements this architecture.
The project structure is as follows:
serving_ml│ app.py│ models.py│ README.md│ requirements.txt│ test_client.py│├───celery_task_app│ │ tasks.py│ │ worker.py│ │ __init__.py│ ││ ├───ml│ │ │ model.py│ │ │ __init__.py
app.py: FastAPI application including route definitions.
models.py: Pydantic model definitions that are used for the API validation and response structure.
test_client.py: Script used for testing the set-up. We’ll cover this in more detail later.
celery_task_app\tasks.py: Contains Celery task definition, specifically the prediction task in our case.
celery_task_app\worker.py: Defines the celery app instance and associated config.
celery_task_app\ml\model.py: Machine learning model wrapper class used to load pretrained model and serve predictions.
First let’s look at how we are going to load the pretrained model and calculate predictions. The code below defines a wrapper class for a pretrained model that loads from file on creation and calculates class probability or membership in its predict method.
This implementation can be re-used for a variety of ML models as long as the model has predict and predict_proba methods (i.e. Scikit-Learn or Keras implementations).
In our example the saved model is in fact a Scikit-Learn pipeline object the contains a preprocessing step, so we don’t need to worry about having additonal preprocessing code before prediction. We can simply create a DataFrame with the feature data and call the pipeline predict method.
Celery is a simple task queue implementation that can used to distribute tasks across threads and/or machines. The implementation requires a broker and optionally a backend:
Broker: This is used to deliver messages between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker. RabbitMQ is often used as the broker and is the default used by Celery.
Backend: This is optional and its only function is to store task results to be retrieved at a later date. Redis is commonly used as the backend.
First let’s look at how we define our Celery app instance:
This app definition is very simple however there are a wide range of additional config options that can be defined (e.g. timezone, serialization).
The include argument is used to specify modules where tasks are defined for the Celery app. In this case we define a single task in tasks.py:
Our task implementation is slightly more complex than usual. Most simple tasks can be defined using the task decorator which overrides the run method of Celery’s base task class. However if we were to use this approach it would lead to a model class being defined and hence loaded from disk for each task processed.
By extending the Celery Task object we can override the default behavior such that the ML model is loaded only once when the task is first called. Subsequent calls can then use the same loaded model.
Although this is better than loading the model each time a task is run, there are still some considerations:
There will be a PredictTask object for each worker process. Therefore if a worker has four threads then the model will be loaded four times (each is then stored in memory as well...).This introduces a cold start scenario for each worker process, where the first task will be slow as the model needs to be loaded. There are different approaches that can be used to tackle this, and the fact that task are asynchronous makes this less of an issue.
There will be a PredictTask object for each worker process. Therefore if a worker has four threads then the model will be loaded four times (each is then stored in memory as well...).
This introduces a cold start scenario for each worker process, where the first task will be slow as the model needs to be loaded. There are different approaches that can be used to tackle this, and the fact that task are asynchronous makes this less of an issue.
We can then use the usual decorator approach and specify base=PredictTask so Celery knows to use our custom Task class instead of the default. The bind parameter allows us to access the model attribute using self (as if we were defining the run method directly in the class).
Finally we can create an API that will be used to generate tasks and fetch results from the backend based on client requests.
Two endpoints are required:
.../churn/predict (POST): Client sends JSON containing required features. Unique task id returned.
.../churn/result/<task_id>: (GET): Checks is task result is available in the backend, and returns the prediction if it is.
We implement these endpoints as follows:
A specific response is implemented within the results route to handle cases where the task result is not ready. This can be used by the client to poll the result endpoint until the result is ready (we’ll use this for testing...).
To check everything is working as expected we can create a separate Python script that imitates a prediction request. To do so we make use of Python’s requests package.
Once both the broker and backend servers are running, we can start the API using uvicorn:
uvicorn app:app
Next start a worker process:
celery -A celery_task_app.worker worker -l info
Running test_client.py will do the following (see repo for code):
An example feature JSON is sent to the predict endpoint. The features are hardcoded in a dictionary within the script.If successful, the task id returned will be used to poll the results endpoint. The dummy client will wait 5 seconds between each request and will make a maximum of 5 attempts.If the task is successful, the result (in this case the probability of membership to class 1) will be printed.
An example feature JSON is sent to the predict endpoint. The features are hardcoded in a dictionary within the script.
If successful, the task id returned will be used to poll the results endpoint. The dummy client will wait 5 seconds between each request and will make a maximum of 5 attempts.
If the task is successful, the result (in this case the probability of membership to class 1) will be printed.
(venv) python.exe test_client.py0.011178750583075114
The solution discussed above is simply a working example and should be adapted with more advanced Celery and FastAPI configuration for full production use.
Another possibility would be to dockerize the entire solution such that it can be deployed easily on cloud infrastructure.
|
[
{
"code": null,
"e": 410,
"s": 171,
"text": "There is an abundance of material online related to building and training all kinds of machine learning models. However once a high performance model has been trained there is significantly less material for how to put it into production."
},
{
"code": null,
"e": 547,
"s": 410,
"text": "This post walks through a working example for serving a ML model using Celery and FastAPI. All code can be found in the repository here."
},
{
"code": null,
"e": 883,
"s": 547,
"text": "We won’t specifically discuss the ML model used for this example however it was trained using example Bank customer churn data (https://www.kaggle.com/sakshigoyal7/credit-card-customers). There is a notebook in the repository outlining the training for a LightGBM model including hyperparameter optimization and performance evaluation."
},
{
"code": null,
"e": 975,
"s": 883,
"text": "Below is a summary of potential approaches for deploying your trained models to production:"
},
{
"code": null,
"e": 1990,
"s": 975,
"text": "Load model directly in application: this option involves having the pretrained model directly in the main application code. For small models this might be feasible however large models may introduce memory issues. This option also introduces a direct dependency on the model within the main application (coupled).Offline batch prediction: Use cases that do not require near real-time predictions can make use of this option. The model can be used the make predictions for a batch of data in a process that runs at defined intervals (e.g. overnight). The predictions can then be utilized by the application once the batch job is complete. Resource for prediction is only required when the batch process runs which can be beneficial.API: The third option is to deploy the model as its own microservice and communicate with it via an API. This decouples the application from the model and allows it to be utilized from multiple other services. The ML service can serve requests in one of the two ways described below."
},
{
"code": null,
"e": 2304,
"s": 1990,
"text": "Load model directly in application: this option involves having the pretrained model directly in the main application code. For small models this might be feasible however large models may introduce memory issues. This option also introduces a direct dependency on the model within the main application (coupled)."
},
{
"code": null,
"e": 2723,
"s": 2304,
"text": "Offline batch prediction: Use cases that do not require near real-time predictions can make use of this option. The model can be used the make predictions for a batch of data in a process that runs at defined intervals (e.g. overnight). The predictions can then be utilized by the application once the batch job is complete. Resource for prediction is only required when the batch process runs which can be beneficial."
},
{
"code": null,
"e": 3007,
"s": 2723,
"text": "API: The third option is to deploy the model as its own microservice and communicate with it via an API. This decouples the application from the model and allows it to be utilized from multiple other services. The ML service can serve requests in one of the two ways described below."
},
{
"code": null,
"e": 3273,
"s": 3007,
"text": "Synchronous: the client requests a prediction and must wait for the model service to return a prediction. This is suitable for small models that require a small number of computations, or where the client cannot continue other processing steps without a prediction."
},
{
"code": null,
"e": 3588,
"s": 3273,
"text": "Asynchronous: instead of directly returning a prediction the model service will return a unique identifier for a task. Whilst the prediction task is being completed by the model service the client is free to continue other processing. The result can then be fetched via a results endpoint using the unique task id."
},
{
"code": null,
"e": 3663,
"s": 3588,
"text": "The steps below describe the actions taken to handle a prediction request:"
},
{
"code": null,
"e": 4545,
"s": 3663,
"text": "Client sends a POST request to the FastAPI prediction endpoint, with the relevant feature information contained in the request body (JSON).The request body is validated by FastAPI against a defined model (i.e. checks if the expected features have been provided). If the validation is successful then a Celery prediction task is created and passed to the configured broker (e.g. RabbitMQ).The unique id is returned to the client if a task is created successfully.The prediction task is delivered to an available worker by the broker. Once delivered the worker generates a prediction using the pretrained ML model.Once a prediction has been generated the result is stored using the Celery backend (e.g. Redis).At any point after step 3 the client can begin to poll the FastAPI results endpoint using the unique task id. Once the prediction is ready it will be returned to the client."
},
{
"code": null,
"e": 4685,
"s": 4545,
"text": "Client sends a POST request to the FastAPI prediction endpoint, with the relevant feature information contained in the request body (JSON)."
},
{
"code": null,
"e": 4935,
"s": 4685,
"text": "The request body is validated by FastAPI against a defined model (i.e. checks if the expected features have been provided). If the validation is successful then a Celery prediction task is created and passed to the configured broker (e.g. RabbitMQ)."
},
{
"code": null,
"e": 5010,
"s": 4935,
"text": "The unique id is returned to the client if a task is created successfully."
},
{
"code": null,
"e": 5161,
"s": 5010,
"text": "The prediction task is delivered to an available worker by the broker. Once delivered the worker generates a prediction using the pretrained ML model."
},
{
"code": null,
"e": 5258,
"s": 5161,
"text": "Once a prediction has been generated the result is stored using the Celery backend (e.g. Redis)."
},
{
"code": null,
"e": 5432,
"s": 5258,
"text": "At any point after step 3 the client can begin to poll the FastAPI results endpoint using the unique task id. Once the prediction is ready it will be returned to the client."
},
{
"code": null,
"e": 5503,
"s": 5432,
"text": "Now let’s look at some example code that implements this architecture."
},
{
"code": null,
"e": 5540,
"s": 5503,
"text": "The project structure is as follows:"
},
{
"code": null,
"e": 5755,
"s": 5540,
"text": "serving_ml│ app.py│ models.py│ README.md│ requirements.txt│ test_client.py│├───celery_task_app│ │ tasks.py│ │ worker.py│ │ __init__.py│ ││ ├───ml│ │ │ model.py│ │ │ __init__.py"
},
{
"code": null,
"e": 5812,
"s": 5755,
"text": "app.py: FastAPI application including route definitions."
},
{
"code": null,
"e": 5911,
"s": 5812,
"text": "models.py: Pydantic model definitions that are used for the API validation and response structure."
},
{
"code": null,
"e": 6002,
"s": 5911,
"text": "test_client.py: Script used for testing the set-up. We’ll cover this in more detail later."
},
{
"code": null,
"e": 6107,
"s": 6002,
"text": "celery_task_app\\tasks.py: Contains Celery task definition, specifically the prediction task in our case."
},
{
"code": null,
"e": 6189,
"s": 6107,
"text": "celery_task_app\\worker.py: Defines the celery app instance and associated config."
},
{
"code": null,
"e": 6308,
"s": 6189,
"text": "celery_task_app\\ml\\model.py: Machine learning model wrapper class used to load pretrained model and serve predictions."
},
{
"code": null,
"e": 6566,
"s": 6308,
"text": "First let’s look at how we are going to load the pretrained model and calculate predictions. The code below defines a wrapper class for a pretrained model that loads from file on creation and calculates class probability or membership in its predict method."
},
{
"code": null,
"e": 6733,
"s": 6566,
"text": "This implementation can be re-used for a variety of ML models as long as the model has predict and predict_proba methods (i.e. Scikit-Learn or Keras implementations)."
},
{
"code": null,
"e": 7021,
"s": 6733,
"text": "In our example the saved model is in fact a Scikit-Learn pipeline object the contains a preprocessing step, so we don’t need to worry about having additonal preprocessing code before prediction. We can simply create a DataFrame with the feature data and call the pipeline predict method."
},
{
"code": null,
"e": 7195,
"s": 7021,
"text": "Celery is a simple task queue implementation that can used to distribute tasks across threads and/or machines. The implementation requires a broker and optionally a backend:"
},
{
"code": null,
"e": 7447,
"s": 7195,
"text": "Broker: This is used to deliver messages between clients and workers. To initiate a task the client adds a message to the queue, the broker then delivers that message to a worker. RabbitMQ is often used as the broker and is the default used by Celery."
},
{
"code": null,
"e": 7592,
"s": 7447,
"text": "Backend: This is optional and its only function is to store task results to be retrieved at a later date. Redis is commonly used as the backend."
},
{
"code": null,
"e": 7651,
"s": 7592,
"text": "First let’s look at how we define our Celery app instance:"
},
{
"code": null,
"e": 7798,
"s": 7651,
"text": "This app definition is very simple however there are a wide range of additional config options that can be defined (e.g. timezone, serialization)."
},
{
"code": null,
"e": 7940,
"s": 7798,
"text": "The include argument is used to specify modules where tasks are defined for the Celery app. In this case we define a single task in tasks.py:"
},
{
"code": null,
"e": 8256,
"s": 7940,
"text": "Our task implementation is slightly more complex than usual. Most simple tasks can be defined using the task decorator which overrides the run method of Celery’s base task class. However if we were to use this approach it would lead to a model class being defined and hence loaded from disk for each task processed."
},
{
"code": null,
"e": 8456,
"s": 8256,
"text": "By extending the Celery Task object we can override the default behavior such that the ML model is loaded only once when the task is first called. Subsequent calls can then use the same loaded model."
},
{
"code": null,
"e": 8565,
"s": 8456,
"text": "Although this is better than loading the model each time a task is run, there are still some considerations:"
},
{
"code": null,
"e": 9011,
"s": 8565,
"text": "There will be a PredictTask object for each worker process. Therefore if a worker has four threads then the model will be loaded four times (each is then stored in memory as well...).This introduces a cold start scenario for each worker process, where the first task will be slow as the model needs to be loaded. There are different approaches that can be used to tackle this, and the fact that task are asynchronous makes this less of an issue."
},
{
"code": null,
"e": 9195,
"s": 9011,
"text": "There will be a PredictTask object for each worker process. Therefore if a worker has four threads then the model will be loaded four times (each is then stored in memory as well...)."
},
{
"code": null,
"e": 9458,
"s": 9195,
"text": "This introduces a cold start scenario for each worker process, where the first task will be slow as the model needs to be loaded. There are different approaches that can be used to tackle this, and the fact that task are asynchronous makes this less of an issue."
},
{
"code": null,
"e": 9734,
"s": 9458,
"text": "We can then use the usual decorator approach and specify base=PredictTask so Celery knows to use our custom Task class instead of the default. The bind parameter allows us to access the model attribute using self (as if we were defining the run method directly in the class)."
},
{
"code": null,
"e": 9860,
"s": 9734,
"text": "Finally we can create an API that will be used to generate tasks and fetch results from the backend based on client requests."
},
{
"code": null,
"e": 9888,
"s": 9860,
"text": "Two endpoints are required:"
},
{
"code": null,
"e": 9987,
"s": 9888,
"text": ".../churn/predict (POST): Client sends JSON containing required features. Unique task id returned."
},
{
"code": null,
"e": 10110,
"s": 9987,
"text": ".../churn/result/<task_id>: (GET): Checks is task result is available in the backend, and returns the prediction if it is."
},
{
"code": null,
"e": 10151,
"s": 10110,
"text": "We implement these endpoints as follows:"
},
{
"code": null,
"e": 10381,
"s": 10151,
"text": "A specific response is implemented within the results route to handle cases where the task result is not ready. This can be used by the client to poll the result endpoint until the result is ready (we’ll use this for testing...)."
},
{
"code": null,
"e": 10550,
"s": 10381,
"text": "To check everything is working as expected we can create a separate Python script that imitates a prediction request. To do so we make use of Python’s requests package."
},
{
"code": null,
"e": 10640,
"s": 10550,
"text": "Once both the broker and backend servers are running, we can start the API using uvicorn:"
},
{
"code": null,
"e": 10656,
"s": 10640,
"text": "uvicorn app:app"
},
{
"code": null,
"e": 10685,
"s": 10656,
"text": "Next start a worker process:"
},
{
"code": null,
"e": 10733,
"s": 10685,
"text": "celery -A celery_task_app.worker worker -l info"
},
{
"code": null,
"e": 10799,
"s": 10733,
"text": "Running test_client.py will do the following (see repo for code):"
},
{
"code": null,
"e": 11203,
"s": 10799,
"text": "An example feature JSON is sent to the predict endpoint. The features are hardcoded in a dictionary within the script.If successful, the task id returned will be used to poll the results endpoint. The dummy client will wait 5 seconds between each request and will make a maximum of 5 attempts.If the task is successful, the result (in this case the probability of membership to class 1) will be printed."
},
{
"code": null,
"e": 11322,
"s": 11203,
"text": "An example feature JSON is sent to the predict endpoint. The features are hardcoded in a dictionary within the script."
},
{
"code": null,
"e": 11498,
"s": 11322,
"text": "If successful, the task id returned will be used to poll the results endpoint. The dummy client will wait 5 seconds between each request and will make a maximum of 5 attempts."
},
{
"code": null,
"e": 11609,
"s": 11498,
"text": "If the task is successful, the result (in this case the probability of membership to class 1) will be printed."
},
{
"code": null,
"e": 11662,
"s": 11609,
"text": "(venv) python.exe test_client.py0.011178750583075114"
},
{
"code": null,
"e": 11818,
"s": 11662,
"text": "The solution discussed above is simply a working example and should be adapted with more advanced Celery and FastAPI configuration for full production use."
}
] |
Pandas timeseries plot setting X-axis major and minor ticks and labels
|
Using Pandas, we can create a dataframe with time and speed, and thereafter, we can use the data frame to get the desired plot.
Construct a new Generator with the default BitGenerator (PCG64).
Construct a new Generator with the default BitGenerator (PCG64).
Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'.
Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'.
Draw samples from a log-normal distribution.
Draw samples from a log-normal distribution.
Make a data frame with above data.
Make a data frame with above data.
Using panda dataframe create plot, with figsize = (10, 5).
Using panda dataframe create plot, with figsize = (10, 5).
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
rng = np.random.default_rng(seed=1)
date_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')
traffic = rng.lognormal(sigma=2, size=date_day.size)
df_day = pd.DataFrame(dict(speed=[pow(2, -i) for i in range(len(date_day))]),
index=date_day)
df_day.plot(figsize=(10, 5))
plt.show()
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Using Pandas, we can create a dataframe with time and speed, and thereafter, we can use the data frame to get the desired plot."
},
{
"code": null,
"e": 1255,
"s": 1190,
"text": "Construct a new Generator with the default BitGenerator (PCG64)."
},
{
"code": null,
"e": 1320,
"s": 1255,
"text": "Construct a new Generator with the default BitGenerator (PCG64)."
},
{
"code": null,
"e": 1406,
"s": 1320,
"text": "Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'."
},
{
"code": null,
"e": 1492,
"s": 1406,
"text": "Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'."
},
{
"code": null,
"e": 1537,
"s": 1492,
"text": "Draw samples from a log-normal distribution."
},
{
"code": null,
"e": 1582,
"s": 1537,
"text": "Draw samples from a log-normal distribution."
},
{
"code": null,
"e": 1617,
"s": 1582,
"text": "Make a data frame with above data."
},
{
"code": null,
"e": 1652,
"s": 1617,
"text": "Make a data frame with above data."
},
{
"code": null,
"e": 1711,
"s": 1652,
"text": "Using panda dataframe create plot, with figsize = (10, 5)."
},
{
"code": null,
"e": 1770,
"s": 1711,
"text": "Using panda dataframe create plot, with figsize = (10, 5)."
},
{
"code": null,
"e": 1817,
"s": 1770,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 1864,
"s": 1817,
"text": "To show the figure, use the plt.show() method."
},
{
"code": null,
"e": 2239,
"s": 1864,
"text": "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\nrng = np.random.default_rng(seed=1)\ndate_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')\ntraffic = rng.lognormal(sigma=2, size=date_day.size)\ndf_day = pd.DataFrame(dict(speed=[pow(2, -i) for i in range(len(date_day))]),\nindex=date_day)\n\ndf_day.plot(figsize=(10, 5))\n\nplt.show()"
}
] |
Tryit Editor v3.7
|
Tryit: HTML HEX color values
|
[] |
TypeScript | Array filter() Method - GeeksforGeeks
|
18 Jun, 2020
The Array.filter() is an inbuilt TypeScript function which is used to creates a new array with all elements that pass the test implemented by the provided function. Syntax:
array.filter(callback[, thisObject])
Parameter: This methods accepts two parameter as mentioned and described below:
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns created array. Below examples illustrate the Array filter() method in TypeScriptExample 1:
JavaScript
<script> // check for positive number function ispositive(element, index, array) { return element > 0; } // Driver code var arr = [ 11, 89, -23, 7, 98 ]; // check for positive number var value = arr.filter(ispositive); console.log( value );</script>
Output:
[11,89,7,98]
Example 2:
JavaScript
<script> // check for odd number function isodd(element, index, array) { return (element % 2 == 1); } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // check for odd number var value = arr.filter(isodd); console.log( value );</script>
Output:
[11,89,23,7]
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24434,
"s": 24406,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 24607,
"s": 24434,
"text": "The Array.filter() is an inbuilt TypeScript function which is used to creates a new array with all elements that pass the test implemented by the provided function. Syntax:"
},
{
"code": null,
"e": 24644,
"s": 24607,
"text": "array.filter(callback[, thisObject])"
},
{
"code": null,
"e": 24724,
"s": 24644,
"text": "Parameter: This methods accepts two parameter as mentioned and described below:"
},
{
"code": null,
"e": 24792,
"s": 24724,
"text": "callback : This parameter is the Function to test for each element."
},
{
"code": null,
"e": 24874,
"s": 24792,
"text": "thisObject : This parameter is the Object to use as this when executing callback."
},
{
"code": null,
"e": 25000,
"s": 24874,
"text": "Return Value: This method returns created array. Below examples illustrate the Array filter() method in TypeScriptExample 1: "
},
{
"code": null,
"e": 25011,
"s": 25000,
"text": "JavaScript"
},
{
"code": "<script> // check for positive number function ispositive(element, index, array) { return element > 0; } // Driver code var arr = [ 11, 89, -23, 7, 98 ]; // check for positive number var value = arr.filter(ispositive); console.log( value );</script>",
"e": 25314,
"s": 25011,
"text": null
},
{
"code": null,
"e": 25323,
"s": 25314,
"text": "Output: "
},
{
"code": null,
"e": 25336,
"s": 25323,
"text": "[11,89,7,98]"
},
{
"code": null,
"e": 25348,
"s": 25336,
"text": "Example 2: "
},
{
"code": null,
"e": 25359,
"s": 25348,
"text": "JavaScript"
},
{
"code": "<script> // check for odd number function isodd(element, index, array) { return (element % 2 == 1); } // Driver code var arr = [ 11, 89, 23, 7, 98 ]; // check for odd number var value = arr.filter(isodd); console.log( value );</script>",
"e": 25647,
"s": 25359,
"text": null
},
{
"code": null,
"e": 25656,
"s": 25647,
"text": "Output: "
},
{
"code": null,
"e": 25669,
"s": 25656,
"text": "[11,89,23,7]"
},
{
"code": null,
"e": 25680,
"s": 25669,
"text": "TypeScript"
},
{
"code": null,
"e": 25691,
"s": 25680,
"text": "JavaScript"
},
{
"code": null,
"e": 25708,
"s": 25691,
"text": "Web Technologies"
},
{
"code": null,
"e": 25806,
"s": 25708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25815,
"s": 25806,
"text": "Comments"
},
{
"code": null,
"e": 25828,
"s": 25815,
"text": "Old Comments"
},
{
"code": null,
"e": 25873,
"s": 25828,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25934,
"s": 25873,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26006,
"s": 25934,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26058,
"s": 26006,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26104,
"s": 26058,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26146,
"s": 26104,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26179,
"s": 26146,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26222,
"s": 26179,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26284,
"s": 26222,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Partition problem | DP-18 - GeeksforGeeks
|
23 Mar, 2022
Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is the same.
Examples:
arr[] = {1, 5, 11, 5}
Output: true
The array can be partitioned as {1, 5, 5} and {11}
arr[] = {1, 5, 3}
Output: false
The array cannot be partitioned into equal sum sets.
Following are the two main steps to solve this problem: 1) Calculate sum of the array. If sum is odd, there can not be two subsets with equal sum, so return false. 2) If sum of array elements is even, calculate sum/2 and find a subset of array with sum equal to sum/2. The first step is simple. The second step is crucial, it can be solved either using recursion or Dynamic Programming.
Recursive Solution Following is the recursive property of the second step mentioned above.
Let isSubsetSum(arr, n, sum/2) be the function that returns true if
there is a subset of arr[0..n-1] with sum equal to sum/2
The isSubsetSum problem can be divided into two subproblems
a) isSubsetSum() without considering last element
(reducing n to n-1)
b) isSubsetSum considering the last element
(reducing sum/2 by arr[n-1] and n to n-1)
If any of the above subproblems return true, then return true.
isSubsetSum (arr, n, sum/2) = isSubsetSum (arr, n-1, sum/2) ||
isSubsetSum (arr, n-1, sum/2 - arr[n-1])
Below is the implementation of the above code:
C++
C
Java
Python3
C#
PHP
Javascript
// A recursive C++ program for partition problem#include <bits/stdc++.h>using namespace std; // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumbool isSubsetSum(int arr[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << "Can be divided into two subsets " "of equal sum"; else cout << "Can not be divided into two subsets" " of equal sum"; return 0;} // This code is contributed by rathbhupendra
// A recursive C program for partition problem#include <stdbool.h>#include <stdio.h> // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumbool isSubsetSum(int arr[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) printf("Can be divided into two subsets " "of equal sum"); else printf("Can not be divided into two subsets" " of equal sum"); return 0;}
// A recursive Java solution for partition problemimport java.io.*; class Partition { // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum static boolean isSubsetSum(int arr[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static boolean findPartition(int arr[], int n) { // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, sum / 2); } // Driver code public static void main(String[] args) { int arr[] = { 3, 1, 5, 9, 12 }; int n = arr.length; // Function call if (findPartition(arr, n) == true) System.out.println("Can be divided into two " + "subsets of equal sum"); else System.out.println( "Can not be divided into " + "two subsets of equal sum"); }}/* This code is contributed by Devesh Agrawal */
# A recursive Python3 program for# partition problem # A utility function that returns# true if there is a subset of# arr[] with sum equal to given sum def isSubsetSum(arr, n, sum): # Base Cases if sum == 0: return True if n == 0 and sum != 0: return False # If last element is greater than sum, then # ignore it if arr[n-1] > sum: return isSubsetSum(arr, n-1, sum) ''' else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element''' return isSubsetSum(arr, n-1, sum) or isSubsetSum(arr, n-1, sum-arr[n-1]) # Returns true if arr[] can be partitioned in two# subsets of equal sum, otherwise false def findPartion(arr, n): # Calculate sum of the elements in array sum = 0 for i in range(0, n): sum += arr[i] # If sum is odd, there cannot be two subsets # with equal sum if sum % 2 != 0: return false # Find if there is subset with sum equal to # half of total sum return isSubsetSum(arr, n, sum // 2) # Driver codearr = [3, 1, 5, 9, 12]n = len(arr) # Function callif findPartion(arr, n) == True: print("Can be divided into two subsets of equal sum")else: print("Can not be divided into two subsets of equal sum") # This code is contributed by shreyanshi_arun.
// A recursive C# solution for partition problemusing System; class GFG { // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum static bool isSubsetSum(int[] arr, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static bool findPartition(int[] arr, int n) { // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, sum / 2); } // Driver code public static void Main() { int[] arr = { 3, 1, 5, 9, 12 }; int n = arr.Length; // Function call if (findPartition(arr, n) == true) Console.Write("Can be divided into two " + "subsets of equal sum"); else Console.Write("Can not be divided into " + "two subsets of equal sum"); }} // This code is contributed by Sam007
<?php// A recursive PHP solution for partition problem // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumfunction isSubsetSum ($arr, $n, $sum){ // Base Cases if ($sum == 0) return true; if ($n == 0 && $sum != 0) return false; // If last element is greater than // sum, then ignore it if ($arr[$n - 1] > $sum) return isSubsetSum ($arr, $n - 1, $sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum ($arr, $n - 1, $sum) || isSubsetSum ($arr, $n - 1, $sum - $arr[$n - 1]);} // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsefunction findPartiion ($arr, $n){ // Calculate sum of the elements // in array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // If sum is odd, there cannot be // two subsets with equal sum if ($sum % 2 != 0) return false; // Find if there is subset with sum // equal to half of total sum return isSubsetSum ($arr, $n, $sum / 2);} // Driver Code$arr = array(3, 1, 5, 9, 12);$n = count($arr); // Function callif (findPartiion($arr, $n) == true) echo "Can be divided into two subsets of equal sum";else echo "Can not be divided into two subsets of equal sum"; // This code is contributed by rathbhupendra?>
<script>// A recursive Javascript solution for partition problem // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum function isSubsetSum(arr,n,sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false function findPartition(arr,n) { // Calculate sum of the elements in array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, Math.floor(sum / 2)); } // Driver code let arr=[3, 1, 5, 9, 12 ]; let n = arr.length; // Function call if (findPartition(arr, n) == true) document.write("Can be divided into two " + "subsets of equal sum"); else document.write( "Can not be divided into " + "two subsets of equal sum"); // This code is contributed by unknown2108</script>
Can be divided into two subsets of equal sum
Time Complexity: O(2^n) In the worst case, this solution tries two possibilities (whether to include or exclude) for every element.
Dynamic Programming Solution 1. Top-Down: Memoization
We can avoid the repeated work done in method 1 by storing the result calculated so far.
We just need to store all the values in a matrix.
C++
Python3
Javascript
// A recursive C++ program for partition problem#include <bits/stdc++.h>using namespace std; // A utility function that returns true if there is// a subset of arr[] with sun equal to given sumbool isSubsetSum(int arr[], int n, int sum, vector<vector<int> >& dp){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // return solved subproblem if (dp[n][sum] != -1) { return dp[n][sum]; } // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum, dp); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ // also store the subproblem in dp matrix return dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // To store overlapping subproblems vector<vector<int> > dp(n + 1, vector<int>(sum + 1, -1)); // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2, dp);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << "Can be divided into two subsets " "of equal sum"; else cout << "Can not be divided into two subsets" " of equal sum"; int arr2[] = { 3, 1, 5, 9, 14 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); if (findPartiion(arr2, n2) == true) cout << endl << "Can be divided into two subsets " "of equal sum"; else cout << endl << "Can not be divided into two subsets" " of equal sum"; return 0;}
# A recursive JavaScript program for partition problem # A utility function that returns true if there is# a subset of arr[] with sun equal to given sumdef isSubsetSum(arr,n,sum,dp): # Base Cases if (sum == 0): return True if (n == 0 and sum != 0): return False # return solved subproblem if (dp[n][sum] != -1): return dp[n][sum] # If last element is greater than sum, then # ignore it if (arr[n - 1] > sum): return isSubsetSum(arr, n - 1, sum, dp) # else, check if sum can be obtained by any of # the following # (a) including the last element # (b) excluding the last element # also store the subproblem in dp matrix dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) or isSubsetSum(arr, n - 1, sum - arr[n - 1], dp) return dp[n][sum] # Returns true if arr[] can be partitioned in two# subsets of equal sum, otherwise falsedef findPartiion(arr, n): # Calculate sum of the elements in array sum = 0 for i in range(n): sum += arr[i] # If sum is odd, there cannot be two subsets # with equal sum if (sum % 2 != 0): return False # To store overlapping subproblems dp = [[-1]*(sum+1)]*(n+1) # Find if there is subset with sum equal to # half of total sum return isSubsetSum(arr, n, sum // 2, dp) # Driver code arr = [ 3, 1, 5, 9, 12 ]n = len(arr) # Function callif (findPartiion(arr, n) == True): print("Can be divided into two subsets of equal sum")else: print("Can not be divided into two subsets of equal sum") arr2 = [ 3, 1, 5, 9, 14 ]n2 = len(arr2) if (findPartiion(arr2, n2) == True): print("Can be divided into two subsets of equal sum")else: print("Can not be divided into two subsets of equal sum") # This code is contributed by shinjanpatra.
<script> // A recursive JavaScript program for partition problem // A utility function that returns true if there is// a subset of arr[] with sun equal to given sumfunction isSubsetSum(arr,n,sum,dp){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // return solved subproblem if (dp[n][sum] != -1) { return dp[n][sum]; } // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum, dp); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ // also store the subproblem in dp matrix return dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsefunction findPartiion(arr, n){ // Calculate sum of the elements in array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // To store overlapping subproblems let dp = new Array(n + 1).fill(new Array(sum+1).fill(-1)); // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2, dp);} // Driver codelet arr = [ 3, 1, 5, 9, 12 ];let n = arr.length; // Function callif (findPartiion(arr, n) == true) document.write("Can be divided into two subsets of equal sum");else document.write("Can not be divided into two subsets of equal sum"); let arr2 = [ 3, 1, 5, 9, 14 ];let n2 = arr2.length; if (findPartiion(arr2, n2) == true) document.write("</br>","Can be divided into two subsets of equal sum");else document.write("</br>","Can not be divided into two subsets of equal sum"); // This code is contributed by shinjanpatra.</script>
Can be divided into two subsets of equal sum
Can not be divided into two subsets of equal sum
Time Complexity: O(sum*n)
Auxiliary Space: O(sum*n)
2. Bottom-Up: Tabulation
The problem can be solved using dynamic programming when the sum of the elements is not too big. We can create a 2D array part[][] of size (sum/2 + 1)*(n+1). And we can construct the solution in a bottom-up manner such that every filled entry has the following property
part[i][j] = true if a subset of {arr[0], arr[1], ..arr[j-1]} has sum
equal to i, otherwise false
C++
C
Java
Python3
C#
Javascript
// A Dynamic Programming based// C++ program to partition problem#include <bits/stdc++.h>using namespace std; // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) cout<<part[i][j]; cout<<endl; } */ return part[sum / 2][n];} // Driver Codeint main(){ int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << "Can be divided into two subsets of equal " "sum"; else cout << "Can not be divided into" << " two subsets of equal sum"; return 0;}
// A Dynamic Programming based C program to partition// problem#include <stdio.h> // Returns true if arr[] can be partitioned in two subsets// of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf ("%4d", part[i][j]); printf("\n"); } */ return part[sum / 2][n];} // Driver codeint main(){ int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) printf( "Can be divided into two subsets of equal sum"); else printf("Can not be divided into two subsets of " "equal sum"); getchar(); return 0;}
// A dynamic programming based Java program for partition// problemimport java.io.*; class Partition { // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static boolean findPartition(int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean part[][] = new boolean[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as // 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf ("%4d", part[i][j]); printf("\n"); } */ return part[sum / 2][n]; } // Driver code public static void main(String[] args) { int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = arr.length; if (findPartition(arr, n) == true) System.out.println( "Can be divided into two " "subsets of equal sum"); else System.out.println( "Can not be divided into" " two subsets of equal sum"); }}/* This code is contributed by Devesh Agrawal */
# Dynamic Programming based python# program to partition problem # Returns true if arr[] can be# partitioned in two subsets of# equal sum, otherwise false def findPartition(arr, n): sum = 0 i, j = 0, 0 # calculate sum of all elements for i in range(n): sum += arr[i] if sum % 2 != 0: return false part = [[True for i in range(n + 1)] for j in range(sum // 2 + 1)] # initialize top row as true for i in range(0, n + 1): part[0][i] = True # initialize leftmost column, # except part[0][0], as 0 for i in range(1, sum // 2 + 1): part[i][0] = False # fill the partition table in # bottom up manner for i in range(1, sum // 2 + 1): for j in range(1, n + 1): part[i][j] = part[i][j - 1] if i >= arr[j - 1]: part[i][j] = (part[i][j] or part[i - arr[j - 1]][j - 1]) return part[sum // 2][n] # Driver Codearr = [3, 1, 1, 2, 2, 1]n = len(arr) # Function callif findPartition(arr, n) == True: print("Can be divided into two", "subsets of equal sum")else: print("Can not be divided into ", "two subsets of equal sum") # This code is contributed# by mohit kumar 29
// A dynamic programming based C# program// for partition problemusing System; class GFG { // Returns true if arr[] can be partitioned // in two subsets of equal sum, otherwise // false static bool findPartition(int[] arr, int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool[, ] part = new bool[sum / 2 + 1, n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0, i] = true; // initialize leftmost column, except // part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i, 0] = false; // Fill the partition table in bottom // up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i, j] = part[i, j - 1]; if (i >= arr[j - 1]) part[i, j] = part[i, j - 1] || part[i - arr[j - 1], j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf ("%4d", part[i][j]); printf("\n"); } */ return part[sum / 2, n]; } // Driver code public static void Main() { int[] arr = { 3, 1, 1, 2, 2, 1 }; int n = arr.Length; // Function call if (findPartition(arr, n) == true) Console.Write("Can be divided" + " into two subsets of" + " equal sum"); else Console.Write("Can not be " + "divided into two subsets" + " of equal sum"); }} // This code is contributed by Sam007.
<script> // A dynamic programming based javascript// program for partition// problemclass Partition // Returns true if arr can be partitioned in two // subsets of equal sum, otherwise false function findPartition(arr , n) { var sum = 0; var i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; var part = Array(parseInt(sum / 2) + 1). fill().map(()=>Array(n + 1).fill(0)); // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as // 0 for (i = 1; i <= parseInt(sum / 2); i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= parseInt(sum / 2); i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf ("%4d", part[i][j]); printf("\n"); } */ return part[parseInt(sum / 2)][n]; } // Driver code var arr = [ 3, 1, 1, 2, 2, 1 ]; var n = arr.length; if (findPartition(arr, n) == true) document.write( "Can be divided into two subsets of equal sum" ); else document.write( "Can not be divided into two subsets of equal sum" ); // This code contributed by Rajput-Ji </script>
Can be divided into two subsets of equal sum
Following diagram shows the values in the partition table.
Time Complexity: O(sum*n) Auxiliary Space: O(sum*n)
Please note that this solution will not be feasible for arrays with big sum.
Dynamic Programming Solution (Space Complexity Optimized)
Instead of creating a 2-D array of size (sum/2 + 1)*(n + 1), we can solve this problem using an array of size (sum/2 + 1 ) only.
part[j] = true if there is a subset with sum equal to j, otherwise false.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// A Dynamic Programming based// C++ program to partition problem#include <bits/stdc++.h>using namespace std; // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1]; // Initialize the part array // as 0 for (i = 0; i <= sum / 2; i++) { part[i] = 0; } // Fill the partition table in bottom up manner for (i = 0; i < n; i++) { // the element to be included // in the sum cannot be // greater than the sum for (j = sum / 2; j >= arr[i]; j--) { // check if sum - arr[i] // could be formed // from a subset // using elements // before index i if (part[j - arr[i]] == 1 || j == arr[i]) part[j] = 1; } } return part[sum / 2];} // Driver Codeint main(){ int arr[] = { 1, 3, 3, 2, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << "Can be divided into two subsets of equal " "sum"; else cout << "Can not be divided into" << " two subsets of equal sum"; return 0;}
// A Dynamic Programming based// Java program to partition problemimport java.io.*; class GFG{ // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsepublic static boolean findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean[] part = new boolean[sum / 2 + 1]; // Initialize the part array // as 0 for(i = 0; i <= sum / 2; i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = sum / 2; j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using elements // before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[sum / 2];} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 3, 3, 2, 3, 2 }; int n = 6; // Function call if (findPartiion(arr, n) == true) System.out.println("Can be divided into two " + "subsets of equal sum"); else System.out.println("Can not be divided into " + "two subsets of equal sum");}} // This code is contributed by RohitOberoi
# A Dynamic Programming based# Python3 program to partition problem # Returns true if arr[] can be partitioned# in two subsets of equal sum, otherwise falsedef findPartiion(arr, n) : Sum = 0 # Calculate sum of all elements for i in range(n) : Sum += arr[i] if (Sum % 2 != 0) : return 0 part = [0] * ((Sum // 2) + 1) # Initialize the part array as 0 for i in range((Sum // 2) + 1) : part[i] = 0 # Fill the partition table in bottom up manner for i in range(n) : # the element to be included # in the sum cannot be # greater than the sum for j in range(Sum // 2, arr[i] - 1, -1) : # check if sum - arr[i] # could be formed # from a subset # using elements # before index i if (part[j - arr[i]] == 1 or j == arr[i]) : part[j] = 1 return part[Sum // 2] # Drive code arr = [ 1, 3, 3, 2, 3, 2 ]n = len(arr) # Function callif (findPartiion(arr, n) == 1) : print("Can be divided into two subsets of equal sum")else : print("Can not be divided into two subsets of equal sum") # This code is contributed by divyeshrabadiya07
// A Dynamic Programming based// C# program to partition problemusing System;class GFG{ // Returns true if arr[] can be partitioned // in two subsets of equal sum, otherwise false static bool findPartiion(int[] arr, int n) { int sum = 0; int i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool[] part = new bool[sum / 2 + 1]; // Initialize the part array // as 0 for(i = 0; i <= sum / 2; i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = sum / 2; j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using elements // before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[sum / 2]; } // Driver code static void Main() { int[] arr = { 1, 3, 3, 2, 3, 2 }; int n = 6; // Function call if (findPartiion(arr, n) == true) Console.WriteLine("Can be divided into two " + "subsets of equal sum"); else Console.WriteLine("Can not be divided into " + "two subsets of equal sum"); }} // This code is contributed by divyesh072019
<script> // A Dynamic Programming based Javascript// program to partition problem // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsefunction findPartiion(arr, n){ let sum = 0; let i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; let part = new Array(parseInt(sum / 2 + 1, 10)); // Initialize the part array // as 0 for(i = 0; i <= parseInt(sum / 2, 10); i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = parseInt(sum / 2, 10); j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using // elements before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[parseInt(sum / 2, 10)];} // Driver code let arr = [ 1, 3, 3, 2, 3, 2 ];let n = arr.length; // Function callif (findPartiion(arr, n) == true) document.write("Can be divided into two " + "subsets of equal sum");else document.write("Can not be divided into " + "two subsets of equal sum"); // This code is contributed by suresh07 </script>
Can be divided into two subsets of equal sum
Time Complexity: O(sum * n)Auxiliary Space: O(sum)
Please note that this solution will not be feasible for arrays with big sum.References: http://en.wikipedia.org/wiki/Partition_problem
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mohit kumar 29
anupam.karn.9726
rathbhupendra
AnuragGupta14
shubham_singh
BournThing
decoder_
nidhi_biet
mohitkumarbt2k18
RohitOberoi
divyesh072019
divyeshrabadiya07
suresh07
unknown2108
Rajput-Ji
x_walker_x
surinderdawra388
prasanna1995
shinjanpatra
Accolite
Adobe
Amazon
Drishti-Soft
subset
Dynamic Programming
Accolite
Amazon
Adobe
Drishti-Soft
Dynamic Programming
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Longest Palindromic Substring | Set 1
Coin Change | DP-7
Sieve of Eratosthenes
Edit Distance | DP-5
Overlapping Subproblems Property in Dynamic Programming | DP-1
Efficient program to print all prime factors of a given number
|
[
{
"code": null,
"e": 24890,
"s": 24862,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 25040,
"s": 24890,
"text": "Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is the same. "
},
{
"code": null,
"e": 25051,
"s": 25040,
"text": "Examples: "
},
{
"code": null,
"e": 25225,
"s": 25051,
"text": "arr[] = {1, 5, 11, 5}\nOutput: true \nThe array can be partitioned as {1, 5, 5} and {11}\n\narr[] = {1, 5, 3}\nOutput: false \nThe array cannot be partitioned into equal sum sets."
},
{
"code": null,
"e": 25612,
"s": 25225,
"text": "Following are the two main steps to solve this problem: 1) Calculate sum of the array. If sum is odd, there can not be two subsets with equal sum, so return false. 2) If sum of array elements is even, calculate sum/2 and find a subset of array with sum equal to sum/2. The first step is simple. The second step is crucial, it can be solved either using recursion or Dynamic Programming."
},
{
"code": null,
"e": 25704,
"s": 25612,
"text": "Recursive Solution Following is the recursive property of the second step mentioned above. "
},
{
"code": null,
"e": 26257,
"s": 25704,
"text": "Let isSubsetSum(arr, n, sum/2) be the function that returns true if \nthere is a subset of arr[0..n-1] with sum equal to sum/2\n\nThe isSubsetSum problem can be divided into two subproblems\n a) isSubsetSum() without considering last element \n (reducing n to n-1)\n b) isSubsetSum considering the last element \n (reducing sum/2 by arr[n-1] and n to n-1)\nIf any of the above subproblems return true, then return true. \nisSubsetSum (arr, n, sum/2) = isSubsetSum (arr, n-1, sum/2) ||\n isSubsetSum (arr, n-1, sum/2 - arr[n-1])"
},
{
"code": null,
"e": 26305,
"s": 26257,
"text": "Below is the implementation of the above code: "
},
{
"code": null,
"e": 26309,
"s": 26305,
"text": "C++"
},
{
"code": null,
"e": 26311,
"s": 26309,
"text": "C"
},
{
"code": null,
"e": 26316,
"s": 26311,
"text": "Java"
},
{
"code": null,
"e": 26324,
"s": 26316,
"text": "Python3"
},
{
"code": null,
"e": 26327,
"s": 26324,
"text": "C#"
},
{
"code": null,
"e": 26331,
"s": 26327,
"text": "PHP"
},
{
"code": null,
"e": 26342,
"s": 26331,
"text": "Javascript"
},
{
"code": "// A recursive C++ program for partition problem#include <bits/stdc++.h>using namespace std; // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumbool isSubsetSum(int arr[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << \"Can be divided into two subsets \" \"of equal sum\"; else cout << \"Can not be divided into two subsets\" \" of equal sum\"; return 0;} // This code is contributed by rathbhupendra",
"e": 27929,
"s": 26342,
"text": null
},
{
"code": "// A recursive C program for partition problem#include <stdbool.h>#include <stdio.h> // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumbool isSubsetSum(int arr[], int n, int sum){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) printf(\"Can be divided into two subsets \" \"of equal sum\"); else printf(\"Can not be divided into two subsets\" \" of equal sum\"); return 0;}",
"e": 29459,
"s": 27929,
"text": null
},
{
"code": "// A recursive Java solution for partition problemimport java.io.*; class Partition { // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum static boolean isSubsetSum(int arr[], int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static boolean findPartition(int arr[], int n) { // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, sum / 2); } // Driver code public static void main(String[] args) { int arr[] = { 3, 1, 5, 9, 12 }; int n = arr.length; // Function call if (findPartition(arr, n) == true) System.out.println(\"Can be divided into two \" + \"subsets of equal sum\"); else System.out.println( \"Can not be divided into \" + \"two subsets of equal sum\"); }}/* This code is contributed by Devesh Agrawal */",
"e": 31305,
"s": 29459,
"text": null
},
{
"code": "# A recursive Python3 program for# partition problem # A utility function that returns# true if there is a subset of# arr[] with sum equal to given sum def isSubsetSum(arr, n, sum): # Base Cases if sum == 0: return True if n == 0 and sum != 0: return False # If last element is greater than sum, then # ignore it if arr[n-1] > sum: return isSubsetSum(arr, n-1, sum) ''' else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element''' return isSubsetSum(arr, n-1, sum) or isSubsetSum(arr, n-1, sum-arr[n-1]) # Returns true if arr[] can be partitioned in two# subsets of equal sum, otherwise false def findPartion(arr, n): # Calculate sum of the elements in array sum = 0 for i in range(0, n): sum += arr[i] # If sum is odd, there cannot be two subsets # with equal sum if sum % 2 != 0: return false # Find if there is subset with sum equal to # half of total sum return isSubsetSum(arr, n, sum // 2) # Driver codearr = [3, 1, 5, 9, 12]n = len(arr) # Function callif findPartion(arr, n) == True: print(\"Can be divided into two subsets of equal sum\")else: print(\"Can not be divided into two subsets of equal sum\") # This code is contributed by shreyanshi_arun.",
"e": 32631,
"s": 31305,
"text": null
},
{
"code": "// A recursive C# solution for partition problemusing System; class GFG { // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum static bool isSubsetSum(int[] arr, int n, int sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static bool findPartition(int[] arr, int n) { // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, sum / 2); } // Driver code public static void Main() { int[] arr = { 3, 1, 5, 9, 12 }; int n = arr.Length; // Function call if (findPartition(arr, n) == true) Console.Write(\"Can be divided into two \" + \"subsets of equal sum\"); else Console.Write(\"Can not be divided into \" + \"two subsets of equal sum\"); }} // This code is contributed by Sam007",
"e": 34417,
"s": 32631,
"text": null
},
{
"code": "<?php// A recursive PHP solution for partition problem // A utility function that returns true if there is// a subset of arr[] with sum equal to given sumfunction isSubsetSum ($arr, $n, $sum){ // Base Cases if ($sum == 0) return true; if ($n == 0 && $sum != 0) return false; // If last element is greater than // sum, then ignore it if ($arr[$n - 1] > $sum) return isSubsetSum ($arr, $n - 1, $sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum ($arr, $n - 1, $sum) || isSubsetSum ($arr, $n - 1, $sum - $arr[$n - 1]);} // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsefunction findPartiion ($arr, $n){ // Calculate sum of the elements // in array $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $arr[$i]; // If sum is odd, there cannot be // two subsets with equal sum if ($sum % 2 != 0) return false; // Find if there is subset with sum // equal to half of total sum return isSubsetSum ($arr, $n, $sum / 2);} // Driver Code$arr = array(3, 1, 5, 9, 12);$n = count($arr); // Function callif (findPartiion($arr, $n) == true) echo \"Can be divided into two subsets of equal sum\";else echo \"Can not be divided into two subsets of equal sum\"; // This code is contributed by rathbhupendra?>",
"e": 35896,
"s": 34417,
"text": null
},
{
"code": "<script>// A recursive Javascript solution for partition problem // A utility function that returns true if there is a // subset of arr[] with sum equal to given sum function isSubsetSum(arr,n,sum) { // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // If last element is greater than sum, then ignore // it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ return isSubsetSum(arr, n - 1, sum) || isSubsetSum(arr, n - 1, sum - arr[n - 1]); } // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false function findPartition(arr,n) { // Calculate sum of the elements in array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // Find if there is subset with sum equal to half // of total sum return isSubsetSum(arr, n, Math.floor(sum / 2)); } // Driver code let arr=[3, 1, 5, 9, 12 ]; let n = arr.length; // Function call if (findPartition(arr, n) == true) document.write(\"Can be divided into two \" + \"subsets of equal sum\"); else document.write( \"Can not be divided into \" + \"two subsets of equal sum\"); // This code is contributed by unknown2108</script>",
"e": 37621,
"s": 35896,
"text": null
},
{
"code": null,
"e": 37666,
"s": 37621,
"text": "Can be divided into two subsets of equal sum"
},
{
"code": null,
"e": 37798,
"s": 37666,
"text": "Time Complexity: O(2^n) In the worst case, this solution tries two possibilities (whether to include or exclude) for every element."
},
{
"code": null,
"e": 37852,
"s": 37798,
"text": "Dynamic Programming Solution 1. Top-Down: Memoization"
},
{
"code": null,
"e": 37941,
"s": 37852,
"text": "We can avoid the repeated work done in method 1 by storing the result calculated so far."
},
{
"code": null,
"e": 37991,
"s": 37941,
"text": "We just need to store all the values in a matrix."
},
{
"code": null,
"e": 37995,
"s": 37991,
"text": "C++"
},
{
"code": null,
"e": 38003,
"s": 37995,
"text": "Python3"
},
{
"code": null,
"e": 38014,
"s": 38003,
"text": "Javascript"
},
{
"code": "// A recursive C++ program for partition problem#include <bits/stdc++.h>using namespace std; // A utility function that returns true if there is// a subset of arr[] with sun equal to given sumbool isSubsetSum(int arr[], int n, int sum, vector<vector<int> >& dp){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // return solved subproblem if (dp[n][sum] != -1) { return dp[n][sum]; } // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum, dp); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ // also store the subproblem in dp matrix return dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ // Calculate sum of the elements in array int sum = 0; for (int i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // To store overlapping subproblems vector<vector<int> > dp(n + 1, vector<int>(sum + 1, -1)); // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2, dp);} // Driver codeint main(){ int arr[] = { 3, 1, 5, 9, 12 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << \"Can be divided into two subsets \" \"of equal sum\"; else cout << \"Can not be divided into two subsets\" \" of equal sum\"; int arr2[] = { 3, 1, 5, 9, 14 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); if (findPartiion(arr2, n2) == true) cout << endl << \"Can be divided into two subsets \" \"of equal sum\"; else cout << endl << \"Can not be divided into two subsets\" \" of equal sum\"; return 0;}",
"e": 40262,
"s": 38014,
"text": null
},
{
"code": "# A recursive JavaScript program for partition problem # A utility function that returns true if there is# a subset of arr[] with sun equal to given sumdef isSubsetSum(arr,n,sum,dp): # Base Cases if (sum == 0): return True if (n == 0 and sum != 0): return False # return solved subproblem if (dp[n][sum] != -1): return dp[n][sum] # If last element is greater than sum, then # ignore it if (arr[n - 1] > sum): return isSubsetSum(arr, n - 1, sum, dp) # else, check if sum can be obtained by any of # the following # (a) including the last element # (b) excluding the last element # also store the subproblem in dp matrix dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) or isSubsetSum(arr, n - 1, sum - arr[n - 1], dp) return dp[n][sum] # Returns true if arr[] can be partitioned in two# subsets of equal sum, otherwise falsedef findPartiion(arr, n): # Calculate sum of the elements in array sum = 0 for i in range(n): sum += arr[i] # If sum is odd, there cannot be two subsets # with equal sum if (sum % 2 != 0): return False # To store overlapping subproblems dp = [[-1]*(sum+1)]*(n+1) # Find if there is subset with sum equal to # half of total sum return isSubsetSum(arr, n, sum // 2, dp) # Driver code arr = [ 3, 1, 5, 9, 12 ]n = len(arr) # Function callif (findPartiion(arr, n) == True): print(\"Can be divided into two subsets of equal sum\")else: print(\"Can not be divided into two subsets of equal sum\") arr2 = [ 3, 1, 5, 9, 14 ]n2 = len(arr2) if (findPartiion(arr2, n2) == True): print(\"Can be divided into two subsets of equal sum\")else: print(\"Can not be divided into two subsets of equal sum\") # This code is contributed by shinjanpatra.",
"e": 42072,
"s": 40262,
"text": null
},
{
"code": "<script> // A recursive JavaScript program for partition problem // A utility function that returns true if there is// a subset of arr[] with sun equal to given sumfunction isSubsetSum(arr,n,sum,dp){ // Base Cases if (sum == 0) return true; if (n == 0 && sum != 0) return false; // return solved subproblem if (dp[n][sum] != -1) { return dp[n][sum]; } // If last element is greater than sum, then // ignore it if (arr[n - 1] > sum) return isSubsetSum(arr, n - 1, sum, dp); /* else, check if sum can be obtained by any of the following (a) including the last element (b) excluding the last element */ // also store the subproblem in dp matrix return dp[n][sum] = isSubsetSum(arr, n - 1, sum, dp) || isSubsetSum(arr, n - 1, sum - arr[n - 1], dp);} // Returns true if arr[] can be partitioned in two// subsets of equal sum, otherwise falsefunction findPartiion(arr, n){ // Calculate sum of the elements in array let sum = 0; for (let i = 0; i < n; i++) sum += arr[i]; // If sum is odd, there cannot be two subsets // with equal sum if (sum % 2 != 0) return false; // To store overlapping subproblems let dp = new Array(n + 1).fill(new Array(sum+1).fill(-1)); // Find if there is subset with sum equal to // half of total sum return isSubsetSum(arr, n, sum / 2, dp);} // Driver codelet arr = [ 3, 1, 5, 9, 12 ];let n = arr.length; // Function callif (findPartiion(arr, n) == true) document.write(\"Can be divided into two subsets of equal sum\");else document.write(\"Can not be divided into two subsets of equal sum\"); let arr2 = [ 3, 1, 5, 9, 14 ];let n2 = arr2.length; if (findPartiion(arr2, n2) == true) document.write(\"</br>\",\"Can be divided into two subsets of equal sum\");else document.write(\"</br>\",\"Can not be divided into two subsets of equal sum\"); // This code is contributed by shinjanpatra.</script>",
"e": 44091,
"s": 42072,
"text": null
},
{
"code": null,
"e": 44185,
"s": 44091,
"text": "Can be divided into two subsets of equal sum\nCan not be divided into two subsets of equal sum"
},
{
"code": null,
"e": 44212,
"s": 44185,
"text": "Time Complexity: O(sum*n) "
},
{
"code": null,
"e": 44238,
"s": 44212,
"text": "Auxiliary Space: O(sum*n)"
},
{
"code": null,
"e": 44263,
"s": 44238,
"text": "2. Bottom-Up: Tabulation"
},
{
"code": null,
"e": 44535,
"s": 44263,
"text": "The problem can be solved using dynamic programming when the sum of the elements is not too big. We can create a 2D array part[][] of size (sum/2 + 1)*(n+1). And we can construct the solution in a bottom-up manner such that every filled entry has the following property "
},
{
"code": null,
"e": 44647,
"s": 44535,
"text": "part[i][j] = true if a subset of {arr[0], arr[1], ..arr[j-1]} has sum \n equal to i, otherwise false"
},
{
"code": null,
"e": 44651,
"s": 44647,
"text": "C++"
},
{
"code": null,
"e": 44653,
"s": 44651,
"text": "C"
},
{
"code": null,
"e": 44658,
"s": 44653,
"text": "Java"
},
{
"code": null,
"e": 44666,
"s": 44658,
"text": "Python3"
},
{
"code": null,
"e": 44669,
"s": 44666,
"text": "C#"
},
{
"code": null,
"e": 44680,
"s": 44669,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based// C++ program to partition problem#include <bits/stdc++.h>using namespace std; // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) cout<<part[i][j]; cout<<endl; } */ return part[sum / 2][n];} // Driver Codeint main(){ int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << \"Can be divided into two subsets of equal \" \"sum\"; else cout << \"Can not be divided into\" << \" two subsets of equal sum\"; return 0;}",
"e": 46173,
"s": 44680,
"text": null
},
{
"code": "// A Dynamic Programming based C program to partition// problem#include <stdio.h> // Returns true if arr[] can be partitioned in two subsets// of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf (\"%4d\", part[i][j]); printf(\"\\n\"); } */ return part[sum / 2][n];} // Driver codeint main(){ int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) printf( \"Can be divided into two subsets of equal sum\"); else printf(\"Can not be divided into two subsets of \" \"equal sum\"); getchar(); return 0;}",
"e": 47660,
"s": 46173,
"text": null
},
{
"code": "// A dynamic programming based Java program for partition// problemimport java.io.*; class Partition { // Returns true if arr[] can be partitioned in two // subsets of equal sum, otherwise false static boolean findPartition(int arr[], int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean part[][] = new boolean[sum / 2 + 1][n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, except part[0][0], as // 0 for (i = 1; i <= sum / 2; i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf (\"%4d\", part[i][j]); printf(\"\\n\"); } */ return part[sum / 2][n]; } // Driver code public static void main(String[] args) { int arr[] = { 3, 1, 1, 2, 2, 1 }; int n = arr.length; if (findPartition(arr, n) == true) System.out.println( \"Can be divided into two \" \"subsets of equal sum\"); else System.out.println( \"Can not be divided into\" \" two subsets of equal sum\"); }}/* This code is contributed by Devesh Agrawal */",
"e": 49454,
"s": 47660,
"text": null
},
{
"code": "# Dynamic Programming based python# program to partition problem # Returns true if arr[] can be# partitioned in two subsets of# equal sum, otherwise false def findPartition(arr, n): sum = 0 i, j = 0, 0 # calculate sum of all elements for i in range(n): sum += arr[i] if sum % 2 != 0: return false part = [[True for i in range(n + 1)] for j in range(sum // 2 + 1)] # initialize top row as true for i in range(0, n + 1): part[0][i] = True # initialize leftmost column, # except part[0][0], as 0 for i in range(1, sum // 2 + 1): part[i][0] = False # fill the partition table in # bottom up manner for i in range(1, sum // 2 + 1): for j in range(1, n + 1): part[i][j] = part[i][j - 1] if i >= arr[j - 1]: part[i][j] = (part[i][j] or part[i - arr[j - 1]][j - 1]) return part[sum // 2][n] # Driver Codearr = [3, 1, 1, 2, 2, 1]n = len(arr) # Function callif findPartition(arr, n) == True: print(\"Can be divided into two\", \"subsets of equal sum\")else: print(\"Can not be divided into \", \"two subsets of equal sum\") # This code is contributed# by mohit kumar 29",
"e": 50698,
"s": 49454,
"text": null
},
{
"code": "// A dynamic programming based C# program// for partition problemusing System; class GFG { // Returns true if arr[] can be partitioned // in two subsets of equal sum, otherwise // false static bool findPartition(int[] arr, int n) { int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool[, ] part = new bool[sum / 2 + 1, n + 1]; // initialize top row as true for (i = 0; i <= n; i++) part[0, i] = true; // initialize leftmost column, except // part[0][0], as 0 for (i = 1; i <= sum / 2; i++) part[i, 0] = false; // Fill the partition table in bottom // up manner for (i = 1; i <= sum / 2; i++) { for (j = 1; j <= n; j++) { part[i, j] = part[i, j - 1]; if (i >= arr[j - 1]) part[i, j] = part[i, j - 1] || part[i - arr[j - 1], j - 1]; } } /* // uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf (\"%4d\", part[i][j]); printf(\"\\n\"); } */ return part[sum / 2, n]; } // Driver code public static void Main() { int[] arr = { 3, 1, 1, 2, 2, 1 }; int n = arr.Length; // Function call if (findPartition(arr, n) == true) Console.Write(\"Can be divided\" + \" into two subsets of\" + \" equal sum\"); else Console.Write(\"Can not be \" + \"divided into two subsets\" + \" of equal sum\"); }} // This code is contributed by Sam007.",
"e": 52567,
"s": 50698,
"text": null
},
{
"code": "<script> // A dynamic programming based javascript// program for partition// problemclass Partition // Returns true if arr can be partitioned in two // subsets of equal sum, otherwise false function findPartition(arr , n) { var sum = 0; var i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; var part = Array(parseInt(sum / 2) + 1). fill().map(()=>Array(n + 1).fill(0)); // initialize top row as true for (i = 0; i <= n; i++) part[0][i] = true; // initialize leftmost column, // except part[0][0], as // 0 for (i = 1; i <= parseInt(sum / 2); i++) part[i][0] = false; // Fill the partition table in bottom up manner for (i = 1; i <= parseInt(sum / 2); i++) { for (j = 1; j <= n; j++) { part[i][j] = part[i][j - 1]; if (i >= arr[j - 1]) part[i][j] = part[i][j] || part[i - arr[j - 1]][j - 1]; } } /* uncomment this part to print table for (i = 0; i <= sum/2; i++) { for (j = 0; j <= n; j++) printf (\"%4d\", part[i][j]); printf(\"\\n\"); } */ return part[parseInt(sum / 2)][n]; } // Driver code var arr = [ 3, 1, 1, 2, 2, 1 ]; var n = arr.length; if (findPartition(arr, n) == true) document.write( \"Can be divided into two subsets of equal sum\" ); else document.write( \"Can not be divided into two subsets of equal sum\" ); // This code contributed by Rajput-Ji </script>",
"e": 54317,
"s": 52567,
"text": null
},
{
"code": null,
"e": 54362,
"s": 54317,
"text": "Can be divided into two subsets of equal sum"
},
{
"code": null,
"e": 54423,
"s": 54362,
"text": "Following diagram shows the values in the partition table. "
},
{
"code": null,
"e": 54476,
"s": 54423,
"text": "Time Complexity: O(sum*n) Auxiliary Space: O(sum*n) "
},
{
"code": null,
"e": 54553,
"s": 54476,
"text": "Please note that this solution will not be feasible for arrays with big sum."
},
{
"code": null,
"e": 54611,
"s": 54553,
"text": "Dynamic Programming Solution (Space Complexity Optimized)"
},
{
"code": null,
"e": 54742,
"s": 54611,
"text": "Instead of creating a 2-D array of size (sum/2 + 1)*(n + 1), we can solve this problem using an array of size (sum/2 + 1 ) only. "
},
{
"code": null,
"e": 54816,
"s": 54742,
"text": "part[j] = true if there is a subset with sum equal to j, otherwise false."
},
{
"code": null,
"e": 54868,
"s": 54816,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 54872,
"s": 54868,
"text": "C++"
},
{
"code": null,
"e": 54877,
"s": 54872,
"text": "Java"
},
{
"code": null,
"e": 54885,
"s": 54877,
"text": "Python3"
},
{
"code": null,
"e": 54888,
"s": 54885,
"text": "C#"
},
{
"code": null,
"e": 54899,
"s": 54888,
"text": "Javascript"
},
{
"code": "// A Dynamic Programming based// C++ program to partition problem#include <bits/stdc++.h>using namespace std; // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsebool findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for (i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool part[sum / 2 + 1]; // Initialize the part array // as 0 for (i = 0; i <= sum / 2; i++) { part[i] = 0; } // Fill the partition table in bottom up manner for (i = 0; i < n; i++) { // the element to be included // in the sum cannot be // greater than the sum for (j = sum / 2; j >= arr[i]; j--) { // check if sum - arr[i] // could be formed // from a subset // using elements // before index i if (part[j - arr[i]] == 1 || j == arr[i]) part[j] = 1; } } return part[sum / 2];} // Driver Codeint main(){ int arr[] = { 1, 3, 3, 2, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call if (findPartiion(arr, n) == true) cout << \"Can be divided into two subsets of equal \" \"sum\"; else cout << \"Can not be divided into\" << \" two subsets of equal sum\"; return 0;}",
"e": 56280,
"s": 54899,
"text": null
},
{
"code": "// A Dynamic Programming based// Java program to partition problemimport java.io.*; class GFG{ // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsepublic static boolean findPartiion(int arr[], int n){ int sum = 0; int i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; boolean[] part = new boolean[sum / 2 + 1]; // Initialize the part array // as 0 for(i = 0; i <= sum / 2; i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = sum / 2; j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using elements // before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[sum / 2];} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 3, 3, 2, 3, 2 }; int n = 6; // Function call if (findPartiion(arr, n) == true) System.out.println(\"Can be divided into two \" + \"subsets of equal sum\"); else System.out.println(\"Can not be divided into \" + \"two subsets of equal sum\");}} // This code is contributed by RohitOberoi",
"e": 57782,
"s": 56280,
"text": null
},
{
"code": "# A Dynamic Programming based# Python3 program to partition problem # Returns true if arr[] can be partitioned# in two subsets of equal sum, otherwise falsedef findPartiion(arr, n) : Sum = 0 # Calculate sum of all elements for i in range(n) : Sum += arr[i] if (Sum % 2 != 0) : return 0 part = [0] * ((Sum // 2) + 1) # Initialize the part array as 0 for i in range((Sum // 2) + 1) : part[i] = 0 # Fill the partition table in bottom up manner for i in range(n) : # the element to be included # in the sum cannot be # greater than the sum for j in range(Sum // 2, arr[i] - 1, -1) : # check if sum - arr[i] # could be formed # from a subset # using elements # before index i if (part[j - arr[i]] == 1 or j == arr[i]) : part[j] = 1 return part[Sum // 2] # Drive code arr = [ 1, 3, 3, 2, 3, 2 ]n = len(arr) # Function callif (findPartiion(arr, n) == 1) : print(\"Can be divided into two subsets of equal sum\")else : print(\"Can not be divided into two subsets of equal sum\") # This code is contributed by divyeshrabadiya07",
"e": 58989,
"s": 57782,
"text": null
},
{
"code": "// A Dynamic Programming based// C# program to partition problemusing System;class GFG{ // Returns true if arr[] can be partitioned // in two subsets of equal sum, otherwise false static bool findPartiion(int[] arr, int n) { int sum = 0; int i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; bool[] part = new bool[sum / 2 + 1]; // Initialize the part array // as 0 for(i = 0; i <= sum / 2; i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = sum / 2; j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using elements // before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[sum / 2]; } // Driver code static void Main() { int[] arr = { 1, 3, 3, 2, 3, 2 }; int n = 6; // Function call if (findPartiion(arr, n) == true) Console.WriteLine(\"Can be divided into two \" + \"subsets of equal sum\"); else Console.WriteLine(\"Can not be divided into \" + \"two subsets of equal sum\"); }} // This code is contributed by divyesh072019",
"e": 60630,
"s": 58989,
"text": null
},
{
"code": "<script> // A Dynamic Programming based Javascript// program to partition problem // Returns true if arr[] can be partitioned// in two subsets of equal sum, otherwise falsefunction findPartiion(arr, n){ let sum = 0; let i, j; // Calculate sum of all elements for(i = 0; i < n; i++) sum += arr[i]; if (sum % 2 != 0) return false; let part = new Array(parseInt(sum / 2 + 1, 10)); // Initialize the part array // as 0 for(i = 0; i <= parseInt(sum / 2, 10); i++) { part[i] = false; } // Fill the partition table in // bottom up manner for(i = 0; i < n; i++) { // The element to be included // in the sum cannot be // greater than the sum for(j = parseInt(sum / 2, 10); j >= arr[i]; j--) { // Check if sum - arr[i] could be // formed from a subset using // elements before index i if (part[j - arr[i]] == true || j == arr[i]) part[j] = true; } } return part[parseInt(sum / 2, 10)];} // Driver code let arr = [ 1, 3, 3, 2, 3, 2 ];let n = arr.length; // Function callif (findPartiion(arr, n) == true) document.write(\"Can be divided into two \" + \"subsets of equal sum\");else document.write(\"Can not be divided into \" + \"two subsets of equal sum\"); // This code is contributed by suresh07 </script>",
"e": 62114,
"s": 60630,
"text": null
},
{
"code": null,
"e": 62159,
"s": 62114,
"text": "Can be divided into two subsets of equal sum"
},
{
"code": null,
"e": 62210,
"s": 62159,
"text": "Time Complexity: O(sum * n)Auxiliary Space: O(sum)"
},
{
"code": null,
"e": 62345,
"s": 62210,
"text": "Please note that this solution will not be feasible for arrays with big sum.References: http://en.wikipedia.org/wiki/Partition_problem"
},
{
"code": null,
"e": 62471,
"s": 62345,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 62488,
"s": 62473,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 62505,
"s": 62488,
"text": "anupam.karn.9726"
},
{
"code": null,
"e": 62519,
"s": 62505,
"text": "rathbhupendra"
},
{
"code": null,
"e": 62533,
"s": 62519,
"text": "AnuragGupta14"
},
{
"code": null,
"e": 62547,
"s": 62533,
"text": "shubham_singh"
},
{
"code": null,
"e": 62558,
"s": 62547,
"text": "BournThing"
},
{
"code": null,
"e": 62567,
"s": 62558,
"text": "decoder_"
},
{
"code": null,
"e": 62578,
"s": 62567,
"text": "nidhi_biet"
},
{
"code": null,
"e": 62595,
"s": 62578,
"text": "mohitkumarbt2k18"
},
{
"code": null,
"e": 62607,
"s": 62595,
"text": "RohitOberoi"
},
{
"code": null,
"e": 62621,
"s": 62607,
"text": "divyesh072019"
},
{
"code": null,
"e": 62639,
"s": 62621,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 62648,
"s": 62639,
"text": "suresh07"
},
{
"code": null,
"e": 62660,
"s": 62648,
"text": "unknown2108"
},
{
"code": null,
"e": 62670,
"s": 62660,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 62681,
"s": 62670,
"text": "x_walker_x"
},
{
"code": null,
"e": 62698,
"s": 62681,
"text": "surinderdawra388"
},
{
"code": null,
"e": 62711,
"s": 62698,
"text": "prasanna1995"
},
{
"code": null,
"e": 62724,
"s": 62711,
"text": "shinjanpatra"
},
{
"code": null,
"e": 62733,
"s": 62724,
"text": "Accolite"
},
{
"code": null,
"e": 62739,
"s": 62733,
"text": "Adobe"
},
{
"code": null,
"e": 62746,
"s": 62739,
"text": "Amazon"
},
{
"code": null,
"e": 62759,
"s": 62746,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 62766,
"s": 62759,
"text": "subset"
},
{
"code": null,
"e": 62786,
"s": 62766,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 62795,
"s": 62786,
"text": "Accolite"
},
{
"code": null,
"e": 62802,
"s": 62795,
"text": "Amazon"
},
{
"code": null,
"e": 62808,
"s": 62802,
"text": "Adobe"
},
{
"code": null,
"e": 62821,
"s": 62808,
"text": "Drishti-Soft"
},
{
"code": null,
"e": 62841,
"s": 62821,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 62848,
"s": 62841,
"text": "subset"
},
{
"code": null,
"e": 62946,
"s": 62848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 62977,
"s": 62946,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 63010,
"s": 62977,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 63045,
"s": 63010,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 63113,
"s": 63045,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 63151,
"s": 63113,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 63170,
"s": 63151,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 63192,
"s": 63170,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 63213,
"s": 63192,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 63276,
"s": 63213,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
}
] |
Comparing RNN Architectures for Lyric Generation | Towards Data Science
|
Music has long been considered to be one of the most influential and powerful forms of artwork. As such, it has been used to express raw emotion from the artist and transfer it to the listener.
Being a fan of music myself, it was only natural to wonder how difficult it would be to generate lyrics using recurrent neural networks (RNNs). I really enjoy rap and hip hop music, so I chose to work off of artists in those genres. It was also a good fit since there is existing research on rap lyric generation.
Recurrent neural networks can be used for many language modeling tasks such as: chat bots, predictive keyboards, and language translation. Recurrent neural networks work well when it comes to text generation because of their ability to work with sequential data. This is beneficial as we need to preserve the context of a sentence or, in this case, a verse.
An explanation of how an RNN works would be that it looks at previous data from the sequence to predict the next element in the sequence. Let’s say we have an RNN trained to perform text prediction on your phone’s keyboard (You know, the word predictions that pop up as you type). Based on previous messages I’ve typed I could input something like “Wezley is super ...” and the neural network will take that sequence, and give a set of predicted words to go off of, such as: “cool”, “smart”, and “funny”.
To add to this experiment, I wanted to train different recurrent neural network architectures to perform the rap lyric generation. I chose to go with SimpleRNN, Gated Recurrent Unit, Long Short Term Memory, and Convolution Neural Network + Long Short Term Memory based architectures. I chose these to ensure we are able to test each architecture against one-another to determine which would perform the best given the task. We don’t know if one model will outperform the other unless we try, right?
The SimpleRNN architecture was more-so for a baseline to see how the other architectures will perform. A SimpleRNN architecture is not very good for this specific task, because of the vanishing gradient problem. This means that the SimpleRNN won’t be very useful in remembering context throughout a bar/verse because it will lose early information about the sequence the further in the sequence we go. This leads to incoherent verses that you’ll see later on in the article. If you are curious and want a TL;DR of how the model performed: we get verses such as “I am, what stone private bedroom now” or “And how the low changed up last gas guitar thing.” Both of these verses were generated from a dataset of Drake lyrics. Neither of them make much sense. However, I’d argue that they’re still fire bars.
The Gated Recurrent Unit architecture was the next architecture I tested. The gated recurrent unit differs from the SimpleRNN by being able to remember a little further down in the sequence. It accomplishes this by utilizing two gates, a reset gate and an update gate. These gates control if the previous sequence information continues through the network or if it it gets updated to the most recent step. I’ll go a little more in-depth on this further into the article.
The Long Short Term Memory architecture was another architecture that was tested for this project. The LSTM differs from the SimpleRNN by, again, being able to remember further down the sequence. The LSTM has an advantage over the GRU by being able to remember longer sequences due to being a little more complex. The LSTM has three gates, instead of two, that control the information it forgets, carries on in the sequence, and updates from the latest step. Again, the LSTM will be covered a little more in-depth later on in the article.
The final architecture I tested was a mixture of a convolution neural network and long short term memory RNN. I threw this one in as a thought experiment based off of a paper that I read which used a C-LSTM architecture for text classification (Reference in Colab notebook). I wondered if the CNN would allow the LSTM to generalize a bar and better understand the stylistic elements of an artist. While fun to see a CNN in a text generation problem, I didn’t notice much of a different between this and the LSTM model.
With a defined set of architectures created, I set out to find the dataset I wanted to use for this problem.
The dataset didn’t really matter to me, so long as it contained lyrics from prominent artists. I wanted to generate lyrics based off of artists I listen to often. This was so I could recognize if the model was able to generate similar lyrics. Don’t worry though! I didn’t determine a model’s performance solely off of what I thought sounded good. I also used a set of metrics that have been described in recent literature on the subject.
The dataset I found was here on Kaggle and was provided by Paul Mooney.
This dataset was great because it contained lyrics from many of the rap/hip hop artists that I listen to. It also didn’t have any weird characters and took care of some of censoring of explicit lyrics.
With the dataset in hand, I set out to load and prepare the data for training.
The first thing I did was load in the data and finish censoring it. I used a preexisting Python library to perform the censorship so that I didn’t have to create a “naughty words” list manually. Unfortunately the library didn’t censor every word, so I apologize if you stumble across something explicit in the published notebook for this article.
With the lyrics read in and censored, I went ahead and split them into an array of bars. I didn’t do any other processing to the bars, but in the future I may try this again and add <start> and <end> tags to each bar. This way the model can possibly learn when to end the sequence. For now, I had it generate bars of randomized lengths and the results were good enough for the initial experiment.
Once I finished splitting the data, I created a Markov model utilizing the markovify Python library. The Markov model will be used to generate the beginning sequences for each bar. This will help us ensure that the beginning of the sequence is somewhat coherent before passing it to the trained models. The models will then take the sequence and finish generating the lyrics for the bar.
The next step was to tokenize the lyrics so that they would be in a format that the models could understand. Tokenization is actually a pretty cool process, as it basically splits up the words into a dictionary of words with IDs tied to them and changes each bar into an array of the corresponding word IDs. There is an example of this in the published notebook, but here’s another example of this in action:
For an example, let’s say we were to tokenize the following sentences:
“Wezley is cool”
“You are cool”
“TensorFlow is very cool”
The following sequences would be produced:
[1, 2, 3]
[4, 5, 3]
[6, 2, 7, 3]
Where the word dictionary is:
[‘Wezley’ : 1, ‘is’ : 2, ‘cool’ : 3, ‘You’ : 4, ‘are’ : 5, ‘TensorFlow’ : 6, ‘very’ : 7]
As-is, these sequences can’t be fed into a model since they are of different lengths. To fix this, we add padding to the front of the arrays.
With padding we get:
[0, 1, 2, 3]
[0, 4, 5, 3]
[6, 2, 7, 3]
With the bars tokenized, I was finally able to create my X and y data for training. The train_X data consisted of an entire bar, minus the last word. The train_y data was the last word in the bar.
Looking into the future, as with adding the <start> and <end> tags to the bars. I want to try changing up the way I’m splitting the training data. Maybe have the next version of this predict an entire bar based off the previous bar. That’ll be a project for another day though.
With the data imported and split into the train_X and train_y sets. It’s time to define the model architectures and begin training.
First up is the SimpleRNN architecture! The SimpleRNN will give a good baseline against the GRU, LSTM, and CNN+LSTM architectures.
The SimpleRNN unit can be expressed arithmetically as:
Where h(t) is expressed as the hidden state at a given point in time t. As you can see in the equation, the SimpleRNN relies on the previous hidden state h(t-1) and the current input x(t) to give us the current hidden state.
The SimpleRNN is great because of its ability to work with sequence data. The shortfall is in its simplicity. The SimpleRNN is unable to remember data further back in the sequence and thus suffers from the vanishing gradient problem. The vanishing gradient problem occurs when we start getting further down the sequence. This is when earlier states have a harder time being expressed. There is no mechanism in a SimpleRNN to help is keep track of previous states.
In code, the SimpleRNN network looks like:
The data being fed into the network is only expressed as a N*T vector, where the SimpleRNN is expecting an N*T*D vector. We correct this by adding an embedding layer to give the vector the D dimension. The embedding layer allows for the inputs to be transformed into a dense vector that can be fed into the SimpleRNN cells. For more information on the embedding layer see the TensorFlow documentation here.
I’m utilizing the Adam optimizer with a learning rate of 0.001. I’m using categorical cross-entropy as my loss function. Categorical cross-entropy is being used because we are trying to classify the next word in the sequence given the previous steps.
Next up is the network utilizing the Gated Recurrent Unit.
The GRU improves upon the SimpleRNN cell by introducing a reset and update gate. At a high level, these gates are used to decide which information we want to retain/lose previous states.
The GRU is expressed as:
Where z(t) is the update gate, r(t) is the reset gate, and h(t) is the hidden cell state.
Here’s how the GRU looks in action:
Here is how the GRU network is constructed in TensorFlow:
Again, I’m utilizing Adam for the optimizer and categorical cross-entropy as the loss function.
The Long Short Term Memory architecture was the next to be utilized.
The long short term memory cell has advantages over the SimpleRNN and GRU cells by being able retain even more information further down the sequence. The LSTM utilizes three different gates as oppose to the GRU’s two, and retains a cell state throughout the network. The GRU is known to have the advantage of speed over the LSTM, in that it is able to generalize faster and utilize fewer parameters. However, the LSTM tends to take the cake when it comes to retaining more contextual data throughout a sequence.
The LSTM cell can be expressed as:
Where f(t) represents the forget gate, and determines how much of the previous state to forget. Then i(t) represents the input gates which determines how much of the new information we will add to the cell state. The o(t) is the output gate, which determines which information will be progressing to the next hidden state. The cell state is represented by c(t), and the hidden state is h(t).
Here is a visualization of data progressing through and LSTM cell:
See below for the implementation in code:
The final architecture I wanted to test was a combination of a convolution neural network and LSTM.
This network was a thought experiment to see how the results would differ from the LSTM, GRU, and SimpleRNN. I was actually surprised at some of the verses it was about to put out.
Here is the code for the architecture:
Creating the models for this project was only about half of the work. The other half was generating song lyrics utilizing the trained model.
In my opinion, this is where the project became really fun. I was able to take the models I trained and utilize them for a non-trivial task.
This project was heavily inspired by “Evaluating Creative Language Generation: The Case of Rap Lyric Ghost Writing” by Peter Potash, Alexey Romanov, and Anna Rumshishky. With that, I’m going to utilize some of the methods outlined in their paper for evaluating the output of the models against the original lyrics from the artist.
The methods I’m utilizing to evaluate bars and generate raps are: comprehension score, rhyme index, and lyrical uniqueness. I’ll discuss how I calculated these shortly.
A high level overview of how I’m generating songs can be described as:
Utilize Markov model to generate first four words of a bar
Take the output of the Markov model and feed them into the RNN
Evaluate the output of the RNN against the original lyrics for uniqueness, similar rhyme index, and similar comprehension score
Either throw out the bar (if it’s trash), or add it to the song (if it’s fire)
Fairly simple, right?
Let’s jump into the code of how this is done.
First, I have a function named generate_rap. This function handles the main functionality of generating a rap song. generate_rap takes in the model I want to use to generate the rap (SimpleRNN, GRU, LSTM, or CNN+LSTM), the max bar length, how many bars we want in the rap, score thresholds, and how many tries we want for generating a fire bar. The score thresholds define how well the bar scores before it is considered fire — in this case, the closer to 0 the bar is, the more fire it is. Here is how the function looks in code:
As you can see, we generate a random bar, score it based on the artist’s average rhyme index, average comprehension, and the uniqueness of the bar. Then if the bar meets the score threshold it is graduated into the final song. If the algorithm fails to generate a fire bar within the defined max tries, it’ll put the best scored bar in the song and move on.
Within generate_rap I’m utilizing another function named generate_bar. This function takes in a seed phrase, the model we are using to generate the sequence, and the sequence’s length. generate_bar will then tokenize the seed phrase and feed it into the provided model until the sequence hits the desired length, then return the output. Here is the code:
To score the bars, I’m utilizing a function named score_bar. This function takes in the bar we want to score, the artist’s original lyrics, the artist’s average comprehension score, and the artist’s average rhyme index. score_bar calculates the input bar’s comprehension score, rhyme index, and uniqueness index then scores the bar.
The bar’s score can be positive or negative with 0 being the best score a bar can achieve. A score of 0 means that the bar has the same rhyme index and comprehension score while remaining completely unique from the original artist’s lyrics. A perfect score of 0 will be impossible to achieve, which is why we are defining min and max thresholds.
The score_bar function looks like:
To calculate the rhyme index of a bar, I’m utilizing the method as described in “Evaluating Creative Language Generation: The Case of Rap Lyric Ghostwriting.” Rhyme index is calculated by taking the number of rhymed syllables and dividing that by the total number of syllables in the bar or song. Here is that implementation in code:
For comparing the uniqueness of the generated bar, I’m computing the cosine distance between the generated bar and all of the artist’s bars. I’m then getting the average distance to compute the total uniqueness score. Here is how that looks:
With all of this I was finally able to generate a full rap utilizing the four models I trained. After generating the rap, I took the generated song and calculated the rhyme index and comprehension scores. Surprisingly the full song still remained fairly close to the original artist’s rhyme index and comprehension score.
Here are some of the outputs when training off of Drake lyrics.
The SimpleRNN:
Generated rap with avg rhyme density: 0.5030674846625767 and avg readability of: 2.0599999999999996 Rap Generated with SimpleRNN: Now you’re throwing me baby know it know Look I gotta started with you hook drake I swear it happened no tellin’ yeah yeah....
The GRU:
Generated rap with avg rhyme density: 0.5176470588235295 and avg readability of: 1.9449999999999998 Rap Generated with GRU: That's why I died everything big crazy on me Who keepin' score up yeah yeah yeah yeah I've loved and you everything big crazy on me on....
The LSTM:
Generated rap with avg rhyme density: 0.3684210526315789 and avg readability of: 1.9749999999999996 Rap Generated with LSTM: Get the **** lick alone same that wait now up ****, see what uh huh heart thing up yeah Despite the things though up up up up yeah yeah....
The LSTM+CSNN:
Generated rap with avg rhyme density: 0.33519553072625696 and avg readability of: 2.2599999999999993 Rap Generated with CNN+LSTM: They still out know play through now out out I got it dedicate dedicate you yeah I've been waiting much much aye aye days aye aye ....
For the full lyrics and list of references, take a look at the Google Colab notebook. Also feel free to try it yourself and change the artist for the style you want to mimic.
As far as the SimpleRNN vs GRU vs LSTM vs CNN+LSTM experiment goes, I would say that the LSTM tended to have the best results. The CNN+LSTM had too many repetitive words in a bar, and I think this has to do with the CNN generalizing the sequence as a whole. The SimpleRNN and GRU produced pretty incoherent bars, and their rhyme densities were really far off from the original artist.
That's it! Let me know what you think in the comments. I’d love to build upon this project in the future. If you have any suggestions for things I need to change to get better results, let me know! Thank you for reading.
Check out my GitHub for the code to this project, and other cool projects!
github.com
Some rights reserved
|
[
{
"code": null,
"e": 365,
"s": 171,
"text": "Music has long been considered to be one of the most influential and powerful forms of artwork. As such, it has been used to express raw emotion from the artist and transfer it to the listener."
},
{
"code": null,
"e": 679,
"s": 365,
"text": "Being a fan of music myself, it was only natural to wonder how difficult it would be to generate lyrics using recurrent neural networks (RNNs). I really enjoy rap and hip hop music, so I chose to work off of artists in those genres. It was also a good fit since there is existing research on rap lyric generation."
},
{
"code": null,
"e": 1037,
"s": 679,
"text": "Recurrent neural networks can be used for many language modeling tasks such as: chat bots, predictive keyboards, and language translation. Recurrent neural networks work well when it comes to text generation because of their ability to work with sequential data. This is beneficial as we need to preserve the context of a sentence or, in this case, a verse."
},
{
"code": null,
"e": 1542,
"s": 1037,
"text": "An explanation of how an RNN works would be that it looks at previous data from the sequence to predict the next element in the sequence. Let’s say we have an RNN trained to perform text prediction on your phone’s keyboard (You know, the word predictions that pop up as you type). Based on previous messages I’ve typed I could input something like “Wezley is super ...” and the neural network will take that sequence, and give a set of predicted words to go off of, such as: “cool”, “smart”, and “funny”."
},
{
"code": null,
"e": 2041,
"s": 1542,
"text": "To add to this experiment, I wanted to train different recurrent neural network architectures to perform the rap lyric generation. I chose to go with SimpleRNN, Gated Recurrent Unit, Long Short Term Memory, and Convolution Neural Network + Long Short Term Memory based architectures. I chose these to ensure we are able to test each architecture against one-another to determine which would perform the best given the task. We don’t know if one model will outperform the other unless we try, right?"
},
{
"code": null,
"e": 2846,
"s": 2041,
"text": "The SimpleRNN architecture was more-so for a baseline to see how the other architectures will perform. A SimpleRNN architecture is not very good for this specific task, because of the vanishing gradient problem. This means that the SimpleRNN won’t be very useful in remembering context throughout a bar/verse because it will lose early information about the sequence the further in the sequence we go. This leads to incoherent verses that you’ll see later on in the article. If you are curious and want a TL;DR of how the model performed: we get verses such as “I am, what stone private bedroom now” or “And how the low changed up last gas guitar thing.” Both of these verses were generated from a dataset of Drake lyrics. Neither of them make much sense. However, I’d argue that they’re still fire bars."
},
{
"code": null,
"e": 3317,
"s": 2846,
"text": "The Gated Recurrent Unit architecture was the next architecture I tested. The gated recurrent unit differs from the SimpleRNN by being able to remember a little further down in the sequence. It accomplishes this by utilizing two gates, a reset gate and an update gate. These gates control if the previous sequence information continues through the network or if it it gets updated to the most recent step. I’ll go a little more in-depth on this further into the article."
},
{
"code": null,
"e": 3856,
"s": 3317,
"text": "The Long Short Term Memory architecture was another architecture that was tested for this project. The LSTM differs from the SimpleRNN by, again, being able to remember further down the sequence. The LSTM has an advantage over the GRU by being able to remember longer sequences due to being a little more complex. The LSTM has three gates, instead of two, that control the information it forgets, carries on in the sequence, and updates from the latest step. Again, the LSTM will be covered a little more in-depth later on in the article."
},
{
"code": null,
"e": 4375,
"s": 3856,
"text": "The final architecture I tested was a mixture of a convolution neural network and long short term memory RNN. I threw this one in as a thought experiment based off of a paper that I read which used a C-LSTM architecture for text classification (Reference in Colab notebook). I wondered if the CNN would allow the LSTM to generalize a bar and better understand the stylistic elements of an artist. While fun to see a CNN in a text generation problem, I didn’t notice much of a different between this and the LSTM model."
},
{
"code": null,
"e": 4484,
"s": 4375,
"text": "With a defined set of architectures created, I set out to find the dataset I wanted to use for this problem."
},
{
"code": null,
"e": 4922,
"s": 4484,
"text": "The dataset didn’t really matter to me, so long as it contained lyrics from prominent artists. I wanted to generate lyrics based off of artists I listen to often. This was so I could recognize if the model was able to generate similar lyrics. Don’t worry though! I didn’t determine a model’s performance solely off of what I thought sounded good. I also used a set of metrics that have been described in recent literature on the subject."
},
{
"code": null,
"e": 4994,
"s": 4922,
"text": "The dataset I found was here on Kaggle and was provided by Paul Mooney."
},
{
"code": null,
"e": 5196,
"s": 4994,
"text": "This dataset was great because it contained lyrics from many of the rap/hip hop artists that I listen to. It also didn’t have any weird characters and took care of some of censoring of explicit lyrics."
},
{
"code": null,
"e": 5275,
"s": 5196,
"text": "With the dataset in hand, I set out to load and prepare the data for training."
},
{
"code": null,
"e": 5622,
"s": 5275,
"text": "The first thing I did was load in the data and finish censoring it. I used a preexisting Python library to perform the censorship so that I didn’t have to create a “naughty words” list manually. Unfortunately the library didn’t censor every word, so I apologize if you stumble across something explicit in the published notebook for this article."
},
{
"code": null,
"e": 6019,
"s": 5622,
"text": "With the lyrics read in and censored, I went ahead and split them into an array of bars. I didn’t do any other processing to the bars, but in the future I may try this again and add <start> and <end> tags to each bar. This way the model can possibly learn when to end the sequence. For now, I had it generate bars of randomized lengths and the results were good enough for the initial experiment."
},
{
"code": null,
"e": 6407,
"s": 6019,
"text": "Once I finished splitting the data, I created a Markov model utilizing the markovify Python library. The Markov model will be used to generate the beginning sequences for each bar. This will help us ensure that the beginning of the sequence is somewhat coherent before passing it to the trained models. The models will then take the sequence and finish generating the lyrics for the bar."
},
{
"code": null,
"e": 6816,
"s": 6407,
"text": "The next step was to tokenize the lyrics so that they would be in a format that the models could understand. Tokenization is actually a pretty cool process, as it basically splits up the words into a dictionary of words with IDs tied to them and changes each bar into an array of the corresponding word IDs. There is an example of this in the published notebook, but here’s another example of this in action:"
},
{
"code": null,
"e": 6887,
"s": 6816,
"text": "For an example, let’s say we were to tokenize the following sentences:"
},
{
"code": null,
"e": 6904,
"s": 6887,
"text": "“Wezley is cool”"
},
{
"code": null,
"e": 6919,
"s": 6904,
"text": "“You are cool”"
},
{
"code": null,
"e": 6945,
"s": 6919,
"text": "“TensorFlow is very cool”"
},
{
"code": null,
"e": 6988,
"s": 6945,
"text": "The following sequences would be produced:"
},
{
"code": null,
"e": 6998,
"s": 6988,
"text": "[1, 2, 3]"
},
{
"code": null,
"e": 7008,
"s": 6998,
"text": "[4, 5, 3]"
},
{
"code": null,
"e": 7021,
"s": 7008,
"text": "[6, 2, 7, 3]"
},
{
"code": null,
"e": 7051,
"s": 7021,
"text": "Where the word dictionary is:"
},
{
"code": null,
"e": 7140,
"s": 7051,
"text": "[‘Wezley’ : 1, ‘is’ : 2, ‘cool’ : 3, ‘You’ : 4, ‘are’ : 5, ‘TensorFlow’ : 6, ‘very’ : 7]"
},
{
"code": null,
"e": 7282,
"s": 7140,
"text": "As-is, these sequences can’t be fed into a model since they are of different lengths. To fix this, we add padding to the front of the arrays."
},
{
"code": null,
"e": 7303,
"s": 7282,
"text": "With padding we get:"
},
{
"code": null,
"e": 7316,
"s": 7303,
"text": "[0, 1, 2, 3]"
},
{
"code": null,
"e": 7329,
"s": 7316,
"text": "[0, 4, 5, 3]"
},
{
"code": null,
"e": 7342,
"s": 7329,
"text": "[6, 2, 7, 3]"
},
{
"code": null,
"e": 7539,
"s": 7342,
"text": "With the bars tokenized, I was finally able to create my X and y data for training. The train_X data consisted of an entire bar, minus the last word. The train_y data was the last word in the bar."
},
{
"code": null,
"e": 7817,
"s": 7539,
"text": "Looking into the future, as with adding the <start> and <end> tags to the bars. I want to try changing up the way I’m splitting the training data. Maybe have the next version of this predict an entire bar based off the previous bar. That’ll be a project for another day though."
},
{
"code": null,
"e": 7949,
"s": 7817,
"text": "With the data imported and split into the train_X and train_y sets. It’s time to define the model architectures and begin training."
},
{
"code": null,
"e": 8080,
"s": 7949,
"text": "First up is the SimpleRNN architecture! The SimpleRNN will give a good baseline against the GRU, LSTM, and CNN+LSTM architectures."
},
{
"code": null,
"e": 8135,
"s": 8080,
"text": "The SimpleRNN unit can be expressed arithmetically as:"
},
{
"code": null,
"e": 8360,
"s": 8135,
"text": "Where h(t) is expressed as the hidden state at a given point in time t. As you can see in the equation, the SimpleRNN relies on the previous hidden state h(t-1) and the current input x(t) to give us the current hidden state."
},
{
"code": null,
"e": 8824,
"s": 8360,
"text": "The SimpleRNN is great because of its ability to work with sequence data. The shortfall is in its simplicity. The SimpleRNN is unable to remember data further back in the sequence and thus suffers from the vanishing gradient problem. The vanishing gradient problem occurs when we start getting further down the sequence. This is when earlier states have a harder time being expressed. There is no mechanism in a SimpleRNN to help is keep track of previous states."
},
{
"code": null,
"e": 8867,
"s": 8824,
"text": "In code, the SimpleRNN network looks like:"
},
{
"code": null,
"e": 9274,
"s": 8867,
"text": "The data being fed into the network is only expressed as a N*T vector, where the SimpleRNN is expecting an N*T*D vector. We correct this by adding an embedding layer to give the vector the D dimension. The embedding layer allows for the inputs to be transformed into a dense vector that can be fed into the SimpleRNN cells. For more information on the embedding layer see the TensorFlow documentation here."
},
{
"code": null,
"e": 9525,
"s": 9274,
"text": "I’m utilizing the Adam optimizer with a learning rate of 0.001. I’m using categorical cross-entropy as my loss function. Categorical cross-entropy is being used because we are trying to classify the next word in the sequence given the previous steps."
},
{
"code": null,
"e": 9584,
"s": 9525,
"text": "Next up is the network utilizing the Gated Recurrent Unit."
},
{
"code": null,
"e": 9771,
"s": 9584,
"text": "The GRU improves upon the SimpleRNN cell by introducing a reset and update gate. At a high level, these gates are used to decide which information we want to retain/lose previous states."
},
{
"code": null,
"e": 9796,
"s": 9771,
"text": "The GRU is expressed as:"
},
{
"code": null,
"e": 9886,
"s": 9796,
"text": "Where z(t) is the update gate, r(t) is the reset gate, and h(t) is the hidden cell state."
},
{
"code": null,
"e": 9922,
"s": 9886,
"text": "Here’s how the GRU looks in action:"
},
{
"code": null,
"e": 9980,
"s": 9922,
"text": "Here is how the GRU network is constructed in TensorFlow:"
},
{
"code": null,
"e": 10076,
"s": 9980,
"text": "Again, I’m utilizing Adam for the optimizer and categorical cross-entropy as the loss function."
},
{
"code": null,
"e": 10145,
"s": 10076,
"text": "The Long Short Term Memory architecture was the next to be utilized."
},
{
"code": null,
"e": 10657,
"s": 10145,
"text": "The long short term memory cell has advantages over the SimpleRNN and GRU cells by being able retain even more information further down the sequence. The LSTM utilizes three different gates as oppose to the GRU’s two, and retains a cell state throughout the network. The GRU is known to have the advantage of speed over the LSTM, in that it is able to generalize faster and utilize fewer parameters. However, the LSTM tends to take the cake when it comes to retaining more contextual data throughout a sequence."
},
{
"code": null,
"e": 10692,
"s": 10657,
"text": "The LSTM cell can be expressed as:"
},
{
"code": null,
"e": 11084,
"s": 10692,
"text": "Where f(t) represents the forget gate, and determines how much of the previous state to forget. Then i(t) represents the input gates which determines how much of the new information we will add to the cell state. The o(t) is the output gate, which determines which information will be progressing to the next hidden state. The cell state is represented by c(t), and the hidden state is h(t)."
},
{
"code": null,
"e": 11151,
"s": 11084,
"text": "Here is a visualization of data progressing through and LSTM cell:"
},
{
"code": null,
"e": 11193,
"s": 11151,
"text": "See below for the implementation in code:"
},
{
"code": null,
"e": 11293,
"s": 11193,
"text": "The final architecture I wanted to test was a combination of a convolution neural network and LSTM."
},
{
"code": null,
"e": 11474,
"s": 11293,
"text": "This network was a thought experiment to see how the results would differ from the LSTM, GRU, and SimpleRNN. I was actually surprised at some of the verses it was about to put out."
},
{
"code": null,
"e": 11513,
"s": 11474,
"text": "Here is the code for the architecture:"
},
{
"code": null,
"e": 11654,
"s": 11513,
"text": "Creating the models for this project was only about half of the work. The other half was generating song lyrics utilizing the trained model."
},
{
"code": null,
"e": 11795,
"s": 11654,
"text": "In my opinion, this is where the project became really fun. I was able to take the models I trained and utilize them for a non-trivial task."
},
{
"code": null,
"e": 12126,
"s": 11795,
"text": "This project was heavily inspired by “Evaluating Creative Language Generation: The Case of Rap Lyric Ghost Writing” by Peter Potash, Alexey Romanov, and Anna Rumshishky. With that, I’m going to utilize some of the methods outlined in their paper for evaluating the output of the models against the original lyrics from the artist."
},
{
"code": null,
"e": 12295,
"s": 12126,
"text": "The methods I’m utilizing to evaluate bars and generate raps are: comprehension score, rhyme index, and lyrical uniqueness. I’ll discuss how I calculated these shortly."
},
{
"code": null,
"e": 12366,
"s": 12295,
"text": "A high level overview of how I’m generating songs can be described as:"
},
{
"code": null,
"e": 12425,
"s": 12366,
"text": "Utilize Markov model to generate first four words of a bar"
},
{
"code": null,
"e": 12488,
"s": 12425,
"text": "Take the output of the Markov model and feed them into the RNN"
},
{
"code": null,
"e": 12616,
"s": 12488,
"text": "Evaluate the output of the RNN against the original lyrics for uniqueness, similar rhyme index, and similar comprehension score"
},
{
"code": null,
"e": 12695,
"s": 12616,
"text": "Either throw out the bar (if it’s trash), or add it to the song (if it’s fire)"
},
{
"code": null,
"e": 12717,
"s": 12695,
"text": "Fairly simple, right?"
},
{
"code": null,
"e": 12763,
"s": 12717,
"text": "Let’s jump into the code of how this is done."
},
{
"code": null,
"e": 13294,
"s": 12763,
"text": "First, I have a function named generate_rap. This function handles the main functionality of generating a rap song. generate_rap takes in the model I want to use to generate the rap (SimpleRNN, GRU, LSTM, or CNN+LSTM), the max bar length, how many bars we want in the rap, score thresholds, and how many tries we want for generating a fire bar. The score thresholds define how well the bar scores before it is considered fire — in this case, the closer to 0 the bar is, the more fire it is. Here is how the function looks in code:"
},
{
"code": null,
"e": 13652,
"s": 13294,
"text": "As you can see, we generate a random bar, score it based on the artist’s average rhyme index, average comprehension, and the uniqueness of the bar. Then if the bar meets the score threshold it is graduated into the final song. If the algorithm fails to generate a fire bar within the defined max tries, it’ll put the best scored bar in the song and move on."
},
{
"code": null,
"e": 14007,
"s": 13652,
"text": "Within generate_rap I’m utilizing another function named generate_bar. This function takes in a seed phrase, the model we are using to generate the sequence, and the sequence’s length. generate_bar will then tokenize the seed phrase and feed it into the provided model until the sequence hits the desired length, then return the output. Here is the code:"
},
{
"code": null,
"e": 14340,
"s": 14007,
"text": "To score the bars, I’m utilizing a function named score_bar. This function takes in the bar we want to score, the artist’s original lyrics, the artist’s average comprehension score, and the artist’s average rhyme index. score_bar calculates the input bar’s comprehension score, rhyme index, and uniqueness index then scores the bar."
},
{
"code": null,
"e": 14686,
"s": 14340,
"text": "The bar’s score can be positive or negative with 0 being the best score a bar can achieve. A score of 0 means that the bar has the same rhyme index and comprehension score while remaining completely unique from the original artist’s lyrics. A perfect score of 0 will be impossible to achieve, which is why we are defining min and max thresholds."
},
{
"code": null,
"e": 14721,
"s": 14686,
"text": "The score_bar function looks like:"
},
{
"code": null,
"e": 15055,
"s": 14721,
"text": "To calculate the rhyme index of a bar, I’m utilizing the method as described in “Evaluating Creative Language Generation: The Case of Rap Lyric Ghostwriting.” Rhyme index is calculated by taking the number of rhymed syllables and dividing that by the total number of syllables in the bar or song. Here is that implementation in code:"
},
{
"code": null,
"e": 15297,
"s": 15055,
"text": "For comparing the uniqueness of the generated bar, I’m computing the cosine distance between the generated bar and all of the artist’s bars. I’m then getting the average distance to compute the total uniqueness score. Here is how that looks:"
},
{
"code": null,
"e": 15619,
"s": 15297,
"text": "With all of this I was finally able to generate a full rap utilizing the four models I trained. After generating the rap, I took the generated song and calculated the rhyme index and comprehension scores. Surprisingly the full song still remained fairly close to the original artist’s rhyme index and comprehension score."
},
{
"code": null,
"e": 15683,
"s": 15619,
"text": "Here are some of the outputs when training off of Drake lyrics."
},
{
"code": null,
"e": 15698,
"s": 15683,
"text": "The SimpleRNN:"
},
{
"code": null,
"e": 15955,
"s": 15698,
"text": "Generated rap with avg rhyme density: 0.5030674846625767 and avg readability of: 2.0599999999999996 Rap Generated with SimpleRNN: Now you’re throwing me baby know it know Look I gotta started with you hook drake I swear it happened no tellin’ yeah yeah...."
},
{
"code": null,
"e": 15964,
"s": 15955,
"text": "The GRU:"
},
{
"code": null,
"e": 16229,
"s": 15964,
"text": "Generated rap with avg rhyme density: 0.5176470588235295 and avg readability of: 1.9449999999999998 Rap Generated with GRU: That's why I died everything big crazy on me Who keepin' score up yeah yeah yeah yeah I've loved and you everything big crazy on me on...."
},
{
"code": null,
"e": 16239,
"s": 16229,
"text": "The LSTM:"
},
{
"code": null,
"e": 16506,
"s": 16239,
"text": "Generated rap with avg rhyme density: 0.3684210526315789 and avg readability of: 1.9749999999999996 Rap Generated with LSTM: Get the **** lick alone same that wait now up ****, see what uh huh heart thing up yeah Despite the things though up up up up yeah yeah...."
},
{
"code": null,
"e": 16521,
"s": 16506,
"text": "The LSTM+CSNN:"
},
{
"code": null,
"e": 16788,
"s": 16521,
"text": "Generated rap with avg rhyme density: 0.33519553072625696 and avg readability of: 2.2599999999999993 Rap Generated with CNN+LSTM: They still out know play through now out out I got it dedicate dedicate you yeah I've been waiting much much aye aye days aye aye ...."
},
{
"code": null,
"e": 16963,
"s": 16788,
"text": "For the full lyrics and list of references, take a look at the Google Colab notebook. Also feel free to try it yourself and change the artist for the style you want to mimic."
},
{
"code": null,
"e": 17348,
"s": 16963,
"text": "As far as the SimpleRNN vs GRU vs LSTM vs CNN+LSTM experiment goes, I would say that the LSTM tended to have the best results. The CNN+LSTM had too many repetitive words in a bar, and I think this has to do with the CNN generalizing the sequence as a whole. The SimpleRNN and GRU produced pretty incoherent bars, and their rhyme densities were really far off from the original artist."
},
{
"code": null,
"e": 17569,
"s": 17348,
"text": "That's it! Let me know what you think in the comments. I’d love to build upon this project in the future. If you have any suggestions for things I need to change to get better results, let me know! Thank you for reading."
},
{
"code": null,
"e": 17644,
"s": 17569,
"text": "Check out my GitHub for the code to this project, and other cool projects!"
},
{
"code": null,
"e": 17655,
"s": 17644,
"text": "github.com"
}
] |
Java Swing | Popup and PopupFactory with examples - GeeksforGeeks
|
16 Jun, 2021
Popup and PopupFactory are a part of the Java Swing library. Popups are used when we want to display to the user a Component on the top of all the other Components in that particular containment hierarchy. PopupFactory is the class that is used to create popups. Popups have a very small life cycle, and generally are lightweight components having limited sub-components.Constructor for the class are :
PopupFactory(): creates an object for popup factory
PopupFactory(): creates an object for popup factory
Commonly used methods:
Below programs will illustrate the use of a popup:
Java Program to create a popup and display it on a parent frame: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We add this popup to a frame f titled “pop” we will create a label and add t to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). Finally, the frame is displayed using show() function.
Java Program to create a popup and display it on a parent frame: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We add this popup to a frame f titled “pop” we will create a label and add t to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). Finally, the frame is displayed using show() function.
Java
// Java Program to create a popup and display// it on a parent frameimport javax.swing.*;import java.awt.*;import java.awt.event.*;class pop extends JFrame implements ActionListener { // popup Popup p; // constructor pop() { // create a frame JFrame f = new JFrame("pop"); // create a label JLabel l = new JLabel("This is a popup"); f.setSize(400, 400); PopupFactory pf = new PopupFactory(); // create a panel JPanel p2 = new JPanel(); // set Background of panel p2.setBackground(Color.red); p2.add(l); // create a popup p = pf.getPopup(f, p2, 180, 100); // create a button JButton b = new JButton("click"); // add action listener b.addActionListener(this); // create a panel JPanel p1 = new JPanel(); p1.add(b); f.add(p1); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { p.show(); } // main class public static void main(String args[]) { pop p = new pop(); }}
Output:
Output:
Java Program to create a popup (add a panel) and display it on a parent frame and also add an action listener to the popup: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We will set the look and feel to System look and feel. We add this popup to a frame f titled “pop”, we will create a label and a button b19 titled “OK”( we will set the font of the label to a specified font object) and add it to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). finally, the frame is displayed using show() function.
Java Program to create a popup (add a panel) and display it on a parent frame and also add an action listener to the popup: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We will set the look and feel to System look and feel. We add this popup to a frame f titled “pop”, we will create a label and a button b19 titled “OK”( we will set the font of the label to a specified font object) and add it to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). finally, the frame is displayed using show() function.
Java
// Java Program to create a popup (add a panel) and// display it on a parent frame and also// add action listener to the popupimport javax.swing.*;import java.awt.*;import java.awt.event.*;class pop1 extends JFrame implements ActionListener { // popup Popup po; // frame JFrame f; // panel JPanel p; // popupfactory PopupFactory pf; // constructor pop1() { // create a frame f = new JFrame("pop"); f.setSize(400, 400); pf = new PopupFactory(); // create a label JLabel l = new JLabel("This is a popup menu"); // create a new button JButton b19 = new JButton("OK"); // add action listener b19.addActionListener(this); try { // set windows look and feel UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName()); } catch (Exception e) { } // create a panel p = new JPanel(); p.setBackground(Color.blue); // create a font Font fo = new Font("BOLD", 1, 14); l.setFont(fo); // add contents to panel p.add(l); p.add(b19); p.setLayout(new GridLayout(2, 1)); // create a popup po = pf.getPopup(f, p, 180, 100); // create a button JButton b = new JButton("click"); // add action listener b.addActionListener(this); // create a panel JPanel p1 = new JPanel(); p1.add(b); f.add(p1); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String d = e.getActionCommand(); // if ok button is pressed hide the popup if (d.equals("OK")) { po.hide(); // create a popup po = pf.getPopup(f, p, 180, 100); } else po.show(); } // main class public static void main(String args[]) { pop1 p = new pop1(); }}
Output:
Output:
https://docs.oracle.com/javase/7/docs/api/javax/swing/Popup.html
https://docs.oracle.com/javase/7/docs/api/javax/swing/PopupFactory.html
ManasChhabra2
surindertarika1234
java-swing
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
|
[
{
"code": null,
"e": 23974,
"s": 23946,
"text": "\n16 Jun, 2021"
},
{
"code": null,
"e": 24379,
"s": 23974,
"text": "Popup and PopupFactory are a part of the Java Swing library. Popups are used when we want to display to the user a Component on the top of all the other Components in that particular containment hierarchy. PopupFactory is the class that is used to create popups. Popups have a very small life cycle, and generally are lightweight components having limited sub-components.Constructor for the class are : "
},
{
"code": null,
"e": 24431,
"s": 24379,
"text": "PopupFactory(): creates an object for popup factory"
},
{
"code": null,
"e": 24483,
"s": 24431,
"text": "PopupFactory(): creates an object for popup factory"
},
{
"code": null,
"e": 24508,
"s": 24483,
"text": "Commonly used methods: "
},
{
"code": null,
"e": 24561,
"s": 24508,
"text": "Below programs will illustrate the use of a popup: "
},
{
"code": null,
"e": 25259,
"s": 24561,
"text": "Java Program to create a popup and display it on a parent frame: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We add this popup to a frame f titled “pop” we will create a label and add t to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). Finally, the frame is displayed using show() function. "
},
{
"code": null,
"e": 25957,
"s": 25259,
"text": "Java Program to create a popup and display it on a parent frame: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We add this popup to a frame f titled “pop” we will create a label and add t to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). Finally, the frame is displayed using show() function. "
},
{
"code": null,
"e": 25962,
"s": 25957,
"text": "Java"
},
{
"code": "// Java Program to create a popup and display// it on a parent frameimport javax.swing.*;import java.awt.*;import java.awt.event.*;class pop extends JFrame implements ActionListener { // popup Popup p; // constructor pop() { // create a frame JFrame f = new JFrame(\"pop\"); // create a label JLabel l = new JLabel(\"This is a popup\"); f.setSize(400, 400); PopupFactory pf = new PopupFactory(); // create a panel JPanel p2 = new JPanel(); // set Background of panel p2.setBackground(Color.red); p2.add(l); // create a popup p = pf.getPopup(f, p2, 180, 100); // create a button JButton b = new JButton(\"click\"); // add action listener b.addActionListener(this); // create a panel JPanel p1 = new JPanel(); p1.add(b); f.add(p1); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { p.show(); } // main class public static void main(String args[]) { pop p = new pop(); }}",
"e": 27083,
"s": 25962,
"text": null
},
{
"code": null,
"e": 27093,
"s": 27083,
"text": "Output: "
},
{
"code": null,
"e": 27103,
"s": 27093,
"text": "Output: "
},
{
"code": null,
"e": 28009,
"s": 27103,
"text": "Java Program to create a popup (add a panel) and display it on a parent frame and also add an action listener to the popup: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We will set the look and feel to System look and feel. We add this popup to a frame f titled “pop”, we will create a label and a button b19 titled “OK”( we will set the font of the label to a specified font object) and add it to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). finally, the frame is displayed using show() function. "
},
{
"code": null,
"e": 28915,
"s": 28009,
"text": "Java Program to create a popup (add a panel) and display it on a parent frame and also add an action listener to the popup: We create a popup p by creating a popup factory and using the function getpopup() which returns a popup. We will set the look and feel to System look and feel. We add this popup to a frame f titled “pop”, we will create a label and a button b19 titled “OK”( we will set the font of the label to a specified font object) and add it to a container panel p2 and set the background of panel p2 using setBackground() function. We will add the container panel p2 to the popup. We will also create a button b titled “click” added with an action listener and displays the popup when the button is pressed. The button b is added to a panel and the panel is added to the frame. Frame is set to the size 400,400 using setSize(400,400). finally, the frame is displayed using show() function. "
},
{
"code": null,
"e": 28920,
"s": 28915,
"text": "Java"
},
{
"code": "// Java Program to create a popup (add a panel) and// display it on a parent frame and also// add action listener to the popupimport javax.swing.*;import java.awt.*;import java.awt.event.*;class pop1 extends JFrame implements ActionListener { // popup Popup po; // frame JFrame f; // panel JPanel p; // popupfactory PopupFactory pf; // constructor pop1() { // create a frame f = new JFrame(\"pop\"); f.setSize(400, 400); pf = new PopupFactory(); // create a label JLabel l = new JLabel(\"This is a popup menu\"); // create a new button JButton b19 = new JButton(\"OK\"); // add action listener b19.addActionListener(this); try { // set windows look and feel UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName()); } catch (Exception e) { } // create a panel p = new JPanel(); p.setBackground(Color.blue); // create a font Font fo = new Font(\"BOLD\", 1, 14); l.setFont(fo); // add contents to panel p.add(l); p.add(b19); p.setLayout(new GridLayout(2, 1)); // create a popup po = pf.getPopup(f, p, 180, 100); // create a button JButton b = new JButton(\"click\"); // add action listener b.addActionListener(this); // create a panel JPanel p1 = new JPanel(); p1.add(b); f.add(p1); f.show(); } // if the button is pressed public void actionPerformed(ActionEvent e) { String d = e.getActionCommand(); // if ok button is pressed hide the popup if (d.equals(\"OK\")) { po.hide(); // create a popup po = pf.getPopup(f, p, 180, 100); } else po.show(); } // main class public static void main(String args[]) { pop1 p = new pop1(); }}",
"e": 30901,
"s": 28920,
"text": null
},
{
"code": null,
"e": 30911,
"s": 30901,
"text": "Output: "
},
{
"code": null,
"e": 30921,
"s": 30911,
"text": "Output: "
},
{
"code": null,
"e": 30986,
"s": 30921,
"text": "https://docs.oracle.com/javase/7/docs/api/javax/swing/Popup.html"
},
{
"code": null,
"e": 31058,
"s": 30986,
"text": "https://docs.oracle.com/javase/7/docs/api/javax/swing/PopupFactory.html"
},
{
"code": null,
"e": 31072,
"s": 31058,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 31091,
"s": 31072,
"text": "surindertarika1234"
},
{
"code": null,
"e": 31102,
"s": 31091,
"text": "java-swing"
},
{
"code": null,
"e": 31107,
"s": 31102,
"text": "Java"
},
{
"code": null,
"e": 31112,
"s": 31107,
"text": "Java"
},
{
"code": null,
"e": 31210,
"s": 31112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31225,
"s": 31210,
"text": "Stream In Java"
},
{
"code": null,
"e": 31246,
"s": 31225,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31292,
"s": 31246,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31311,
"s": 31292,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31341,
"s": 31311,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31358,
"s": 31341,
"text": "Generics in Java"
},
{
"code": null,
"e": 31401,
"s": 31358,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 31422,
"s": 31401,
"text": "Introduction to Java"
},
{
"code": null,
"e": 31451,
"s": 31422,
"text": "HashMap get() Method in Java"
}
] |
Visualizing Three-Dimensional Data in Python | Towards Data Science
|
When you are measuring the dependence of a property on multiple independent variables, you now need to plot data in three dimensions. Examples of this typically occur with spatial measurements, where there is an intensity associated with each (x, y) point, like in a rastered microscopy measurement or spatial diffraction pattern. To visualize this data, we have a few options at our disposal — we will explore creating heatmaps, contour plots (unfilled and filled), and a 3D plot.
The dataset I will use for this example is a 2 μm x 2 μm micrograph from an atomic force microscope (AFM). First, we import packages — the two new packages we are adding this time are make_axes_locatable, which will help us with managing the colorbar for our plots, and Axes3D, which we need for our 3D plot:
# Import packages%matplotlib inlineimport matplotlib as mplimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatablefrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np
We will now load our AFM data, again using numpy.loadtxt which will directly load our data into a 2D numpy array.
# Import AFM dataafm_data = np.loadtxt('./afm.txt')
We can then inspect a few rows our loaded data:
# Print some of the AFM dataprint(afm_data[0:5])>>> [[4.8379e-08 4.7485e-08 4.6752e-08 ... 6.0293e-08 5.7804e-08 5.4779e-08] [5.0034e-08 4.9139e-08 4.7975e-08 ... 5.7221e-08 5.4744e-08 5.1316e-08] [5.2966e-08 5.2099e-08 5.1076e-08 ... 5.4061e-08 5.0873e-08 4.7128e-08] [5.7146e-08 5.6070e-08 5.4871e-08 ... 5.1104e-08 4.6898e-08 4.1961e-08] [6.2167e-08 6.0804e-08 5.9588e-08 ... 4.7038e-08 4.2115e-08 3.7258e-08]]
We have a 256 x 256 array of points with each value corresponding to the measured height (in meters) at that position. Since we know that our data would be more meaningful if presented in nanometers, we can scale all our values by this constant parameter:
# Convert data to nanometers (nm)afm_data *= (10**9)
Now we can go ahead and start visualizing our data. We start with setting some global parameters (edit these as you like, but these are settings I use):
# Edit overall plot parameters# Font parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 18# Edit axes parametersmpl.rcParams['axes.linewidth'] = 2# Tick propertiesmpl.rcParams['xtick.major.size'] = 10mpl.rcParams['xtick.major.width'] = 2mpl.rcParams['xtick.direction'] = 'out'mpl.rcParams['ytick.major.size'] = 10mpl.rcParams['ytick.major.width'] = 2mpl.rcParams['ytick.direction'] = 'out'
For the heatmap visualization, we will use the imshow function to display our data as an image. First, we create a figure and add a main axis to show our image. Additionally, we will remove tick marks since we will be adding a scale bar.
# Create figure and add axisfig = plt.figure(figsize=(4,4))ax = fig.add_subplot(111)# Remove x and y ticksax.xaxis.set_tick_params(size=0)ax.yaxis.set_tick_params(size=0)ax.set_xticks([])ax.set_yticks([])
Now we display our image with the following command:
# Show AFM imageimg = ax.imshow(afm_data, origin='lower', cmap='YlGnBu_r', extent=(0, 2, 0, 2), vmin=0, vmax=200)
origin — images are typically shown with their origin as the top left corner, so by using origin='lower' we force the origin to be a the bottom left
cmap — the colormap for our image. All available matplotlib colormaps can be found here, and adding _r to any colormap name will reverse it.
extent — imshow will plot our image using pixels unless we tell it what range these pixels correspond to. In this case, we know that our image is 2 μm x 2 μm, so we make our extent=(x_min, x_max, y_min, y_max) equal to (0, 2, 0, 2)
vmin — the value to set to the minimum of our colormap
vmax — the value to set to the maximum of our colormap
Now, we should add our scale bar, so anyone looking at the plot has an idea of the size scale. We will generate the bar using plt.fill_between to create a filled rectangle, and then add a text label on top.
# Create scale barax.fill_between(x=[1.4, 1.9], y1=[0.1, 0.1], y2=[0.2, 0.2], color='white')
x — the x-range of our filled shape (since our image goes from [0, 2] the range specified [1.4, 1.9] is 0.5 μm or 500 nm)
y1 — the bottom y-value (corresponding to values of x) of our filled shape
y2 — the top y-value (corresponding to values of x) of our filled shape
ax.text(x=1.65, y=0.25, s='500 nm', va='bottom', ha='center', color='white', size=20)
x — x-position of text
y — y-position of text
s — text string
va — vertical alignment ( bottom means that y corresponds to the bottom of the text)
ha — horizontal alignment ( center means that x corresponds to the center of the text)
Finally, we can add a colorbar to show how colors in our image correspond to height values. First, we create a new axis object for the colorbar, which we do by appending a new axis to the right of our original axis using the make_axes_locatable().append_axes function. We pass our original axes object ax to the function:
# Create axis for colorbarcbar_ax = make_axes_locatable(ax).append_axes(position='right', size='5%', pad=0.1)
position — where to append next axes, in this case to the right of the original image
size — the size of the new axes along the position direction, relative to the original axes (5% of the image width)
pad — the padding (in absolute coordinates) between the two axes
Now, we turn this new axis object into a colorbar:
# Create colorbarcbar = fig.colorbar(mappable=img, cax=cbar_ax)
mappable — the image/plot to map to the colorbar (we created img when we used imshow earlier)
cax — the axis to use for the colorbar
Finally, we adjust the tick marks and labels for the colorbar:
# Edit colorbar ticks and labelscbar.set_ticks([0, 50, 100, 150, 200])cbar.set_ticklabels(['0', '50', '100', '150', '200 nm'])
Just like in a topographical map found at most hiking trails, we can also present three-dimensional data with contour lines of constant intensity. We will now plot the same AFM data using a contour plot.
We use the same code as before, with the following line changed (I have added zorder=1 to ensure that the contour plot is below the scale bar as lower z-order numbers are drawn first):
# Show AFM contour plotax.contour(afm_data, extent=(0, 2, 0, 2), cmap='YlGnBu_r', vmin=0, vmax=200, zorder=1)
If we use contourf instead of contour, we can create filled contours instead of just contour lines:
# Show AFM filled contour plotax.contourf(afm_data, extent=(0, 2, 0, 2), cmap='YlGnBu_r', vmin=0, vmax=200)
In this case, a lot of the finer details from imshow are not well captured in contour or contourf. If you have fairly smooth data without a lot of smaller details, the contour images may look better than the heatmap. Ultimately, you want to present your data in as transparent and straightforward a manner as possible, so in this case, the heatmap with colorbar is probably best.
Up to this point, we have limited our plots to two-dimensions and used the color scale to let the reader infer the intensity. If we wanted to give a better sense of these intensity values, we can actually plot our data in 3D.
We start by creating a 3D axis with the following code, the key here is that we are using projection=’3d' when we generate our axis object:
# Create figure and add axisfig = plt.figure(figsize=(8,6))ax = plt.subplot(111, projection='3d')
The gray panes and axis grids add clutter to our plot, so let’s remove them. Additionally, I am going to add the colorbar again for height — the z-axis will get very compressed because of the perspective view, so I will remove it.
# Remove gray panes and axis gridax.xaxis.pane.fill = Falseax.xaxis.pane.set_edgecolor('white')ax.yaxis.pane.fill = Falseax.yaxis.pane.set_edgecolor('white')ax.zaxis.pane.fill = Falseax.zaxis.pane.set_edgecolor('white')ax.grid(False)# Remove z-axisax.w_zaxis.line.set_lw(0.)ax.set_zticks([])
For the surface plot, we need 2D arrays of x and y values to correspond to the intensity values. We do this by creating a mesh-grid with np.meshgrid — our inputs to this function are an array of x-values and y-values to repeat in the grid, which we will generate using np.linspace.
# Create meshgridX, Y = np.meshgrid(np.linspace(0, 2, len(afm_data)), np.linspace(0, 2, len(afm_data)))
Now that we have our meshgrid, we can plot our 3D data:
# Plot surfaceplot = ax.plot_surface(X=X, Y=Y, Z=afm_data, cmap='YlGnBu_r', vmin=0, vmax=200)
X — grid of x-values
Y — grid of y-values
Z — grid of z-values
Now, we can adjust the view of plot — there are three parameters that we control for this: elevation, azimuthal angle (in the x-y plane), and distance from the axes, which roughly correspond to the spherical coordinate system values of φ, θ, and r, respectively. I am setting the azimuthal angle to 225 ̊ because we want the x and y axes to meet at (0, 0).
# Adjust plot viewax.view_init(elev=50, azim=225)ax.dist=11
Add the colorbar:
# Add colorbarcbar = fig.colorbar(plot, ax=ax, shrink=0.6)cbar.set_ticks([0, 50, 100, 150, 200])cbar.set_ticklabels(['0', '50', '100', '150', '200 nm'])
shrink — how much to shrink the colorbar relative to its default size
Finally, we edit some of the aesthetics — the tick marks on the x and y-axes, axis limits, and the axis labels.
# Set tick marksax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))# Set axis labelsax.set_xlabel(r'$\mathregular{\mu}$m', labelpad=20)ax.set_ylabel(r'$\mathregular{\mu}$m', labelpad=20)# Set z-limitax.set_zlim(50, 200)
This plot lets the reader actually see the height fluctuations in addition to using color for intensity values. However, a noisier dataset could lead to a very messy 3D plot.
I hope this tutorial was helpful is addressing different methods to plot three-dimensional datasets. Examples are available at this Github repository. Thanks for reading!
|
[
{
"code": null,
"e": 654,
"s": 172,
"text": "When you are measuring the dependence of a property on multiple independent variables, you now need to plot data in three dimensions. Examples of this typically occur with spatial measurements, where there is an intensity associated with each (x, y) point, like in a rastered microscopy measurement or spatial diffraction pattern. To visualize this data, we have a few options at our disposal — we will explore creating heatmaps, contour plots (unfilled and filled), and a 3D plot."
},
{
"code": null,
"e": 963,
"s": 654,
"text": "The dataset I will use for this example is a 2 μm x 2 μm micrograph from an atomic force microscope (AFM). First, we import packages — the two new packages we are adding this time are make_axes_locatable, which will help us with managing the colorbar for our plots, and Axes3D, which we need for our 3D plot:"
},
{
"code": null,
"e": 1179,
"s": 963,
"text": "# Import packages%matplotlib inlineimport matplotlib as mplimport matplotlib.pyplot as pltfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatablefrom mpl_toolkits.mplot3d import Axes3Dimport numpy as np"
},
{
"code": null,
"e": 1293,
"s": 1179,
"text": "We will now load our AFM data, again using numpy.loadtxt which will directly load our data into a 2D numpy array."
},
{
"code": null,
"e": 1345,
"s": 1293,
"text": "# Import AFM dataafm_data = np.loadtxt('./afm.txt')"
},
{
"code": null,
"e": 1393,
"s": 1345,
"text": "We can then inspect a few rows our loaded data:"
},
{
"code": null,
"e": 1807,
"s": 1393,
"text": "# Print some of the AFM dataprint(afm_data[0:5])>>> [[4.8379e-08 4.7485e-08 4.6752e-08 ... 6.0293e-08 5.7804e-08 5.4779e-08] [5.0034e-08 4.9139e-08 4.7975e-08 ... 5.7221e-08 5.4744e-08 5.1316e-08] [5.2966e-08 5.2099e-08 5.1076e-08 ... 5.4061e-08 5.0873e-08 4.7128e-08] [5.7146e-08 5.6070e-08 5.4871e-08 ... 5.1104e-08 4.6898e-08 4.1961e-08] [6.2167e-08 6.0804e-08 5.9588e-08 ... 4.7038e-08 4.2115e-08 3.7258e-08]]"
},
{
"code": null,
"e": 2063,
"s": 1807,
"text": "We have a 256 x 256 array of points with each value corresponding to the measured height (in meters) at that position. Since we know that our data would be more meaningful if presented in nanometers, we can scale all our values by this constant parameter:"
},
{
"code": null,
"e": 2116,
"s": 2063,
"text": "# Convert data to nanometers (nm)afm_data *= (10**9)"
},
{
"code": null,
"e": 2269,
"s": 2116,
"text": "Now we can go ahead and start visualizing our data. We start with setting some global parameters (edit these as you like, but these are settings I use):"
},
{
"code": null,
"e": 2684,
"s": 2269,
"text": "# Edit overall plot parameters# Font parametersmpl.rcParams['font.family'] = 'Avenir'mpl.rcParams['font.size'] = 18# Edit axes parametersmpl.rcParams['axes.linewidth'] = 2# Tick propertiesmpl.rcParams['xtick.major.size'] = 10mpl.rcParams['xtick.major.width'] = 2mpl.rcParams['xtick.direction'] = 'out'mpl.rcParams['ytick.major.size'] = 10mpl.rcParams['ytick.major.width'] = 2mpl.rcParams['ytick.direction'] = 'out'"
},
{
"code": null,
"e": 2922,
"s": 2684,
"text": "For the heatmap visualization, we will use the imshow function to display our data as an image. First, we create a figure and add a main axis to show our image. Additionally, we will remove tick marks since we will be adding a scale bar."
},
{
"code": null,
"e": 3127,
"s": 2922,
"text": "# Create figure and add axisfig = plt.figure(figsize=(4,4))ax = fig.add_subplot(111)# Remove x and y ticksax.xaxis.set_tick_params(size=0)ax.yaxis.set_tick_params(size=0)ax.set_xticks([])ax.set_yticks([])"
},
{
"code": null,
"e": 3180,
"s": 3127,
"text": "Now we display our image with the following command:"
},
{
"code": null,
"e": 3294,
"s": 3180,
"text": "# Show AFM imageimg = ax.imshow(afm_data, origin='lower', cmap='YlGnBu_r', extent=(0, 2, 0, 2), vmin=0, vmax=200)"
},
{
"code": null,
"e": 3443,
"s": 3294,
"text": "origin — images are typically shown with their origin as the top left corner, so by using origin='lower' we force the origin to be a the bottom left"
},
{
"code": null,
"e": 3584,
"s": 3443,
"text": "cmap — the colormap for our image. All available matplotlib colormaps can be found here, and adding _r to any colormap name will reverse it."
},
{
"code": null,
"e": 3816,
"s": 3584,
"text": "extent — imshow will plot our image using pixels unless we tell it what range these pixels correspond to. In this case, we know that our image is 2 μm x 2 μm, so we make our extent=(x_min, x_max, y_min, y_max) equal to (0, 2, 0, 2)"
},
{
"code": null,
"e": 3871,
"s": 3816,
"text": "vmin — the value to set to the minimum of our colormap"
},
{
"code": null,
"e": 3926,
"s": 3871,
"text": "vmax — the value to set to the maximum of our colormap"
},
{
"code": null,
"e": 4133,
"s": 3926,
"text": "Now, we should add our scale bar, so anyone looking at the plot has an idea of the size scale. We will generate the bar using plt.fill_between to create a filled rectangle, and then add a text label on top."
},
{
"code": null,
"e": 4226,
"s": 4133,
"text": "# Create scale barax.fill_between(x=[1.4, 1.9], y1=[0.1, 0.1], y2=[0.2, 0.2], color='white')"
},
{
"code": null,
"e": 4348,
"s": 4226,
"text": "x — the x-range of our filled shape (since our image goes from [0, 2] the range specified [1.4, 1.9] is 0.5 μm or 500 nm)"
},
{
"code": null,
"e": 4423,
"s": 4348,
"text": "y1 — the bottom y-value (corresponding to values of x) of our filled shape"
},
{
"code": null,
"e": 4495,
"s": 4423,
"text": "y2 — the top y-value (corresponding to values of x) of our filled shape"
},
{
"code": null,
"e": 4581,
"s": 4495,
"text": "ax.text(x=1.65, y=0.25, s='500 nm', va='bottom', ha='center', color='white', size=20)"
},
{
"code": null,
"e": 4604,
"s": 4581,
"text": "x — x-position of text"
},
{
"code": null,
"e": 4627,
"s": 4604,
"text": "y — y-position of text"
},
{
"code": null,
"e": 4643,
"s": 4627,
"text": "s — text string"
},
{
"code": null,
"e": 4728,
"s": 4643,
"text": "va — vertical alignment ( bottom means that y corresponds to the bottom of the text)"
},
{
"code": null,
"e": 4815,
"s": 4728,
"text": "ha — horizontal alignment ( center means that x corresponds to the center of the text)"
},
{
"code": null,
"e": 5137,
"s": 4815,
"text": "Finally, we can add a colorbar to show how colors in our image correspond to height values. First, we create a new axis object for the colorbar, which we do by appending a new axis to the right of our original axis using the make_axes_locatable().append_axes function. We pass our original axes object ax to the function:"
},
{
"code": null,
"e": 5247,
"s": 5137,
"text": "# Create axis for colorbarcbar_ax = make_axes_locatable(ax).append_axes(position='right', size='5%', pad=0.1)"
},
{
"code": null,
"e": 5333,
"s": 5247,
"text": "position — where to append next axes, in this case to the right of the original image"
},
{
"code": null,
"e": 5449,
"s": 5333,
"text": "size — the size of the new axes along the position direction, relative to the original axes (5% of the image width)"
},
{
"code": null,
"e": 5514,
"s": 5449,
"text": "pad — the padding (in absolute coordinates) between the two axes"
},
{
"code": null,
"e": 5565,
"s": 5514,
"text": "Now, we turn this new axis object into a colorbar:"
},
{
"code": null,
"e": 5629,
"s": 5565,
"text": "# Create colorbarcbar = fig.colorbar(mappable=img, cax=cbar_ax)"
},
{
"code": null,
"e": 5723,
"s": 5629,
"text": "mappable — the image/plot to map to the colorbar (we created img when we used imshow earlier)"
},
{
"code": null,
"e": 5762,
"s": 5723,
"text": "cax — the axis to use for the colorbar"
},
{
"code": null,
"e": 5825,
"s": 5762,
"text": "Finally, we adjust the tick marks and labels for the colorbar:"
},
{
"code": null,
"e": 5952,
"s": 5825,
"text": "# Edit colorbar ticks and labelscbar.set_ticks([0, 50, 100, 150, 200])cbar.set_ticklabels(['0', '50', '100', '150', '200 nm'])"
},
{
"code": null,
"e": 6156,
"s": 5952,
"text": "Just like in a topographical map found at most hiking trails, we can also present three-dimensional data with contour lines of constant intensity. We will now plot the same AFM data using a contour plot."
},
{
"code": null,
"e": 6341,
"s": 6156,
"text": "We use the same code as before, with the following line changed (I have added zorder=1 to ensure that the contour plot is below the scale bar as lower z-order numbers are drawn first):"
},
{
"code": null,
"e": 6451,
"s": 6341,
"text": "# Show AFM contour plotax.contour(afm_data, extent=(0, 2, 0, 2), cmap='YlGnBu_r', vmin=0, vmax=200, zorder=1)"
},
{
"code": null,
"e": 6551,
"s": 6451,
"text": "If we use contourf instead of contour, we can create filled contours instead of just contour lines:"
},
{
"code": null,
"e": 6659,
"s": 6551,
"text": "# Show AFM filled contour plotax.contourf(afm_data, extent=(0, 2, 0, 2), cmap='YlGnBu_r', vmin=0, vmax=200)"
},
{
"code": null,
"e": 7039,
"s": 6659,
"text": "In this case, a lot of the finer details from imshow are not well captured in contour or contourf. If you have fairly smooth data without a lot of smaller details, the contour images may look better than the heatmap. Ultimately, you want to present your data in as transparent and straightforward a manner as possible, so in this case, the heatmap with colorbar is probably best."
},
{
"code": null,
"e": 7265,
"s": 7039,
"text": "Up to this point, we have limited our plots to two-dimensions and used the color scale to let the reader infer the intensity. If we wanted to give a better sense of these intensity values, we can actually plot our data in 3D."
},
{
"code": null,
"e": 7405,
"s": 7265,
"text": "We start by creating a 3D axis with the following code, the key here is that we are using projection=’3d' when we generate our axis object:"
},
{
"code": null,
"e": 7503,
"s": 7405,
"text": "# Create figure and add axisfig = plt.figure(figsize=(8,6))ax = plt.subplot(111, projection='3d')"
},
{
"code": null,
"e": 7734,
"s": 7503,
"text": "The gray panes and axis grids add clutter to our plot, so let’s remove them. Additionally, I am going to add the colorbar again for height — the z-axis will get very compressed because of the perspective view, so I will remove it."
},
{
"code": null,
"e": 8026,
"s": 7734,
"text": "# Remove gray panes and axis gridax.xaxis.pane.fill = Falseax.xaxis.pane.set_edgecolor('white')ax.yaxis.pane.fill = Falseax.yaxis.pane.set_edgecolor('white')ax.zaxis.pane.fill = Falseax.zaxis.pane.set_edgecolor('white')ax.grid(False)# Remove z-axisax.w_zaxis.line.set_lw(0.)ax.set_zticks([])"
},
{
"code": null,
"e": 8308,
"s": 8026,
"text": "For the surface plot, we need 2D arrays of x and y values to correspond to the intensity values. We do this by creating a mesh-grid with np.meshgrid — our inputs to this function are an array of x-values and y-values to repeat in the grid, which we will generate using np.linspace."
},
{
"code": null,
"e": 8412,
"s": 8308,
"text": "# Create meshgridX, Y = np.meshgrid(np.linspace(0, 2, len(afm_data)), np.linspace(0, 2, len(afm_data)))"
},
{
"code": null,
"e": 8468,
"s": 8412,
"text": "Now that we have our meshgrid, we can plot our 3D data:"
},
{
"code": null,
"e": 8562,
"s": 8468,
"text": "# Plot surfaceplot = ax.plot_surface(X=X, Y=Y, Z=afm_data, cmap='YlGnBu_r', vmin=0, vmax=200)"
},
{
"code": null,
"e": 8583,
"s": 8562,
"text": "X — grid of x-values"
},
{
"code": null,
"e": 8604,
"s": 8583,
"text": "Y — grid of y-values"
},
{
"code": null,
"e": 8625,
"s": 8604,
"text": "Z — grid of z-values"
},
{
"code": null,
"e": 8982,
"s": 8625,
"text": "Now, we can adjust the view of plot — there are three parameters that we control for this: elevation, azimuthal angle (in the x-y plane), and distance from the axes, which roughly correspond to the spherical coordinate system values of φ, θ, and r, respectively. I am setting the azimuthal angle to 225 ̊ because we want the x and y axes to meet at (0, 0)."
},
{
"code": null,
"e": 9042,
"s": 8982,
"text": "# Adjust plot viewax.view_init(elev=50, azim=225)ax.dist=11"
},
{
"code": null,
"e": 9060,
"s": 9042,
"text": "Add the colorbar:"
},
{
"code": null,
"e": 9213,
"s": 9060,
"text": "# Add colorbarcbar = fig.colorbar(plot, ax=ax, shrink=0.6)cbar.set_ticks([0, 50, 100, 150, 200])cbar.set_ticklabels(['0', '50', '100', '150', '200 nm'])"
},
{
"code": null,
"e": 9283,
"s": 9213,
"text": "shrink — how much to shrink the colorbar relative to its default size"
},
{
"code": null,
"e": 9395,
"s": 9283,
"text": "Finally, we edit some of the aesthetics — the tick marks on the x and y-axes, axis limits, and the axis labels."
},
{
"code": null,
"e": 9682,
"s": 9395,
"text": "# Set tick marksax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.5))# Set axis labelsax.set_xlabel(r'$\\mathregular{\\mu}$m', labelpad=20)ax.set_ylabel(r'$\\mathregular{\\mu}$m', labelpad=20)# Set z-limitax.set_zlim(50, 200)"
},
{
"code": null,
"e": 9857,
"s": 9682,
"text": "This plot lets the reader actually see the height fluctuations in addition to using color for intensity values. However, a noisier dataset could lead to a very messy 3D plot."
}
] |
Java Program For Finding The Middle Element Of A Given Linked List - GeeksforGeeks
|
08 Dec, 2021
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.
Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.
Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list.
Below image shows how printMiddle function works in the code :
Java
// Java program to find middle of
// the linked list
class LinkedList
{
// Head of linked list
Node head;
// Linked list node
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
// Function to print middle of
// the linked list
void printMiddle()
{
Node slow_ptr = head;
Node fast_ptr = head;
if (head != null)
{
while (fast_ptr != null &&
fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
slow_ptr = slow_ptr.next;
}
System.out.println("The middle element is [" +
slow_ptr.data + "]");
}
}
// Inserts a new Node at front of the list.
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);
// 3. Make next of new Node as head
new_node.next = head;
// 4. Move the head to point to new Node
head = new_node;
}
// This function prints contents of linked list
// starting from the given node
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data + "->");
tnode = tnode.next;
}
System.out.println("NULL");
}
// Driver code
public static void main(String [] args)
{
LinkedList llist = new LinkedList();
for (int i = 5; i > 0; --i)
{
llist.push(i);
llist.printList();
llist.printMiddle();
}
}
}
// This code is contributed by Rajat Mishra
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method.
Java
// Java program to implement the
// above approach
class GFG
{
static Node head;
// Link list node
class Node
{
int data;
Node next;
// Constructor
public Node(Node next,
int data)
{
this.data = data;
this.next = next;
}
}
// Function to get the middle of
// the linked list
void printMiddle(Node head)
{
int count = 0;
Node mid = head;
while (head != null)
{
// Update mid, when 'count'
// is odd number
if ((count % 2) == 1)
mid = mid.next;
++count;
head = head.next;
}
// If empty list is provided
if (mid != null)
System.out.println("The middle element is [" +
mid.data + "]\n");
}
void push(Node head_ref, int new_data)
{
// Allocate node
Node new_node = new Node(head_ref,
new_data);
// Move the head to point to the new node
head = new_node;
}
// A utility function to print a
// given linked list
void printList(Node head)
{
while (head != null)
{
System.out.print(head.data + "-> ");
head = head.next;
}
System.out.println("null");
}
// Driver code
public static void main(String[] args)
{
GFG ll = new GFG();
for(int i = 5; i > 0; i--)
{
ll.push(head, i);
ll.printList(head);
ll.printMiddle(head);
}
}
}
// This code is contributed by mark_3
Output:
5->NULL
The middle element is [5]
4->5->NULL
The middle element is [5]
3->4->5->NULL
The middle element is [4]
2->3->4->5->NULL
The middle element is [4]
1->2->3->4->5->NULL
The middle element is [3]
Please refer complete article on Find the middle of a given linked list for more details!
Adobe
Amazon
Flipkart
GE
Hike
Linked Lists
MAQ Software
Microsoft
Morgan Stanley
Nagarro
Payu
Qualcomm
Samsung
Veritas
VMWare
Wipro
Zoho
Java
Java Programs
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 24098,
"s": 24067,
"text": " \n08 Dec, 2021\n"
},
{
"code": null,
"e": 24437,
"s": 24098,
"text": "Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4. "
},
{
"code": null,
"e": 24580,
"s": 24437,
"text": "Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2. "
},
{
"code": null,
"e": 24779,
"s": 24580,
"text": "Method 2: Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list."
},
{
"code": null,
"e": 24842,
"s": 24779,
"text": "Below image shows how printMiddle function works in the code :"
},
{
"code": null,
"e": 24847,
"s": 24842,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java program to find middle of \n// the linked list \nclass LinkedList \n{ \n // Head of linked list \n Node head; \n \n // Linked list node \n class Node \n { \n int data; \n Node next; \n Node(int d) \n { \n data = d; \n next = null; \n } \n } \n \n // Function to print middle of \n // the linked list \n void printMiddle() \n { \n Node slow_ptr = head; \n Node fast_ptr = head; \n if (head != null) \n { \n while (fast_ptr != null && \n fast_ptr.next != null) \n { \n fast_ptr = fast_ptr.next.next; \n slow_ptr = slow_ptr.next; \n } \n System.out.println(\"The middle element is [\" + \n slow_ptr.data + \"]\"); \n } \n } \n \n // Inserts a new Node at front of the list. \n public void push(int new_data) \n { \n /* 1 & 2: Allocate the Node & \n Put in the data*/\n Node new_node = new Node(new_data); \n \n // 3. Make next of new Node as head \n new_node.next = head; \n \n // 4. Move the head to point to new Node \n head = new_node; \n } \n \n // This function prints contents of linked list \n // starting from the given node \n public void printList() \n { \n Node tnode = head; \n while (tnode != null) \n { \n System.out.print(tnode.data + \"->\"); \n tnode = tnode.next; \n } \n System.out.println(\"NULL\"); \n } \n \n // Driver code \n public static void main(String [] args) \n { \n LinkedList llist = new LinkedList(); \n for (int i = 5; i > 0; --i) \n { \n llist.push(i); \n llist.printList(); \n llist.printMiddle(); \n } \n } \n} \n// This code is contributed by Rajat Mishra \n\n\n\n\n\n",
"e": 26767,
"s": 24857,
"text": null
},
{
"code": null,
"e": 26775,
"s": 26767,
"text": "Output:"
},
{
"code": null,
"e": 26979,
"s": 26775,
"text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]"
},
{
"code": null,
"e": 27300,
"s": 26979,
"text": "Method 3: Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list. Thanks to Narendra Kangralkar for suggesting this method. "
},
{
"code": null,
"e": 27305,
"s": 27300,
"text": "Java"
},
{
"code": "\n\n\n\n\n\n\n// Java program to implement the \n// above approach \nclass GFG \n{ \n static Node head; \n \n // Link list node \n class Node \n { \n int data; \n Node next; \n \n // Constructor \n public Node(Node next, \n int data) \n { \n this.data = data; \n this.next = next; \n } \n } \n \n // Function to get the middle of \n // the linked list \n void printMiddle(Node head) \n { \n int count = 0; \n Node mid = head; \n \n while (head != null) \n { \n // Update mid, when 'count' \n // is odd number \n if ((count % 2) == 1) \n mid = mid.next; \n \n ++count; \n head = head.next; \n } \n \n // If empty list is provided \n if (mid != null) \n System.out.println(\"The middle element is [\" + \n mid.data + \"]\\n\"); \n } \n \n void push(Node head_ref, int new_data) \n { \n \n // Allocate node \n Node new_node = new Node(head_ref, \n new_data); \n \n // Move the head to point to the new node \n head = new_node; \n } \n \n // A utility function to print a \n // given linked list \n void printList(Node head) \n { \n while (head != null) \n { \n System.out.print(head.data + \"-> \"); \n head = head.next; \n } \n System.out.println(\"null\"); \n } \n \n // Driver code \n public static void main(String[] args) \n { \n GFG ll = new GFG(); \n \n for(int i = 5; i > 0; i--) \n { \n ll.push(head, i); \n ll.printList(head); \n ll.printMiddle(head); \n } \n } \n} \n// This code is contributed by mark_3 \n\n\n\n\n\n",
"e": 29145,
"s": 27315,
"text": null
},
{
"code": null,
"e": 29153,
"s": 29145,
"text": "Output:"
},
{
"code": null,
"e": 29357,
"s": 29153,
"text": "5->NULL\nThe middle element is [5]\n\n4->5->NULL\nThe middle element is [5]\n\n3->4->5->NULL\nThe middle element is [4]\n\n2->3->4->5->NULL\nThe middle element is [4]\n\n1->2->3->4->5->NULL\nThe middle element is [3]"
},
{
"code": null,
"e": 29447,
"s": 29357,
"text": "Please refer complete article on Find the middle of a given linked list for more details!"
},
{
"code": null,
"e": 29455,
"s": 29447,
"text": "\nAdobe\n"
},
{
"code": null,
"e": 29464,
"s": 29455,
"text": "\nAmazon\n"
},
{
"code": null,
"e": 29475,
"s": 29464,
"text": "\nFlipkart\n"
},
{
"code": null,
"e": 29480,
"s": 29475,
"text": "\nGE\n"
},
{
"code": null,
"e": 29487,
"s": 29480,
"text": "\nHike\n"
},
{
"code": null,
"e": 29502,
"s": 29487,
"text": "\nLinked Lists\n"
},
{
"code": null,
"e": 29517,
"s": 29502,
"text": "\nMAQ Software\n"
},
{
"code": null,
"e": 29529,
"s": 29517,
"text": "\nMicrosoft\n"
},
{
"code": null,
"e": 29546,
"s": 29529,
"text": "\nMorgan Stanley\n"
},
{
"code": null,
"e": 29556,
"s": 29546,
"text": "\nNagarro\n"
},
{
"code": null,
"e": 29563,
"s": 29556,
"text": "\nPayu\n"
},
{
"code": null,
"e": 29574,
"s": 29563,
"text": "\nQualcomm\n"
},
{
"code": null,
"e": 29584,
"s": 29574,
"text": "\nSamsung\n"
},
{
"code": null,
"e": 29594,
"s": 29584,
"text": "\nVeritas\n"
},
{
"code": null,
"e": 29603,
"s": 29594,
"text": "\nVMWare\n"
},
{
"code": null,
"e": 29611,
"s": 29603,
"text": "\nWipro\n"
},
{
"code": null,
"e": 29618,
"s": 29611,
"text": "\nZoho\n"
},
{
"code": null,
"e": 29625,
"s": 29618,
"text": "\nJava\n"
},
{
"code": null,
"e": 29641,
"s": 29625,
"text": "\nJava Programs\n"
},
{
"code": null,
"e": 29655,
"s": 29641,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 29860,
"s": 29655,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29906,
"s": 29860,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29927,
"s": 29906,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29942,
"s": 29927,
"text": "Stream In Java"
},
{
"code": null,
"e": 29959,
"s": 29942,
"text": "Generics in Java"
},
{
"code": null,
"e": 29978,
"s": 29959,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30022,
"s": 29978,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 30048,
"s": 30022,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30082,
"s": 30048,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30129,
"s": 30082,
"text": "Implementing a Linked List in Java using Class"
}
] |
Call by Value Vs Call by Reference in JavaScript - GeeksforGeeks
|
31 Aug, 2020
Call by Value: Suppose there is a variable named “a”. Now, we store a primitive value(boolean, integer, float, etc) in the variable “a”.
Let us store an integer value in “a”, Let a=5. Now the variable “a” stores 5 and has an address location where that primitive value sits in memory.
Now, suppose we copy the value of “a” in “b” by assignment (a=b). Now, “b” points to a new location in memory, containing the same data as variable “a”.
Thus, a=b=5 but both points to separate locations in memory.
This approach is called call by value where 2 variables become the same by copying the value but in 2 separate spots in the memory.
Features of call by value:
Function arguments are always passed by value.
It copies the value of a variable passed in a function to a local variable.
Both these variables occupy separate locations in memory. Thus, if changes are made in a particular variable it does not affect the other one.
Example:
JavaScript
<script type="text/javascript"> // By value (primitives) var a = 5; var b; b = a; a = 3; console.log(a); console.log(b);</script>
Output: “b” was just a copy of “a”. It has its own space in memory. When we change “a” it does not have any impact on the value of “b”.
By value
Call by reference: Let’s say, we have an object stored in the variable “a”. The variable stores the location or the address where the object lives. Now we set b=a. Now that new variable “b” instead of pointing to a new location in the memory, points to the same location where “a” does. No new object is created, no copy is created. Both the variables point to the same object. This is like having 2 names.
This is call by reference. It behaves quite differently from by value. All objects interact by reference.
Features of By reference:
In JavaScript, all objects interact by reference.
If an object is stored in a variable and that variable is made equal to another variable then both of them occupy the same location in memory.
Changes in one object variable affect the other object variable.
Example: Over here, when we set d=c, “d” points to the same location in memory where “c” does. At first, we have a name-value pair stored in “c”. Now when we change a property using “c”, it changes the property in “d” also because both point to the same object. Changes in one it affects.
Javascript
<script> // By reference (all objects (including functions)) var c = { greeting : 'Welcome' }; var d; d = c; // Mutating the value of c c.greeting = 'Welcome to geeksforgeeks'; console.log(c); console.log(d);</script>
Output:
By reference
Difference between call by value and call by reference:
Call by value
Call by reference
javascript-basics
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
|
[
{
"code": null,
"e": 24831,
"s": 24803,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 24968,
"s": 24831,
"text": "Call by Value: Suppose there is a variable named “a”. Now, we store a primitive value(boolean, integer, float, etc) in the variable “a”."
},
{
"code": null,
"e": 25116,
"s": 24968,
"text": "Let us store an integer value in “a”, Let a=5. Now the variable “a” stores 5 and has an address location where that primitive value sits in memory."
},
{
"code": null,
"e": 25269,
"s": 25116,
"text": "Now, suppose we copy the value of “a” in “b” by assignment (a=b). Now, “b” points to a new location in memory, containing the same data as variable “a”."
},
{
"code": null,
"e": 25330,
"s": 25269,
"text": "Thus, a=b=5 but both points to separate locations in memory."
},
{
"code": null,
"e": 25462,
"s": 25330,
"text": "This approach is called call by value where 2 variables become the same by copying the value but in 2 separate spots in the memory."
},
{
"code": null,
"e": 25489,
"s": 25462,
"text": "Features of call by value:"
},
{
"code": null,
"e": 25536,
"s": 25489,
"text": "Function arguments are always passed by value."
},
{
"code": null,
"e": 25612,
"s": 25536,
"text": "It copies the value of a variable passed in a function to a local variable."
},
{
"code": null,
"e": 25755,
"s": 25612,
"text": "Both these variables occupy separate locations in memory. Thus, if changes are made in a particular variable it does not affect the other one."
},
{
"code": null,
"e": 25764,
"s": 25755,
"text": "Example:"
},
{
"code": null,
"e": 25775,
"s": 25764,
"text": "JavaScript"
},
{
"code": "<script type=\"text/javascript\"> // By value (primitives) var a = 5; var b; b = a; a = 3; console.log(a); console.log(b);</script>",
"e": 25926,
"s": 25775,
"text": null
},
{
"code": null,
"e": 26063,
"s": 25926,
"text": "Output: “b” was just a copy of “a”. It has its own space in memory. When we change “a” it does not have any impact on the value of “b”. "
},
{
"code": null,
"e": 26072,
"s": 26063,
"text": "By value"
},
{
"code": null,
"e": 26479,
"s": 26072,
"text": "Call by reference: Let’s say, we have an object stored in the variable “a”. The variable stores the location or the address where the object lives. Now we set b=a. Now that new variable “b” instead of pointing to a new location in the memory, points to the same location where “a” does. No new object is created, no copy is created. Both the variables point to the same object. This is like having 2 names."
},
{
"code": null,
"e": 26585,
"s": 26479,
"text": "This is call by reference. It behaves quite differently from by value. All objects interact by reference."
},
{
"code": null,
"e": 26611,
"s": 26585,
"text": "Features of By reference:"
},
{
"code": null,
"e": 26661,
"s": 26611,
"text": "In JavaScript, all objects interact by reference."
},
{
"code": null,
"e": 26804,
"s": 26661,
"text": "If an object is stored in a variable and that variable is made equal to another variable then both of them occupy the same location in memory."
},
{
"code": null,
"e": 26869,
"s": 26804,
"text": "Changes in one object variable affect the other object variable."
},
{
"code": null,
"e": 27158,
"s": 26869,
"text": "Example: Over here, when we set d=c, “d” points to the same location in memory where “c” does. At first, we have a name-value pair stored in “c”. Now when we change a property using “c”, it changes the property in “d” also because both point to the same object. Changes in one it affects."
},
{
"code": null,
"e": 27169,
"s": 27158,
"text": "Javascript"
},
{
"code": "<script> // By reference (all objects (including functions)) var c = { greeting : 'Welcome' }; var d; d = c; // Mutating the value of c c.greeting = 'Welcome to geeksforgeeks'; console.log(c); console.log(d);</script>",
"e": 27415,
"s": 27169,
"text": null
},
{
"code": null,
"e": 27423,
"s": 27415,
"text": "Output:"
},
{
"code": null,
"e": 27436,
"s": 27423,
"text": "By reference"
},
{
"code": null,
"e": 27492,
"s": 27436,
"text": "Difference between call by value and call by reference:"
},
{
"code": null,
"e": 27506,
"s": 27492,
"text": "Call by value"
},
{
"code": null,
"e": 27524,
"s": 27506,
"text": "Call by reference"
},
{
"code": null,
"e": 27542,
"s": 27524,
"text": "javascript-basics"
},
{
"code": null,
"e": 27558,
"s": 27542,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27569,
"s": 27558,
"text": "JavaScript"
},
{
"code": null,
"e": 27586,
"s": 27569,
"text": "Web Technologies"
},
{
"code": null,
"e": 27684,
"s": 27586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27729,
"s": 27684,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27790,
"s": 27729,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27862,
"s": 27790,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27914,
"s": 27862,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27960,
"s": 27914,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28002,
"s": 27960,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28064,
"s": 28002,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28107,
"s": 28064,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28140,
"s": 28107,
"text": "Installation of Node.js on Linux"
}
] |
Machine Learning 101: Predicting Drug Use Using Logistic Regression In R | by Leihua Ye, PhD | Towards Data Science
|
Executive Summary
Generalized Linear Models (GLM)
Three types of link function: Logit, Probit, and Complementary log-log (cloglog)
Building a logistic regression to predict drug use and compare these three types of GLM
In Machine Learning 101 courses, stats professors introduce GLM right after linear regression as the next stepping stone of becoming data scientists. GLM comes with several forms, and the most well-known ones are logit, probit, and cloglog.
These GLMs are well suited for classification questions: to be or not to be, to vote or not to vote, and to click or not to click.
For the full project description and the complete R code, please check my Github.
Basics
Usually, GLM for binary data can be expressed in the following form:
where g represents a linear relation of the predictors (on the right) of the probability p, and g is a function which maps p ∈[0,1] to R.
There are three ways of linking the components on the left and right.
Logit:
In words, the log form of p.
Probit:
In words, the inverse of the cumulative density function of the normal distribution.
Cloglog:
In words, the log form of the negative value of the log form of the probability of not happening. Confused? At least, I’m. The link function for this one is straightforward.
OK, let’s move on and build GLM models to predict who is more vulnerable to drug use and learn to read plots.
Load, clean, and spliting the dataset
Load, clean, and spliting the dataset
library(readr)drug_use <- read_csv(‘drug.csv’,col_names=c(‘ID’,’Age’,’Gender’,’Education’,’Country’,’Ethnicity’,’Nscore’,’Escore’,’Oscore’,’Ascore’,’Cscore’,’Impulsive’,’SS’,’Alcohol’,’Amphet’,’Amyl’,’Benzos’,’Caff’,’Cannabis’,’Choc’,’Coke’,’Crack’,’Ecstasy’,’Heroin’,’Ketamine’,’Legalh’,’LSD’,’Meth’,’Mushrooms’,’Nicotine’,’Semer’,’VSA’))library(dplyr)drug_use <- drug_use %>% mutate_at(as.ordered, .vars=vars(Alcohol:VSA)) drug_use <- drug_use %>% mutate(Gender = factor(Gender, labels=c(“Male”, “Female”))) %>% mutate(Ethnicity = factor(Ethnicity, labels=c(“Black”, “Asian”, “White”, “Mixed:White/Black”, “Other”, “Mixed:White/Asian”, “Mixed:Black/Asian”))) %>% mutate(Country = factor(Country, labels=c(“Australia”, “Canada”, “New Zealand”, “Other”, “Ireland”, “UK”,”USA”)))#create a new factor variable called recent_cannabis_usedrug_use = drug_use %>% mutate(recent_cannabis_use=as.factor(ifelse(Cannabis>=”CL3",”Yes”,”No”)))#create a new tibble that includes a subset of the original variable #data split into training and test setsdrug_use_subset <- drug_use %>% select(Age:SS, recent_cannabis_use)set.seed(1)traint.indices = sample(1:nrow(drug_use_subset),1500)drug_use_train = drug_use_subset[traint.indices,]drug_use_test = drug_use_subset[-traint.indices,]dim(drug_use_train)dim(drug_use_test)[1] 1500 13[1] 385 13
So, the train set has a 1500*13 dimension, and the test set has a 385*13 dimension.
2. Fit a logistic regression
#use logit as the link functionglm_fit = glm(recent_cannabis_use ~ .,data=drug_use_train,family=binomial(link= “logit”))summary(glm_fit)Call:glm(formula = recent_cannabis_use ~ ., family = binomial(link = "logit"), data = drug_use_train)Deviance Residuals: Min 1Q Median 3Q Max -3.0024 -0.5996 0.1512 0.5410 2.7525 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 1.33629 0.64895 2.059 0.039480 * Age -0.77441 0.09123 -8.489 < 2e-16 ***GenderFemale -0.65308 0.15756 -4.145 3.40e-05 ***Education -0.41192 0.08006 -5.145 2.67e-07 ***CountryCanada -0.67373 1.23497 -0.546 0.585377 CountryNew Zealand -1.24256 0.31946 -3.890 0.000100 ***CountryOther 0.11062 0.49754 0.222 0.824056 CountryIreland -0.50841 0.69084 -0.736 0.461773 CountryUK -0.88941 0.39042 -2.278 0.022720 * CountryUSA -1.97561 0.20101 -9.828 < 2e-16 ***EthnicityAsian -1.19642 0.96794 -1.236 0.216443 EthnicityWhite 0.65189 0.63569 1.025 0.305130 EthnicityMixed:White/Black 0.10814 1.07403 0.101 0.919799 EthnicityOther 0.66571 0.79791 0.834 0.404105 EthnicityMixed:White/Asian 0.48986 0.96724 0.506 0.612535 EthnicityMixed:Black/Asian13.07740 466.45641 0.028 0.977634 Nscore -0.08318 0.09163 -0.908 0.363956 Escore -0.11130 0.09621 -1.157 0.247349 Oscore 0.64932 0.09259 7.013 2.33e-12 ***Ascore 0.09697 0.08235 1.178 0.238990 Cscore -0.30243 0.09179 -3.295 0.000984 ***Impulsive -0.14213 0.10381 -1.369 0.170958 SS 0.70960 0.11793 6.017 1.78e-09 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Interpretations of are straightforward, and significant variables
include: age, female, education, country variable (ZJ, UK, USA), oscore, score, and SS.
3. Probit and cloglog
#probit link functionglm_fit_probit = glm(recent_cannabis_use ~ .,data=drug_use_train,family = binomial(link = “probit”))prob_training_probit = predict(glm_fit_probit, type=”response”)#c-log-log” linkglm_fit_clog = glm(recent_cannabis_use ~ .,data=drug_use_train,family = binomial(link = “cloglog”))prob_training_clog = predict(glm_fit_clog, type=”response”)
4. Compare these three plots
# compare logit and probitplot(prob_training_logit,prob_training_probit,xlab = “Fitted Values of Logit Model”,ylab= “Fitted Values of Probit Model”, main= “Plot 1: Fitted Values for Logit and Probit Regressions”, pch=19, cex=0.2,abline(a=0,b=1,col=”red”))
As well known, probit and logit predict almost the same values as they aligh closely on the 45-degree line. Probably, the only difference lies in the middle range between 0.5 to 0.8 where the probit model predicts value slightly below the abline.
# compare logit and cloglogplot(prob_training_logit,prob_training_clog,xlab = “Fitted Values of Logit Model”,ylab= “Fitted Values of Cloglog Model”, main= “Plot 2: Fitted Values for Logit and Cloglog Regressions”, pch=19, cex=0.2,abline(a=0,b=1,col=”red”))
This is an interesting plot. C-loglog generates predictions higher value in the early stage, followed by lower dispersed predictions than the logit in the middle range.
In Machine Learning, logistic regression serves as the 101 technique that data scientists can apply.
Please find me on LinkedIn and Youtube.
Also, check my other posts on Artificial Intelligence and Machine Learning.
|
[
{
"code": null,
"e": 189,
"s": 171,
"text": "Executive Summary"
},
{
"code": null,
"e": 221,
"s": 189,
"text": "Generalized Linear Models (GLM)"
},
{
"code": null,
"e": 302,
"s": 221,
"text": "Three types of link function: Logit, Probit, and Complementary log-log (cloglog)"
},
{
"code": null,
"e": 390,
"s": 302,
"text": "Building a logistic regression to predict drug use and compare these three types of GLM"
},
{
"code": null,
"e": 631,
"s": 390,
"text": "In Machine Learning 101 courses, stats professors introduce GLM right after linear regression as the next stepping stone of becoming data scientists. GLM comes with several forms, and the most well-known ones are logit, probit, and cloglog."
},
{
"code": null,
"e": 762,
"s": 631,
"text": "These GLMs are well suited for classification questions: to be or not to be, to vote or not to vote, and to click or not to click."
},
{
"code": null,
"e": 844,
"s": 762,
"text": "For the full project description and the complete R code, please check my Github."
},
{
"code": null,
"e": 851,
"s": 844,
"text": "Basics"
},
{
"code": null,
"e": 920,
"s": 851,
"text": "Usually, GLM for binary data can be expressed in the following form:"
},
{
"code": null,
"e": 1058,
"s": 920,
"text": "where g represents a linear relation of the predictors (on the right) of the probability p, and g is a function which maps p ∈[0,1] to R."
},
{
"code": null,
"e": 1128,
"s": 1058,
"text": "There are three ways of linking the components on the left and right."
},
{
"code": null,
"e": 1135,
"s": 1128,
"text": "Logit:"
},
{
"code": null,
"e": 1164,
"s": 1135,
"text": "In words, the log form of p."
},
{
"code": null,
"e": 1172,
"s": 1164,
"text": "Probit:"
},
{
"code": null,
"e": 1257,
"s": 1172,
"text": "In words, the inverse of the cumulative density function of the normal distribution."
},
{
"code": null,
"e": 1266,
"s": 1257,
"text": "Cloglog:"
},
{
"code": null,
"e": 1440,
"s": 1266,
"text": "In words, the log form of the negative value of the log form of the probability of not happening. Confused? At least, I’m. The link function for this one is straightforward."
},
{
"code": null,
"e": 1550,
"s": 1440,
"text": "OK, let’s move on and build GLM models to predict who is more vulnerable to drug use and learn to read plots."
},
{
"code": null,
"e": 1588,
"s": 1550,
"text": "Load, clean, and spliting the dataset"
},
{
"code": null,
"e": 1626,
"s": 1588,
"text": "Load, clean, and spliting the dataset"
},
{
"code": null,
"e": 2957,
"s": 1626,
"text": "library(readr)drug_use <- read_csv(‘drug.csv’,col_names=c(‘ID’,’Age’,’Gender’,’Education’,’Country’,’Ethnicity’,’Nscore’,’Escore’,’Oscore’,’Ascore’,’Cscore’,’Impulsive’,’SS’,’Alcohol’,’Amphet’,’Amyl’,’Benzos’,’Caff’,’Cannabis’,’Choc’,’Coke’,’Crack’,’Ecstasy’,’Heroin’,’Ketamine’,’Legalh’,’LSD’,’Meth’,’Mushrooms’,’Nicotine’,’Semer’,’VSA’))library(dplyr)drug_use <- drug_use %>% mutate_at(as.ordered, .vars=vars(Alcohol:VSA)) drug_use <- drug_use %>% mutate(Gender = factor(Gender, labels=c(“Male”, “Female”))) %>% mutate(Ethnicity = factor(Ethnicity, labels=c(“Black”, “Asian”, “White”, “Mixed:White/Black”, “Other”, “Mixed:White/Asian”, “Mixed:Black/Asian”))) %>% mutate(Country = factor(Country, labels=c(“Australia”, “Canada”, “New Zealand”, “Other”, “Ireland”, “UK”,”USA”)))#create a new factor variable called recent_cannabis_usedrug_use = drug_use %>% mutate(recent_cannabis_use=as.factor(ifelse(Cannabis>=”CL3\",”Yes”,”No”)))#create a new tibble that includes a subset of the original variable #data split into training and test setsdrug_use_subset <- drug_use %>% select(Age:SS, recent_cannabis_use)set.seed(1)traint.indices = sample(1:nrow(drug_use_subset),1500)drug_use_train = drug_use_subset[traint.indices,]drug_use_test = drug_use_subset[-traint.indices,]dim(drug_use_train)dim(drug_use_test)[1] 1500 13[1] 385 13"
},
{
"code": null,
"e": 3041,
"s": 2957,
"text": "So, the train set has a 1500*13 dimension, and the test set has a 385*13 dimension."
},
{
"code": null,
"e": 3070,
"s": 3041,
"text": "2. Fit a logistic regression"
},
{
"code": null,
"e": 5085,
"s": 3070,
"text": "#use logit as the link functionglm_fit = glm(recent_cannabis_use ~ .,data=drug_use_train,family=binomial(link= “logit”))summary(glm_fit)Call:glm(formula = recent_cannabis_use ~ ., family = binomial(link = \"logit\"), data = drug_use_train)Deviance Residuals: Min 1Q Median 3Q Max -3.0024 -0.5996 0.1512 0.5410 2.7525 Coefficients: Estimate Std. Error z value Pr(>|z|) (Intercept) 1.33629 0.64895 2.059 0.039480 * Age -0.77441 0.09123 -8.489 < 2e-16 ***GenderFemale -0.65308 0.15756 -4.145 3.40e-05 ***Education -0.41192 0.08006 -5.145 2.67e-07 ***CountryCanada -0.67373 1.23497 -0.546 0.585377 CountryNew Zealand -1.24256 0.31946 -3.890 0.000100 ***CountryOther 0.11062 0.49754 0.222 0.824056 CountryIreland -0.50841 0.69084 -0.736 0.461773 CountryUK -0.88941 0.39042 -2.278 0.022720 * CountryUSA -1.97561 0.20101 -9.828 < 2e-16 ***EthnicityAsian -1.19642 0.96794 -1.236 0.216443 EthnicityWhite 0.65189 0.63569 1.025 0.305130 EthnicityMixed:White/Black 0.10814 1.07403 0.101 0.919799 EthnicityOther 0.66571 0.79791 0.834 0.404105 EthnicityMixed:White/Asian 0.48986 0.96724 0.506 0.612535 EthnicityMixed:Black/Asian13.07740 466.45641 0.028 0.977634 Nscore -0.08318 0.09163 -0.908 0.363956 Escore -0.11130 0.09621 -1.157 0.247349 Oscore 0.64932 0.09259 7.013 2.33e-12 ***Ascore 0.09697 0.08235 1.178 0.238990 Cscore -0.30243 0.09179 -3.295 0.000984 ***Impulsive -0.14213 0.10381 -1.369 0.170958 SS 0.70960 0.11793 6.017 1.78e-09 ***---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1"
},
{
"code": null,
"e": 5151,
"s": 5085,
"text": "Interpretations of are straightforward, and significant variables"
},
{
"code": null,
"e": 5239,
"s": 5151,
"text": "include: age, female, education, country variable (ZJ, UK, USA), oscore, score, and SS."
},
{
"code": null,
"e": 5261,
"s": 5239,
"text": "3. Probit and cloglog"
},
{
"code": null,
"e": 5620,
"s": 5261,
"text": "#probit link functionglm_fit_probit = glm(recent_cannabis_use ~ .,data=drug_use_train,family = binomial(link = “probit”))prob_training_probit = predict(glm_fit_probit, type=”response”)#c-log-log” linkglm_fit_clog = glm(recent_cannabis_use ~ .,data=drug_use_train,family = binomial(link = “cloglog”))prob_training_clog = predict(glm_fit_clog, type=”response”)"
},
{
"code": null,
"e": 5649,
"s": 5620,
"text": "4. Compare these three plots"
},
{
"code": null,
"e": 5905,
"s": 5649,
"text": "# compare logit and probitplot(prob_training_logit,prob_training_probit,xlab = “Fitted Values of Logit Model”,ylab= “Fitted Values of Probit Model”, main= “Plot 1: Fitted Values for Logit and Probit Regressions”, pch=19, cex=0.2,abline(a=0,b=1,col=”red”))"
},
{
"code": null,
"e": 6152,
"s": 5905,
"text": "As well known, probit and logit predict almost the same values as they aligh closely on the 45-degree line. Probably, the only difference lies in the middle range between 0.5 to 0.8 where the probit model predicts value slightly below the abline."
},
{
"code": null,
"e": 6409,
"s": 6152,
"text": "# compare logit and cloglogplot(prob_training_logit,prob_training_clog,xlab = “Fitted Values of Logit Model”,ylab= “Fitted Values of Cloglog Model”, main= “Plot 2: Fitted Values for Logit and Cloglog Regressions”, pch=19, cex=0.2,abline(a=0,b=1,col=”red”))"
},
{
"code": null,
"e": 6578,
"s": 6409,
"text": "This is an interesting plot. C-loglog generates predictions higher value in the early stage, followed by lower dispersed predictions than the logit in the middle range."
},
{
"code": null,
"e": 6679,
"s": 6578,
"text": "In Machine Learning, logistic regression serves as the 101 technique that data scientists can apply."
},
{
"code": null,
"e": 6719,
"s": 6679,
"text": "Please find me on LinkedIn and Youtube."
}
] |
Classification Basics: Walk-through with the Iris Data Set | Towards Data Science
|
When I was first learning how to code, I would practice my data skills on different data sets to create mini Jupyter Notebook reference guides. Since I have found this to be an incredibly useful tool, I thought I’d start sharing code walk-throughs. Hopefully this is a positive resource for those learning to use Python for data science, and something that can be referenced in future projects. Full code is available on Github.
The first step is to import the preloaded data sets from the scikit-learn python library. More info on the “toy” data sets included in the package can be found here. The data description will also give more information on the features, statistics, and sources.
from sklearn.datasets import load_iris#save data information as variableiris = load_iris()#view data description and informationprint(iris.DESCR)
The data will be pre-saved as a dictionary with the keys “data” and “target”, each paired with an array of lists as the values. Initially the information will be output like this:
{'data': array([[5.1, 3.5, 1.4, 0.2], [4.9, 3. , 1.4, 0.2], [4.7, 3.2, 1.3, 0.2], [4.6, 3.1, 1.5, 0.2], [5. , 3.6, 1.4, 0.2], [5.4, 3.9, 1.7, 0.4], [4.6, 3.4, 1.4, 0.3] ...'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ...}
To view the data more easily we can put this information into a data frame by using the Pandas library. Let’s create a data frame to store the data information about the flowers’ features first.
import pandas as pd#make sure to save the data frame to a variabledata = pd.DataFrame(iris.data)data.head()
Using data.head() will automatically output the first 5 rows of data, but if we can also specify how many rows we want in the brackets, data.head(10).
Now, we have a data frame with the iris data, but the columns are not clearly labeled. Looking at the data description we printed above, or referencing the source code tells us more about the features. In the documentation the data features are listed as:
sepal length in cm
sepal width in cm
petal length in cm
petal width in cm
Let’s rename the columns so the features are clear.
data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']#note: it is common practice to use underscores between words, and avoid spacesdata.head()
Now that the data related to the features is neatly in a data frame, we can do the same with the target data.
#put target data into data frametarget = pd.DataFrame(iris.target)#Lets rename the column so that we know that these values refer to the target valuestarget = target.rename(columns = {0: 'target'})target.head()
The target data frame is only one column, and it gives a list of the values 0, 1, and 2. We will use the information from the feature data to predict if a flower belongs in group 0, 1, or 2. But what do these numbers refer to?
0 is Iris Setosa
1 is Iris Versicolour
2 is Iris Virginica
To help us understand our data better, let’s first combine the two data frames we just created. By doing this we can see the features and class determination of the flowers together.
df = pd.concat([data, target], axis = 1)#note: it is common practice to name your data frame as "df", but you can name it anything as long as you are clear and consistent#in the code above, axis = 1 tells the data frame to add the target data frame as another column of the data data frame, axis = 0 would add the values as another row on the bottomdf.head()
It’s super important to look through your data, make sure it is clean, and begin to explore relationships between features and target variables. Since this is a relatively simple data set there is not much cleaning that needs to be done, but let’s walk through the steps.
Look at Data Types
Look at Data Types
df.dtypes
float = numbers with decimals (1.678)int = integer or whole number without decimals (1, 2, 3)obj = object, string, or words (‘hello’)The 64 after these data types refers to how many bits of storage the value occupies. You will often seen 32 or 64.
In this data set, the data types are all ready for modeling. In some instances the number values will be coded as objects, so we would have to change the data types before performing statistic modeling.
2. Check for Missing Values
df.isnull().sum()
This data set is not missing any values. While this makes modeling much easier, this is not usually the case — data is always messy in real life. If there were missing values you could delete rows of data that had missing values, or there are several options of how you could fill that missing number (with the column’s mean, previous value...).
3. Statistical Overview
df.describe()
This allows us to get a quick overview of the data. We can check for outliers by looking at the min and max values of each column in relation to the mean. Spend a bit of time looking through this chart to begin understanding the spread of the data.
The next step in the EDA process is to start visualizing some relationships.
The Seaborn library has a great heat map visual for mapping the correlations between features. The higher the number is, the greater the correlation between the two elements. A high positive correlation indicates that the two elements have a positive linear relationship (as one increases the other also increases), and a low negative correlation indicates a negative linear relationship (as one increases the other decreases).
import seaborn as snssns.heatmap(df.corr(), annot = True);#annot = True adds the numbers onto the squares
Petal length and width is most correlated with the target, meaning that as these numbers increase, so does the target value. In this case, it means that flowers in class 2 often have longer petal length and width than flowers in class 0. Sepal width is most anti-correlated, indicating that flowers in class 0 have the greatest sepal width than those in class 2. We can also see some intercorrelation between features, for example petal width and length are also highly correlated. This information is not necessarily the best way to analyze the data, but it allows us to start seeing these relationships.
To start looking at the relationships between features, we can create scatter plots to further visualize the way the different classes of flowers relate to sepal and petal data.
# The indices of the features that we are plotting (class 0 & 1)x_index = 0y_index = 1# this formatter will label the colorbar with the correct target namesformatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])plt.figure(figsize=(5, 4))plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)plt.colorbar(ticks=[0, 1, 2], format=formatter)plt.xlabel(iris.feature_names[x_index])plt.ylabel(iris.feature_names[y_index])plt.tight_layout()plt.show()
Now let’s create the same scatter plot to compare the petal data points.
x_index = 2y_index = 3# this formatter will label the colorbar with the correct target namesformatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])plt.figure(figsize=(5, 4))plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)plt.colorbar(ticks=[0, 1, 2], format=formatter)plt.xlabel(iris.feature_names[x_index])plt.ylabel(iris.feature_names[y_index])plt.tight_layout()plt.show()
Now that we have cleaned and explored the data, we can begin to develop a model. Our goal is to create a Logistic Regression classification model that will predict which class the flower is based on petal and sepal sizes.
#divide our data into predictors (X) and target values (y)X = df.copy()y = X.pop('target')
Once we separate the features from the target, we can create a train and test class. As the names suggest, we will train our model on the train set, and test the model on the test set. We will randomly select 80% of the data to be in our training, and 20% as test.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1, stratify = y)'''by stratifying on y we assure that the different classes are represented proportionally to the amount in the total data (this makes sure that all of class 1 is not in the test group only)'''
With the X values split between training and test, now we can standardize the values. This puts the numbers on a consistent scale while keeping the proportional relationship between them.
from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train = pd.DataFrame(scaler.fit_transform(X_train), columns=X_train.columns)X_test = pd.DataFrame(scaler.transform(X_test), columns=X_test.columns)
The baseline is the probability of predicting class before the model is implemented. If the data is split into 2 classes evenly, there is already a 50% chance of randomly assigning an element to the correct class. The goal of our model is to improve on this baseline, or random prediction. Also, if there is a strong class imbalance (if 90% of the data was in class 1), then we could alter the proportion of each class to help the model predict more accurately.
df.target.value_counts(normalize= True)
from sklearn.linear_model import LogisticRegression#create the model instancemodel = LogisticRegression()#fit the model on the training datamodel.fit(X_train, y_train)#the score, or accuracy of the modelmodel.score(X_test, y_test)# Output = 0.9666666666666667#the test score is already very high, but we can use the cross validated score to ensure the model's strength from sklearn.model_selection import cross_val_scorescores = cross_val_score(model, X_train, y_train, cv=10)print(np.mean(scores))# Output = 0.9499999999999998
Without any adjustments or tuning, this model is already performing very well with a test score of .9667 and a cross validation score of .9499. This means that the model is predicting the correct class for the flower about 95% of time. Much higher than the baseline of 33%!
Normally there will be lots of fine tuning and experimentation with parameters to find the model that performs with the highest scores. However, since this data set was straightforward, we can move on for now and start looking at how the model made its predictions.
df_coef = pd.DataFrame(model.coef_, columns=X_train.columns)df_coef
Coefficients are often a bit hard to interpret in Logistic Regression, but we can get an idea of how much of an impact each of the features had in deciding if a flower belonged to that class. For instance, petal length was barely a deciding factor for if a flower was in class 1, but petal width was a strong predictor for class 2.
We can also compare the values that our model predicted with the actual values.
predictions = model.predict(X_test)#compare predicted values with the actual scorescompare_df = pd.DataFrame({'actual': y_test, 'predicted': predictions})compare_df = compare_df.reset_index(drop = True)compare_df
To look more closely at the predictions that the model made, we can use the confusion matrix. In the confusion matrix, the predicted values are the columns and the actual are the rows. It allows us to see where the model makes true and false predictions, and if it predicts incorrectly, we can see which class it is predicting falsely.
from sklearn.metrics import confusion_matrixpd.DataFrame(confusion_matrix(y_test, predictions, labels=[2, 1, 0]),index=[2, 1, 0], columns=[2, 1, 0])
Another good way to check how your model is performing is by looking at the classification report. It shows the precision, recall, f1 scores, and accuracy scores, and below is a very brief explanation of these features.
Precision: Number of correctly predicted Iris Virginica flowers (10) out of total number of predicted Iris Virginica flowers (10). Precision in predicting Iris Virginica =10/10 = 1.0
Recall: Number of correctly predicted Iris Virginica out of the number of actual Iris Virginica. Recall = 9/10 = .9
F1 Score: This is a harmonic mean of precision and recall. The formula is F1 Score = 2* (precision * recall) / (precision + recall)
Accuracy: Add all the correct predictions together for all classes and divide by the total number of predictions. 29 correct predictions /30 total values = accuracy of .9667.
from sklearn.metrics import classification_reportprint(classification_report(y_test, predictions))
Using the code below we can look at the probabilities of each row of data being assigned to one of the three classes. By default, the model will assign the item to the class with the highest probability. If we wanted to adjust the accuracy or precision, we could do this by changing the threshold of how high the predicted probability would have to be before it was assigned to that class.
In this case, there is not a consequence to incorrectly assigning a flower to another class, but models used to detect cancer cells adjust their models to ‘assume the worst’ and assign it as a true cancer cell more often. This is used in many cases when it is better to be over cautious than mislabel the cell as safe and healthy.
probs = model.predict_proba(X_test)#put the probabilities into a dataframe for easier viewingY_pp = pd.DataFrame(model.predict_proba(X_test), columns=['class_0_pp', 'class_1_pp', 'class_2_pp'])Y_pp.head()
Hopefully this walk-through helped to show some major steps in the process of a data science project. Of course this is not an exhaustive list of steps that could be taken with this data set, but it aims to carefully show some of the important steps of classification.
This is a classic data set because it is relatively straightforward, but the steps highlighted here can be applied to a classification project of any kind. Follow for more simple (and advanced) data set walk-throughs in the future!
Looking for the next step? Read about the basics of regression with a data science project predicting car sale prices.
|
[
{
"code": null,
"e": 601,
"s": 172,
"text": "When I was first learning how to code, I would practice my data skills on different data sets to create mini Jupyter Notebook reference guides. Since I have found this to be an incredibly useful tool, I thought I’d start sharing code walk-throughs. Hopefully this is a positive resource for those learning to use Python for data science, and something that can be referenced in future projects. Full code is available on Github."
},
{
"code": null,
"e": 862,
"s": 601,
"text": "The first step is to import the preloaded data sets from the scikit-learn python library. More info on the “toy” data sets included in the package can be found here. The data description will also give more information on the features, statistics, and sources."
},
{
"code": null,
"e": 1008,
"s": 862,
"text": "from sklearn.datasets import load_iris#save data information as variableiris = load_iris()#view data description and informationprint(iris.DESCR)"
},
{
"code": null,
"e": 1188,
"s": 1008,
"text": "The data will be pre-saved as a dictionary with the keys “data” and “target”, each paired with an array of lists as the values. Initially the information will be output like this:"
},
{
"code": null,
"e": 1459,
"s": 1188,
"text": "{'data': array([[5.1, 3.5, 1.4, 0.2], [4.9, 3. , 1.4, 0.2], [4.7, 3.2, 1.3, 0.2], [4.6, 3.1, 1.5, 0.2], [5. , 3.6, 1.4, 0.2], [5.4, 3.9, 1.7, 0.4], [4.6, 3.4, 1.4, 0.3] ...'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ...}"
},
{
"code": null,
"e": 1654,
"s": 1459,
"text": "To view the data more easily we can put this information into a data frame by using the Pandas library. Let’s create a data frame to store the data information about the flowers’ features first."
},
{
"code": null,
"e": 1762,
"s": 1654,
"text": "import pandas as pd#make sure to save the data frame to a variabledata = pd.DataFrame(iris.data)data.head()"
},
{
"code": null,
"e": 1913,
"s": 1762,
"text": "Using data.head() will automatically output the first 5 rows of data, but if we can also specify how many rows we want in the brackets, data.head(10)."
},
{
"code": null,
"e": 2169,
"s": 1913,
"text": "Now, we have a data frame with the iris data, but the columns are not clearly labeled. Looking at the data description we printed above, or referencing the source code tells us more about the features. In the documentation the data features are listed as:"
},
{
"code": null,
"e": 2188,
"s": 2169,
"text": "sepal length in cm"
},
{
"code": null,
"e": 2206,
"s": 2188,
"text": "sepal width in cm"
},
{
"code": null,
"e": 2225,
"s": 2206,
"text": "petal length in cm"
},
{
"code": null,
"e": 2243,
"s": 2225,
"text": "petal width in cm"
},
{
"code": null,
"e": 2295,
"s": 2243,
"text": "Let’s rename the columns so the features are clear."
},
{
"code": null,
"e": 2463,
"s": 2295,
"text": "data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']#note: it is common practice to use underscores between words, and avoid spacesdata.head()"
},
{
"code": null,
"e": 2573,
"s": 2463,
"text": "Now that the data related to the features is neatly in a data frame, we can do the same with the target data."
},
{
"code": null,
"e": 2784,
"s": 2573,
"text": "#put target data into data frametarget = pd.DataFrame(iris.target)#Lets rename the column so that we know that these values refer to the target valuestarget = target.rename(columns = {0: 'target'})target.head()"
},
{
"code": null,
"e": 3011,
"s": 2784,
"text": "The target data frame is only one column, and it gives a list of the values 0, 1, and 2. We will use the information from the feature data to predict if a flower belongs in group 0, 1, or 2. But what do these numbers refer to?"
},
{
"code": null,
"e": 3028,
"s": 3011,
"text": "0 is Iris Setosa"
},
{
"code": null,
"e": 3050,
"s": 3028,
"text": "1 is Iris Versicolour"
},
{
"code": null,
"e": 3070,
"s": 3050,
"text": "2 is Iris Virginica"
},
{
"code": null,
"e": 3253,
"s": 3070,
"text": "To help us understand our data better, let’s first combine the two data frames we just created. By doing this we can see the features and class determination of the flowers together."
},
{
"code": null,
"e": 3612,
"s": 3253,
"text": "df = pd.concat([data, target], axis = 1)#note: it is common practice to name your data frame as \"df\", but you can name it anything as long as you are clear and consistent#in the code above, axis = 1 tells the data frame to add the target data frame as another column of the data data frame, axis = 0 would add the values as another row on the bottomdf.head()"
},
{
"code": null,
"e": 3884,
"s": 3612,
"text": "It’s super important to look through your data, make sure it is clean, and begin to explore relationships between features and target variables. Since this is a relatively simple data set there is not much cleaning that needs to be done, but let’s walk through the steps."
},
{
"code": null,
"e": 3903,
"s": 3884,
"text": "Look at Data Types"
},
{
"code": null,
"e": 3922,
"s": 3903,
"text": "Look at Data Types"
},
{
"code": null,
"e": 3932,
"s": 3922,
"text": "df.dtypes"
},
{
"code": null,
"e": 4180,
"s": 3932,
"text": "float = numbers with decimals (1.678)int = integer or whole number without decimals (1, 2, 3)obj = object, string, or words (‘hello’)The 64 after these data types refers to how many bits of storage the value occupies. You will often seen 32 or 64."
},
{
"code": null,
"e": 4383,
"s": 4180,
"text": "In this data set, the data types are all ready for modeling. In some instances the number values will be coded as objects, so we would have to change the data types before performing statistic modeling."
},
{
"code": null,
"e": 4411,
"s": 4383,
"text": "2. Check for Missing Values"
},
{
"code": null,
"e": 4429,
"s": 4411,
"text": "df.isnull().sum()"
},
{
"code": null,
"e": 4775,
"s": 4429,
"text": "This data set is not missing any values. While this makes modeling much easier, this is not usually the case — data is always messy in real life. If there were missing values you could delete rows of data that had missing values, or there are several options of how you could fill that missing number (with the column’s mean, previous value...)."
},
{
"code": null,
"e": 4799,
"s": 4775,
"text": "3. Statistical Overview"
},
{
"code": null,
"e": 4813,
"s": 4799,
"text": "df.describe()"
},
{
"code": null,
"e": 5062,
"s": 4813,
"text": "This allows us to get a quick overview of the data. We can check for outliers by looking at the min and max values of each column in relation to the mean. Spend a bit of time looking through this chart to begin understanding the spread of the data."
},
{
"code": null,
"e": 5139,
"s": 5062,
"text": "The next step in the EDA process is to start visualizing some relationships."
},
{
"code": null,
"e": 5567,
"s": 5139,
"text": "The Seaborn library has a great heat map visual for mapping the correlations between features. The higher the number is, the greater the correlation between the two elements. A high positive correlation indicates that the two elements have a positive linear relationship (as one increases the other also increases), and a low negative correlation indicates a negative linear relationship (as one increases the other decreases)."
},
{
"code": null,
"e": 5673,
"s": 5567,
"text": "import seaborn as snssns.heatmap(df.corr(), annot = True);#annot = True adds the numbers onto the squares"
},
{
"code": null,
"e": 6279,
"s": 5673,
"text": "Petal length and width is most correlated with the target, meaning that as these numbers increase, so does the target value. In this case, it means that flowers in class 2 often have longer petal length and width than flowers in class 0. Sepal width is most anti-correlated, indicating that flowers in class 0 have the greatest sepal width than those in class 2. We can also see some intercorrelation between features, for example petal width and length are also highly correlated. This information is not necessarily the best way to analyze the data, but it allows us to start seeing these relationships."
},
{
"code": null,
"e": 6457,
"s": 6279,
"text": "To start looking at the relationships between features, we can create scatter plots to further visualize the way the different classes of flowers relate to sepal and petal data."
},
{
"code": null,
"e": 6938,
"s": 6457,
"text": "# The indices of the features that we are plotting (class 0 & 1)x_index = 0y_index = 1# this formatter will label the colorbar with the correct target namesformatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])plt.figure(figsize=(5, 4))plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)plt.colorbar(ticks=[0, 1, 2], format=formatter)plt.xlabel(iris.feature_names[x_index])plt.ylabel(iris.feature_names[y_index])plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 7011,
"s": 6938,
"text": "Now let’s create the same scatter plot to compare the petal data points."
},
{
"code": null,
"e": 7428,
"s": 7011,
"text": "x_index = 2y_index = 3# this formatter will label the colorbar with the correct target namesformatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])plt.figure(figsize=(5, 4))plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target)plt.colorbar(ticks=[0, 1, 2], format=formatter)plt.xlabel(iris.feature_names[x_index])plt.ylabel(iris.feature_names[y_index])plt.tight_layout()plt.show()"
},
{
"code": null,
"e": 7650,
"s": 7428,
"text": "Now that we have cleaned and explored the data, we can begin to develop a model. Our goal is to create a Logistic Regression classification model that will predict which class the flower is based on petal and sepal sizes."
},
{
"code": null,
"e": 7741,
"s": 7650,
"text": "#divide our data into predictors (X) and target values (y)X = df.copy()y = X.pop('target')"
},
{
"code": null,
"e": 8006,
"s": 7741,
"text": "Once we separate the features from the target, we can create a train and test class. As the names suggest, we will train our model on the train set, and test the model on the test set. We will randomly select 80% of the data to be in our training, and 20% as test."
},
{
"code": null,
"e": 8358,
"s": 8006,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=1, stratify = y)'''by stratifying on y we assure that the different classes are represented proportionally to the amount in the total data (this makes sure that all of class 1 is not in the test group only)'''"
},
{
"code": null,
"e": 8546,
"s": 8358,
"text": "With the X values split between training and test, now we can standardize the values. This puts the numbers on a consistent scale while keeping the proportional relationship between them."
},
{
"code": null,
"e": 8769,
"s": 8546,
"text": "from sklearn.preprocessing import StandardScalerscaler = StandardScaler()X_train = pd.DataFrame(scaler.fit_transform(X_train), columns=X_train.columns)X_test = pd.DataFrame(scaler.transform(X_test), columns=X_test.columns)"
},
{
"code": null,
"e": 9231,
"s": 8769,
"text": "The baseline is the probability of predicting class before the model is implemented. If the data is split into 2 classes evenly, there is already a 50% chance of randomly assigning an element to the correct class. The goal of our model is to improve on this baseline, or random prediction. Also, if there is a strong class imbalance (if 90% of the data was in class 1), then we could alter the proportion of each class to help the model predict more accurately."
},
{
"code": null,
"e": 9271,
"s": 9231,
"text": "df.target.value_counts(normalize= True)"
},
{
"code": null,
"e": 9799,
"s": 9271,
"text": "from sklearn.linear_model import LogisticRegression#create the model instancemodel = LogisticRegression()#fit the model on the training datamodel.fit(X_train, y_train)#the score, or accuracy of the modelmodel.score(X_test, y_test)# Output = 0.9666666666666667#the test score is already very high, but we can use the cross validated score to ensure the model's strength from sklearn.model_selection import cross_val_scorescores = cross_val_score(model, X_train, y_train, cv=10)print(np.mean(scores))# Output = 0.9499999999999998"
},
{
"code": null,
"e": 10073,
"s": 9799,
"text": "Without any adjustments or tuning, this model is already performing very well with a test score of .9667 and a cross validation score of .9499. This means that the model is predicting the correct class for the flower about 95% of time. Much higher than the baseline of 33%!"
},
{
"code": null,
"e": 10339,
"s": 10073,
"text": "Normally there will be lots of fine tuning and experimentation with parameters to find the model that performs with the highest scores. However, since this data set was straightforward, we can move on for now and start looking at how the model made its predictions."
},
{
"code": null,
"e": 10407,
"s": 10339,
"text": "df_coef = pd.DataFrame(model.coef_, columns=X_train.columns)df_coef"
},
{
"code": null,
"e": 10739,
"s": 10407,
"text": "Coefficients are often a bit hard to interpret in Logistic Regression, but we can get an idea of how much of an impact each of the features had in deciding if a flower belonged to that class. For instance, petal length was barely a deciding factor for if a flower was in class 1, but petal width was a strong predictor for class 2."
},
{
"code": null,
"e": 10819,
"s": 10739,
"text": "We can also compare the values that our model predicted with the actual values."
},
{
"code": null,
"e": 11032,
"s": 10819,
"text": "predictions = model.predict(X_test)#compare predicted values with the actual scorescompare_df = pd.DataFrame({'actual': y_test, 'predicted': predictions})compare_df = compare_df.reset_index(drop = True)compare_df"
},
{
"code": null,
"e": 11368,
"s": 11032,
"text": "To look more closely at the predictions that the model made, we can use the confusion matrix. In the confusion matrix, the predicted values are the columns and the actual are the rows. It allows us to see where the model makes true and false predictions, and if it predicts incorrectly, we can see which class it is predicting falsely."
},
{
"code": null,
"e": 11517,
"s": 11368,
"text": "from sklearn.metrics import confusion_matrixpd.DataFrame(confusion_matrix(y_test, predictions, labels=[2, 1, 0]),index=[2, 1, 0], columns=[2, 1, 0])"
},
{
"code": null,
"e": 11737,
"s": 11517,
"text": "Another good way to check how your model is performing is by looking at the classification report. It shows the precision, recall, f1 scores, and accuracy scores, and below is a very brief explanation of these features."
},
{
"code": null,
"e": 11920,
"s": 11737,
"text": "Precision: Number of correctly predicted Iris Virginica flowers (10) out of total number of predicted Iris Virginica flowers (10). Precision in predicting Iris Virginica =10/10 = 1.0"
},
{
"code": null,
"e": 12036,
"s": 11920,
"text": "Recall: Number of correctly predicted Iris Virginica out of the number of actual Iris Virginica. Recall = 9/10 = .9"
},
{
"code": null,
"e": 12168,
"s": 12036,
"text": "F1 Score: This is a harmonic mean of precision and recall. The formula is F1 Score = 2* (precision * recall) / (precision + recall)"
},
{
"code": null,
"e": 12343,
"s": 12168,
"text": "Accuracy: Add all the correct predictions together for all classes and divide by the total number of predictions. 29 correct predictions /30 total values = accuracy of .9667."
},
{
"code": null,
"e": 12442,
"s": 12343,
"text": "from sklearn.metrics import classification_reportprint(classification_report(y_test, predictions))"
},
{
"code": null,
"e": 12832,
"s": 12442,
"text": "Using the code below we can look at the probabilities of each row of data being assigned to one of the three classes. By default, the model will assign the item to the class with the highest probability. If we wanted to adjust the accuracy or precision, we could do this by changing the threshold of how high the predicted probability would have to be before it was assigned to that class."
},
{
"code": null,
"e": 13163,
"s": 12832,
"text": "In this case, there is not a consequence to incorrectly assigning a flower to another class, but models used to detect cancer cells adjust their models to ‘assume the worst’ and assign it as a true cancer cell more often. This is used in many cases when it is better to be over cautious than mislabel the cell as safe and healthy."
},
{
"code": null,
"e": 13381,
"s": 13163,
"text": "probs = model.predict_proba(X_test)#put the probabilities into a dataframe for easier viewingY_pp = pd.DataFrame(model.predict_proba(X_test), columns=['class_0_pp', 'class_1_pp', 'class_2_pp'])Y_pp.head()"
},
{
"code": null,
"e": 13650,
"s": 13381,
"text": "Hopefully this walk-through helped to show some major steps in the process of a data science project. Of course this is not an exhaustive list of steps that could be taken with this data set, but it aims to carefully show some of the important steps of classification."
},
{
"code": null,
"e": 13882,
"s": 13650,
"text": "This is a classic data set because it is relatively straightforward, but the steps highlighted here can be applied to a classification project of any kind. Follow for more simple (and advanced) data set walk-throughs in the future!"
}
] |
Binding mouse double click in Tkinter
|
Let us suppose that for a particular application, we want to bind the mouse double-click so that it performs some event or operation. We can use the bind(‘<Double-Button-1>’, handler) or bind(‘<Double-Button-2>’, handler) methods to bind the mouse Left or Right Buttons with a handler or a callback function.
In this example, we will create an application that contains a button. When we double click the button, it will open a popup window.
#Import required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define a function
def handler(e):
top= Toplevel(win)
top.geometry("600x200")
Label(top, text= "Hey There!", font= ('Helvetica 15 bold')).pack(pady=30)
#Define a Label in Main window
Label(win, text= "Double Click to Open the Popup",font=('Helvetica 15 underline')).pack(pady=30)
#Create a Button
ttk.Button(win, text= "Click", command=lambda:handler).pack(pady=20)
#Bind the Double Click with the Handler
win.bind('<Double-Button-1>', handler)
win.mainloop()
Now, run the above code to display the window.
Double-click the button "Click" to open a popup window.
|
[
{
"code": null,
"e": 1371,
"s": 1062,
"text": "Let us suppose that for a particular application, we want to bind the mouse double-click so that it performs some event or operation. We can use the bind(‘<Double-Button-1>’, handler) or bind(‘<Double-Button-2>’, handler) methods to bind the mouse Left or Right Buttons with a handler or a callback function."
},
{
"code": null,
"e": 1504,
"s": 1371,
"text": "In this example, we will create an application that contains a button. When we double click the button, it will open a popup window."
},
{
"code": null,
"e": 2155,
"s": 1504,
"text": "#Import required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter frame\nwin= Tk()\n#Define the geometry of the window\nwin.geometry(\"750x250\")\n#Define a function\ndef handler(e):\n top= Toplevel(win)\n top.geometry(\"600x200\")\n Label(top, text= \"Hey There!\", font= ('Helvetica 15 bold')).pack(pady=30)\n\n#Define a Label in Main window\nLabel(win, text= \"Double Click to Open the Popup\",font=('Helvetica 15 underline')).pack(pady=30)\n\n#Create a Button\nttk.Button(win, text= \"Click\", command=lambda:handler).pack(pady=20)\n\n#Bind the Double Click with the Handler\nwin.bind('<Double-Button-1>', handler)\nwin.mainloop()"
},
{
"code": null,
"e": 2202,
"s": 2155,
"text": "Now, run the above code to display the window."
},
{
"code": null,
"e": 2258,
"s": 2202,
"text": "Double-click the button \"Click\" to open a popup window."
}
] |
T-SQL - Quick Guide
|
In 1970's the product called 'SEQUEL', structured English query language, developed by IBM and later SEQUEL was renamed to 'SQL' which stands for Structured Query Language.
In 1986, SQL was approved by ANSI (American national Standards Institute) and in 1987, it was approved by ISO (International Standards Organization).
SQL is a structure query language which is a common database language for all RDBMS products. Different RDBMS product vendors have developed their own database language by extending SQL for their own RDBMS products.
T-SQL stands for Transact Structure Query Language which is a Microsoft product and is an extension of SQL Language.
MS SQL Server - SQL\T-SQL
ORACLE - SQL\PL-SQL
SQL Server data type is an attribute that specifies types of data of any object. Each column, variable and expression has related data type in SQL Server. These data types can be used while creating tables. You can choose a particular data type for a table column based on your requirement.
SQL Server offers seven categories including other category of data types for use.
Numeric and decimal are Fixed precision and scale data types and are functionally equivalent.
datetime(3.33 milliseconds accuracy)
smalldatetime(1 minute accuracy)
date(1 day accuracy. Introduced in SQL Server 2008)
datetimeoffset(100 nanoseconds accuracy. Introduced in SQL Server 2008)
datetime2(100 nanoseconds accuracy. Introduced in SQL Server 2008)
time(100 nanoseconds accuracy. Introduced in SQL Server 2008)
char
Fixed-length non-Unicode character data with a maximum length of 8,000 characters.
varchar
Variable-length non-Unicode data with a maximum of 8,000 characters.
Varchar (max)
Variable-length non-Unicode data with a maximum length of 231 characters (Introduced in SQL Server 2005).
text
Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters
nchar
Fixed-length Unicode data with a maximum length of 4,000 characters.
nvarchar
Variable-length Unicode data with a maximum length of 4,000 characters.
Nvarchar (max)
Variable-length Unicode data with a maximum length of 230 characters (Introduced in SQL Server 2005).
ntext
Variable-length Unicode data with a maximum length of 1,073,741,823 characters.
binary
Fixed-length binary data with a maximum length of 8,000 bytes.
varbinary
Variable-length binary data with a maximum length of 8,000 bytes.
varbinary(max)
Variable-length binary data with a maximum length of 231 bytes (Introduced in SQL Server 2005).
image
Variable-length binary data with a maximum length of 2,147,483,647 bytes.
sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.
sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.
timestamp − Stores a database-wide unique number that gets updated every time a row gets updated.
timestamp − Stores a database-wide unique number that gets updated every time a row gets updated.
uniqueidentifier − Stores a globally unique identifier (GUID).
uniqueidentifier − Stores a globally unique identifier (GUID).
xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005).
xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005).
cursor − A reference to a cursor.
cursor − A reference to a cursor.
table − Stores a result set for later processing.
table − Stores a result set for later processing.
hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008).
hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008).
Creating a basic table involves naming the table and defining its columns and each column's data type.
The SQL Server CREATE TABLE statement is used to create a new table.
Following is the basic syntax of CREATE TABLE statement −
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns ));
CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer to understand with the following example.
A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check complete details at Create Table Using another Table.
In this example, let’s create a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table −
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the following command −
exec sp_columns CUSTOMERS
The above command produces the following output.
TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME
PRECISION LENGTH SCALE RADIX NULLABLE REMARKS COLUMN_DEF SQL_DATA_TYPE
SQL_DATETIME_SUB CHAR_OCTET_LENGTH ORDINAL_POSITION IS_NULLABLE SS_DATA_TYPE
TestDB dbo CUSTOMERS ID 4 int 10 4 0 10 0
NULL NULL 4 NULL NULL 1 NO 56
TestDB dbo CUSTOMERS NAME 12 varchar 20 20 NULL NULL 0
NULL NULL 12 NULL 20 2 NO 39
TestDB dbo CUSTOMERS AGE 4 int 10 4 0 10 0
NULL NULL 4 NULL NULL 3 NO 56
TestDB dbo CUSTOMERS ADDRESS 1 char 25 25 NULL NULL 1
NULL NULL 1 NULL 25 4 YES 39
TestDB dbo CUSTOMERS SALARY 3 decimal 18 20 2 10 1
NULL NULL 3 NULL NULL 5 YES 106
You can now see that CUSTOMERS table is available in your database which you can use to store required information related to customers.
The SQL Server DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table.
Note − You have to be careful while using this command because once a table is deleted then all the information available in the table would also be lost forever.
Following is the basic syntax of DROP TABLE statement −
DROP TABLE table_name;
Let us first verify CUSTOMERS table and then we will delete it from the database −
Exec sp_columns CUSTOMERS;
The above command shows the following table.
TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME
PRECISION LENGTH SCALE RADIX NULLABLE REMARKS COLUMN_DEF SQL_DATA_TYPE
SQL_DATETIME_SUB CHAR_OCTET_LENGTH ORDINAL_POSITION IS_NULLABLE SS_DATA_TYPE
TestDB dbo CUSTOMERS ID 4 int 10 4 0 10 0
NULL NULL 4 NULL NULL 1 NO 56
TestDB dbo CUSTOMERS NAME 12 varchar 20 20 NULL NULL 0
NULL NULL 12 NULL 20 2 NO 39
TestDB dbo CUSTOMERS AGE 4 int 10 4 0 10 0
NULL NULL 4 NULL NULL 3 NO 56
TestDB dbo CUSTOMERS ADDRESS 1 char 25 25 NULL NULL 1
NULL NULL 1 NULL 25 4 YES 39
TestDB dbo CUSTOMERS SALARY 3 decimal 18 20 2 10 1
NULL NULL 3 NULL NULL 5 YES 106
CUSTOMERS table is available in the database, so let us drop it. Following is the command for the same.
DROP TABLE CUSTOMERS;
Command(s) completed successfully.
With the above command, you will not get any rows.
Exec sp_columns CUSTOMERS;
No rows\data will be displayed
The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database.
Following are the two basic syntaxes of INSERT INTO statement.
INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Where column1, column2,...columnN are the names of the columns in the table into which you want to insert data.
You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Following statements will create six records in CUSTOMERS table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );
You can create a record in CUSTOMERS table using second syntax as follows −
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements will produce the following records in CUSTOMERS table −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −
INSERT INTO first_table_name
SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];
SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets.
Following is the basic syntax of SELECT statement −
SELECT column1, column2, columnN FROM table_name;
Where, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −
SELECT * FROM table_name;
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table −
SELECT ID, NAME, SALARY FROM CUSTOMERS;
The above command will produce the following output.
ID NAME SALARY
1 Ramesh 2000.00
2 Khilan 1500.00
3 kaushik 2000.00
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
If you want to fetch all the fields of CUSTOMERS table, then use the following query −
SELECT * FROM CUSTOMERS;
The above will produce the following output.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
The SQL Server UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected.
Following is the basic syntax of UPDATE query with WHERE clause −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which would update ADDRESS for a customer whose ID is 6 −
UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
CUSTOMERS table will now have the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Pune 4500.00
7 Muffy 24 Indore 10000.00
If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to use WHERE clause. UPDATE query would be as follows −
UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
CUSTOMERS table will now have the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Pune 1000.00
2 Khilan 25 Pune 1000.00
3 kaushik 23 Pune 1000.00
4 Chaitali 25 Pune 1000.00
5 Hardik 27 Pune 1000.00
6 Komal 22 Pune 1000.00
7 Muffy 24 Pune 1000.00
The SQL Server DELETE Query is used to delete the existing records from a table.
You have to use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.
Following is the basic syntax of DELETE query with WHERE clause −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which would DELETE a customer, whose ID is 6 −
DELETE FROM CUSTOMERS
WHERE ID = 6;
CUSTOMERS table will now have the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00
If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause. DELETE query would be as follows −
DELETE FROM CUSTOMERS;
CUSTOMERS table now will not have any record.
The MS SQL Server WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple tables.
If the given condition is satisfied, only then it returns a specific value from the table. You will have to use WHERE clause to filter the records and fetch only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we would examine in subsequent chapters.
Following is the basic syntax of SELECT statement with WHERE clause −
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc. The following example will make this concept clear.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000.
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;
The above command will produce the following output.
ID NAME SALARY
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
Following command is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table for a customer with the name ‘Hardik’. It is important to note that all the strings should be given inside single quotes ('') whereas numeric values should be given without any quote as in the above example −
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = 'Hardik';
The above command will produce the following output.
ID NAME SALARY
5 Hardik 8500.00
The MS SQL Server LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator −
The percent sign (%)
The underscore (_)
The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character. The symbols can be used in combinations.
Following is the basic syntax of % and _.
SELECT *\column-list FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT *\column-list FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT *\column-list FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT *\column-list FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT *\column-list FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. XXXX could be any numeric or string value.
Following are a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators.
WHERE SALARY LIKE '200%'
Finds any values that start with 200
WHERE SALARY LIKE '%200%'
Finds any values that have 200 in any position
WHERE SALARY LIKE '_00%'
Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_%'
Finds any values that start with 2 and are at least 3 characters in length
WHERE SALARY LIKE '%2'
Finds any values that end with 2
WHERE SALARY LIKE '_2%3'
Finds any values that have a 2 in the second position and end with a 3
WHERE SALARY LIKE '2___3'
Finds any values in a five-digit number that start with 2 and end with 3
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which will display all the records from CUSTOMERS table where SALARY starts with 200.
SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
3 kaushik 23 Kota 2000.00
The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default.
Following is the basic syntax of ORDER BY clause.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example, which would sort the result in ascending order by NAME and SALARY.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
3 kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
1 Ramesh 32 Ahmedabad 2000.00
Following command is an example, which would sort the result in descending order by NAME.
SELECT * FROM CUSTOMERS
ORDER BY NAME DESC
The above command will produce the following result −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
7 Muffy 24 Indore 10000.00
6 Komal 22 MP 4500.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
4 Chaitali 25 Mumbai 6500.00
The SQL Server GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
Following is the basic syntax of GROUP BY clause. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Consider the CUSTOMERS table is having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
If you want to know the total amount of salary on each customer, then following will be the GROUP BY query.
SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
GROUP BY NAME;
The above command will produce the following output.
NAME sum of salary
Chaitali 6500.00
Hardik 8500.00
kaushik 2000.00
Khilan 1500.00
Komal 4500.00
Muffy 10000.00
Ramesh 2000.00
Let us now consider the following CUSTOMERS table having the following records with duplicate names.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
If we want to know the total amount of salary on each customer, then following will be GROUP BY query.
SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
GROUP BY NAME
The above command will produce the following output.
NAME sum of salary
Hardik 8500.00
kaushik 8500.00
Komal 4500.00
Muffy 10000.00
Ramesh 3500.00
The MS SQL Server DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.
Following is the basic syntax of DISTINCT keyword to eliminate duplicate records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Let us see how the following SELECT query returns duplicate salary records.
SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY
The above command will produce the following output where salary 2000 comes twice which is a duplicate record from the original table.
SALARY
1500.00
2000.00
2000.00
4500.00
6500.00
8500.00
10000.00
Let us now use DISTINCT keyword with the above SELECT query and see the result.
SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY
The above command produces the following output where we do not have any duplicate entry.
SALARY
1500.00
2000.00
4500.00
6500.00
8500.00
10000.00
The MS SQL Server Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.
Consider the following two tables, (a) CUSTOMERS table is as follows −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
(b) Another table is ORDERS as follows −
OID DATE CUSTOMER_ID AMOUNT
100 2009-10-08 00:00:00.000 3 1500.00
101 2009-11-20 00:00:00.000 2 1560.00
102 2009-10-08 00:00:00.000 3 3000.00
103 2008-05-20 00:00:00.000 4 2060.00
Let us join these two tables in our SELECT statement as follows −
SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID
OR
SELECT A.ID, A.NAME, A.AGE, B.AMOUNT
FROM CUSTOMERS A inner join ORDERS B on A.ID = B.Customer_ID
The above command will produce the following output.
ID NAME AGE AMOUNT
2 Khilan 25 1560.00
3 kaushik 23 1500.00
3 kaushik 23 3000.00
4 Chaitali 25 2060.00
It is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol.
MS SQL Server Join Types −
There are different types of joins available in MS SQL Server −
INNER JOIN − Returns rows when there is a match in both tables.
INNER JOIN − Returns rows when there is a match in both tables.
LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table.
LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table.
RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN − Returns rows when there is a match in one of the tables.
FULL JOIN − Returns rows when there is a match in one of the tables.
SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement.
SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement.
CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables.
CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables.
A sub-query or Inner query or Nested query is a query within another SQL Server query and embedded within the WHERE clause. A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that sub queries must follow −
You must enclose a subquery in parenthesis.
You must enclose a subquery in parenthesis.
A subquery must include a SELECT clause and a FROM clause.
A subquery must include a SELECT clause and a FROM clause.
A subquery can include optional WHERE, GROUP BY, and HAVING clauses.
A subquery can include optional WHERE, GROUP BY, and HAVING clauses.
A subquery cannot include COMPUTE or FOR BROWSE clauses.
A subquery cannot include COMPUTE or FOR BROWSE clauses.
You can include an ORDER BY clause only when a TOP clause is included.
You can include an ORDER BY clause only when a TOP clause is included.
You can nest sub queries up to 32 levels.
You can nest sub queries up to 32 levels.
Subqueries are most frequently used with the SELECT statement. Following is the basic syntax.
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Let us apply the following subquery with SELECT statement.
SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500)
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00
Sub queries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.
Following is the basic syntax.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Following is the syntax to copy complete CUSTOMERS table into CUSTOMERS_BKP.
INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS)
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.
Following is the basic syntax.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following command example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 )
This will impact two rows and finally CUSTOMERS table will have the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 500.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 2125.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.
Following is the basic syntax.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following command example deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 )
This would impact two rows and finally CUSTOMERS table will have the following records.
ID NAME AGE ADDRESS SALARY
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
The MS SQL Server Stored procedure is used to save time to write code again and again by storing the same in database and also get the required output by passing parameters.
Following is the basic syntax of Stored procedure creation.
Create procedure <procedure_Name>
As
Begin
<SQL Statement>
End
Go
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command is an example which would fetch all records from the CUSTOMERS table in Testdb database.
CREATE PROCEDURE SelectCustomerstabledata
AS
SELECT * FROM Testdb.Customers
GO
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.
Transactions have the following four standard properties, usually referred to by the acronym ACID −
Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.
Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.
Consistency − Ensures that the database properly changes state upon a successfully committed transaction.
Consistency − Ensures that the database properly changes state upon a successfully committed transaction.
Isolation − Enables transactions to operate independently of and transparent to each other.
Isolation − Enables transactions to operate independently of and transparent to each other.
Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.
Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.
There are following commands used to control transactions −
COMMIT − To save the changes.
COMMIT − To save the changes.
ROLLBACK − To roll back the changes.
ROLLBACK − To roll back the changes.
SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK.
SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK.
SET TRANSACTION − Places a name on a transaction.
SET TRANSACTION − Places a name on a transaction.
Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.
In order to use transactional control commands in MS SQL Server, we have to begin transaction with ‘begin tran’ or begin transaction command otherwise these commands will not work.
The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. This command saves all transactions to the database since the last COMMIT or ROLLBACK command.
Following is the syntax for COMMIT command.
COMMIT;
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command example will delete records from the table having age = 25 and then COMMIT the changes in the database.
Begin Tran
DELETE FROM CUSTOMERS
WHERE AGE = 25
COMMIT
As a result, two rows from the table would be deleted and SELECT statement will produce the following output.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
3 kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.
Following is the syntax for ROLLBACK command.
ROLLBACK
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following command example will delete records from the table having age = 25 and then ROLLBACK the changes in the database.
Begin Tran
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK
As a result, delete operation will not impact the table and SELECT statement will produce the following result.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.
Following is the syntax for SAVEPOINT command.
SAVE TRANSACTION SAVEPOINT_NAME
This command serves only in the creation of a SAVEPOINT among transactional statements. The ROLLBACK command is used to undo a group of transactions.
Following is the syntax for rolling back to a SAVEPOINT.
ROLLBACK TO SAVEPOINT_NAME
In the following example, we will delete three different records from the CUSTOMERS table. We will have to create a SAVEPOINT before each delete, so that we can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state.
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Following are the series of operations −
Begin Tran
SAVE Transaction SP1
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 1
1 row deleted.
SAVE Transaction SP2
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 2
1 row deleted.
SAVE Transaction SP3
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 3
1 row deleted.
The three deletions have taken place, however, we have changed our mind and decide to ROLLBACK to the SAVEPOINT that we identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −
ROLLBACK Transaction SP2
Rollback complete.
Notice that only the first deletion took place since we rolled back to SP2.
SELECT * FROM CUSTOMERS
6 rows selected.
ID NAME AGE ADDRESS SALARY
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows.
Following is the syntax for SET TRANSACTION.
SET TRANSACTION ISOLATION LEVEL <Isolationlevel_name>
Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index at the end of a book.
For example, if you want to reference all the pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers.
An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in ascending or descending order.
Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index.
Following is the basic syntax of CREATE INDEX.
CREATE INDEX index_name ON table_name
A single-column index is one that is created based on only one table column. Following is the basic syntax.
CREATE INDEX index_name
ON table_name (column_name)
CREATE INDEX singlecolumnindex
ON customers (ID)
Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. Following is the basic syntax.
CREATE UNIQUE INDEX index_name
on table_name (column_name)
CREATE UNIQUE INDEX uniqueindex
on customers (NAME)
A composite index is an index on two or more columns of a table. Following is the basic syntax.
CREATE INDEX index_name on table_name (column1, column2)
CREATE INDEX compositeindex
on customers (NAME, ID)
Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice.
Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.
An index can be dropped using MS SQL SERVER DROP command. Care should be taken when dropping an index because performance may be slowed or improved.
Following is the basic syntax.
DROP INDEX tablename.index_name
Although indexes are intended to enhance the performance of databases, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered −
Indexes should not be used on small tables.
Indexes should not be used on small tables.
Tables that have frequent, large batch update or insert operations should not be indexed.
Tables that have frequent, large batch update or insert operations should not be indexed.
Indexes should not be used on columns that contain a high number of NULL values.
Indexes should not be used on columns that contain a high number of NULL values.
Columns that are frequently manipulated should not be indexed.
Columns that are frequently manipulated should not be indexed.
MS SQL Server has many built-in functions to perform processing on string or numeric data. Following is the list of all useful SQL built-in functions −
SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table.
SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table.
SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column.
SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column.
SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column.
SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column.
SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column.
SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column.
SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column.
SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column.
SQL Server SQRT Function − This is used to generate a square root of a given number.
SQL Server SQRT Function − This is used to generate a square root of a given number.
SQL Server RAND Function − This is used to generate a random number using SQL command.
SQL Server RAND Function − This is used to generate a random number using SQL command.
SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter.
SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter.
SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL.
SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL.
SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL.
SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL.
MS SQL Server String functions can be applied on string value or will return string value or numeric data.
Following is the list of String functions with examples.
Ascii code value will come as output for a character expression.
The following query will give the Ascii code value of a given character.
Select ASCII ('word')
Character will come as output for given Ascii code or integer.
The following query will give the character for a given integer.
Select CHAR(97)
Unicode character will come as output for a given integer.
The following query will give the Unicode character for a given integer.
Select NCHAR(300)
Starting position for given search expression will come as output in a given string expression.
The following query will give the starting position of 'G' character for given string expression 'KING'.
Select CHARINDEX('G', 'KING')
Left part of the given string till the specified number of characters will come as output for a given string.
The following query will give the 'WORL' string as mentioned 4 number of characters for given string 'WORLD'.
Select LEFT('WORLD', 4)
Right part of the given string till the specified number of characters will come as output for a given string.
The following query will give the 'DIA' string as mentioned 3 number of characters for given string 'INDIA'.
Select RIGHT('INDIA', 3)
Part of a string based on the start position value and length value will come as output for a given string.
The following queries will give the 'WOR', 'DIA', 'ING' strings as we mentioned (1,3), (3,3) and (2,3) as start and length values respectively for given strings 'WORLD', 'INDIA' and 'KING'.
Select SUBSTRING ('WORLD', 1,3)
Select SUBSTRING ('INDIA', 3,3)
Select SUBSTRING ('KING', 2,3)
Number of characters will come as output for a given string expression.
The following query will give the 5 for the 'HELLO' string expression.
Select LEN('HELLO')
Lowercase string will come as output for a given string data.
The following query will give the 'sqlserver' for the 'SQLServer' character data.
Select LOWER('SQLServer')
Uppercase string will come as output for a given string data.
The following query will give the 'SQLSERVER' for the 'SqlServer' character data.
Select UPPER('SqlServer')
String expression will come as output for a given string data after removing leading blanks.
The following query will give the 'WORLD' for the ' WORLD' character data.
Select LTRIM(' WORLD')
String expression will come as output for a given string data after removing trailing blanks.
The following query will give the 'INDIA' for the 'INDIA ' character data.
Select RTRIM('INDIA ')
String expression will come as output for a given string data after replacing all occurrences of specified character with specified character.
The following query will give the 'KNDKA' string for the 'INDIA' string data.
Select REPLACE('INDIA', 'I', 'K')
Repeat string expression will come as output for a given string data with specified number of times.
The following query will give the 'WORLDWORLD' string for the 'WORLD' string data.
Select REPLICATE('WORLD', 2)
Reverse string expression will come as output for a given string data.
The following query will give the 'DLROW' string for the 'WORLD' string data.
Select REVERSE('WORLD')
Returns four-character (SOUNDEX) code to evaluate the similarity of two given strings.
The following query will give the 'S530' for the 'Smith', 'Smyth' strings.
Select SOUNDEX('Smith'), SOUNDEX('Smyth')
Integer value will come as output of given two expressions.
The following query will give the 4 for the 'Smith', 'Smyth' expressions.
Select Difference('Smith','Smyth')
Note − If the output value is 0 it indicates weak or no similarity between give 2 expressions.
String will come as output with the specified number of spaces.
The following query will give the 'I LOVE INDIA'.
Select 'I'+space(1)+'LOVE'+space(1)+'INDIA'
String expression will come as output for a given string data after replacing from starting character till the specified length with specified character.
The following query will give the 'AIJKFGH' string for the 'ABCDEFGH' string data as per given starting character and length as 2 and 4 respectively and 'IJK' as specified target string.
Select STUFF('ABCDEFGH', 2,4,'IJK')
Character data will come as output for the given numeric data.
The following query will give the 187.37 for the given 187.369 based on specified length as 6 and decimal as 2.
Select STR(187.369,6,2)
Integer value will come as output for the first character of given expression.
The following query will give the 82 for the 'RAMA' expression.
Select UNICODE('RAMA')
Given string will come as output with the specified delimiter.
The following query will give the "RAMA" for the given 'RAMA' string as we specified double quote as delimiter.
Select QUOTENAME('RAMA','"')
Starting position of the first occurrence from the given expression as we specified 'I' position is required.
The following query will give the 1 for the 'INDIA'.
Select PATINDEX('I%','INDIA')
Given expression will come as output with the specified format.
The following query will give the ' Monday, November 16, 2015' for the getdate function as per specified format with 'D' refers weekday name.
SELECT FORMAT ( getdate(), 'D')
Single string will come as output after concatenating the given parameter values.
The following query will give the 'A,B,C' for the given parameters.
Select CONCAT('A',',','B',',','C')
Following is the list of date functions in MS SQL Server.
It will return the current date along with time.
Syntax for the above function −
GETDATE()
The following query will return the current date along with time in MS SQL Server.
Select getdate() as currentdatetime
It will return the part of date or time.
Syntax for the above function −
DATEPART(datepart, datecolumnname)
Example 1 − The following query will return the part of current date in MS SQL Server.
Select datepart(day, getdate()) as currentdate
Example 2 − The following query will return the part of current month in MS SQL Server.
Select datepart(month, getdate()) as currentmonth
It will display the date and time by add or subtract date and time interval.
Syntax for the above function −
DATEADD(datepart, number, datecolumnname)
The following query will return the after 10 days date and time from the current date and time in MS SQL Server.
Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime
It will display the date and time between two dates.
Syntax for the above function −
DATEDIFF(datepart, startdate, enddate)
The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server.
Select datediff(hour, 2015-11-16, 2015-11-11) as
differencehoursbetween20151116and20151111
It will display the date and time in different formats.
Syntax for the above function −
CONVERT(datatype, expression, style)
The following queries will return the date and time in different format in MS SQL Server.
SELECT CONVERT(VARCHAR(19),GETDATE())
SELECT CONVERT(VARCHAR(10),GETDATE(),10)
SELECT CONVERT(VARCHAR(10),GETDATE(),110)
MS SQL Server numeric functions can be applied on numeric data and will return numeric data.
Following is the list of Numeric functions with examples.
Absolute value will come as output for numeric expression.
The following query will give the absolute value.
Select ABS(-22)
Arc cosine value will come as output for the specified numeric expression.
The following query will give the arc cosine value of 0.
Select ACOS(0)
Arc sine value will come as output for the specified numeric expression.
The following query will give the arc sine value of 0.
Select ASIN(0)
Arc tangent value will come as output for the specified numeric expression.
The following query will give the arc tangent value of 0.
Select ATAN(0)
Arc tangent value in all four quadrants will come as output for the specified numeric expression.
The following query will give the arc tangent value in all four quadrants of 0.
Select ATN2(0, -1)
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
If the values exist between given two expressions then those will be come as output.
The following query will give the following output.
SELECT salary from customers where salary between 2000 and 8500
salary
2000.00
2000.00
6500.00
8500.00
4500.00
Minimum value will come as output from the given expression.
The following query will give '1500.00' for the given 'salary' expression from the customers table.
Select MIN(salary)from CUSTOMERS
Maximum value will come as output from the given expression.
The following query will give '10000.00' for the given 'salary' expression from the customers table.
Select MAX(salary)from CUSTOMERS
Square root of the given numeric expression will come as output.
The following query will give 2 for the given 4 numeric expression.
Select SQRT(4)
PI value will come as output.
The following query will give 3.14159265358979 for the PI value.
Select PI()
Given value will come as output after rounding the decimals which is the next highest value.
The following query will give 124 for the given 123.25 value.
Select CEILING(123.25)
Given value will come as output after rounding the decimals which is less than or equal to the expression.
The following query will give 123 for the given 123.25 value.
Select FLOOR(123.25)
Natural logarithm of the given expression will come as output.
The following query will give 0 for the given 1 value.
Select LOG(1)
12 Lectures
2 hours
Nishant Malik
10 Lectures
1.5 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
20 Lectures
2 hours
Asif Hussain
10 Lectures
1.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2233,
"s": 2060,
"text": "In 1970's the product called 'SEQUEL', structured English query language, developed by IBM and later SEQUEL was renamed to 'SQL' which stands for Structured Query Language."
},
{
"code": null,
"e": 2383,
"s": 2233,
"text": "In 1986, SQL was approved by ANSI (American national Standards Institute) and in 1987, it was approved by ISO (International Standards Organization)."
},
{
"code": null,
"e": 2599,
"s": 2383,
"text": "SQL is a structure query language which is a common database language for all RDBMS products. Different RDBMS product vendors have developed their own database language by extending SQL for their own RDBMS products."
},
{
"code": null,
"e": 2716,
"s": 2599,
"text": "T-SQL stands for Transact Structure Query Language which is a Microsoft product and is an extension of SQL Language."
},
{
"code": null,
"e": 2742,
"s": 2716,
"text": "MS SQL Server - SQL\\T-SQL"
},
{
"code": null,
"e": 2762,
"s": 2742,
"text": "ORACLE - SQL\\PL-SQL"
},
{
"code": null,
"e": 3053,
"s": 2762,
"text": "SQL Server data type is an attribute that specifies types of data of any object. Each column, variable and expression has related data type in SQL Server. These data types can be used while creating tables. You can choose a particular data type for a table column based on your requirement."
},
{
"code": null,
"e": 3136,
"s": 3053,
"text": "SQL Server offers seven categories including other category of data types for use."
},
{
"code": null,
"e": 3230,
"s": 3136,
"text": "Numeric and decimal are Fixed precision and scale data types and are functionally equivalent."
},
{
"code": null,
"e": 3267,
"s": 3230,
"text": "datetime(3.33 milliseconds accuracy)"
},
{
"code": null,
"e": 3300,
"s": 3267,
"text": "smalldatetime(1 minute accuracy)"
},
{
"code": null,
"e": 3352,
"s": 3300,
"text": "date(1 day accuracy. Introduced in SQL Server 2008)"
},
{
"code": null,
"e": 3424,
"s": 3352,
"text": "datetimeoffset(100 nanoseconds accuracy. Introduced in SQL Server 2008)"
},
{
"code": null,
"e": 3491,
"s": 3424,
"text": "datetime2(100 nanoseconds accuracy. Introduced in SQL Server 2008)"
},
{
"code": null,
"e": 3553,
"s": 3491,
"text": "time(100 nanoseconds accuracy. Introduced in SQL Server 2008)"
},
{
"code": null,
"e": 3558,
"s": 3553,
"text": "char"
},
{
"code": null,
"e": 3641,
"s": 3558,
"text": "Fixed-length non-Unicode character data with a maximum length of 8,000 characters."
},
{
"code": null,
"e": 3649,
"s": 3641,
"text": "varchar"
},
{
"code": null,
"e": 3718,
"s": 3649,
"text": "Variable-length non-Unicode data with a maximum of 8,000 characters."
},
{
"code": null,
"e": 3732,
"s": 3718,
"text": "Varchar (max)"
},
{
"code": null,
"e": 3838,
"s": 3732,
"text": "Variable-length non-Unicode data with a maximum length of 231 characters (Introduced in SQL Server 2005)."
},
{
"code": null,
"e": 3843,
"s": 3838,
"text": "text"
},
{
"code": null,
"e": 3926,
"s": 3843,
"text": "Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters"
},
{
"code": null,
"e": 3932,
"s": 3926,
"text": "nchar"
},
{
"code": null,
"e": 4001,
"s": 3932,
"text": "Fixed-length Unicode data with a maximum length of 4,000 characters."
},
{
"code": null,
"e": 4010,
"s": 4001,
"text": "nvarchar"
},
{
"code": null,
"e": 4082,
"s": 4010,
"text": "Variable-length Unicode data with a maximum length of 4,000 characters."
},
{
"code": null,
"e": 4097,
"s": 4082,
"text": "Nvarchar (max)"
},
{
"code": null,
"e": 4199,
"s": 4097,
"text": "Variable-length Unicode data with a maximum length of 230 characters (Introduced in SQL Server 2005)."
},
{
"code": null,
"e": 4205,
"s": 4199,
"text": "ntext"
},
{
"code": null,
"e": 4285,
"s": 4205,
"text": "Variable-length Unicode data with a maximum length of 1,073,741,823 characters."
},
{
"code": null,
"e": 4292,
"s": 4285,
"text": "binary"
},
{
"code": null,
"e": 4355,
"s": 4292,
"text": "Fixed-length binary data with a maximum length of 8,000 bytes."
},
{
"code": null,
"e": 4365,
"s": 4355,
"text": "varbinary"
},
{
"code": null,
"e": 4431,
"s": 4365,
"text": "Variable-length binary data with a maximum length of 8,000 bytes."
},
{
"code": null,
"e": 4446,
"s": 4431,
"text": "varbinary(max)"
},
{
"code": null,
"e": 4542,
"s": 4446,
"text": "Variable-length binary data with a maximum length of 231 bytes (Introduced in SQL Server 2005)."
},
{
"code": null,
"e": 4548,
"s": 4542,
"text": "image"
},
{
"code": null,
"e": 4622,
"s": 4548,
"text": "Variable-length binary data with a maximum length of 2,147,483,647 bytes."
},
{
"code": null,
"e": 4729,
"s": 4622,
"text": "sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp."
},
{
"code": null,
"e": 4836,
"s": 4729,
"text": "sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp."
},
{
"code": null,
"e": 4934,
"s": 4836,
"text": "timestamp − Stores a database-wide unique number that gets updated every time a row gets updated."
},
{
"code": null,
"e": 5032,
"s": 4934,
"text": "timestamp − Stores a database-wide unique number that gets updated every time a row gets updated."
},
{
"code": null,
"e": 5095,
"s": 5032,
"text": "uniqueidentifier − Stores a globally unique identifier (GUID)."
},
{
"code": null,
"e": 5158,
"s": 5095,
"text": "uniqueidentifier − Stores a globally unique identifier (GUID)."
},
{
"code": null,
"e": 5268,
"s": 5158,
"text": "xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005)."
},
{
"code": null,
"e": 5378,
"s": 5268,
"text": "xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005)."
},
{
"code": null,
"e": 5412,
"s": 5378,
"text": "cursor − A reference to a cursor."
},
{
"code": null,
"e": 5446,
"s": 5412,
"text": "cursor − A reference to a cursor."
},
{
"code": null,
"e": 5496,
"s": 5446,
"text": "table − Stores a result set for later processing."
},
{
"code": null,
"e": 5546,
"s": 5496,
"text": "table − Stores a result set for later processing."
},
{
"code": null,
"e": 5671,
"s": 5546,
"text": "hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008)."
},
{
"code": null,
"e": 5796,
"s": 5671,
"text": "hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008)."
},
{
"code": null,
"e": 5899,
"s": 5796,
"text": "Creating a basic table involves naming the table and defining its columns and each column's data type."
},
{
"code": null,
"e": 5968,
"s": 5899,
"text": "The SQL Server CREATE TABLE statement is used to create a new table."
},
{
"code": null,
"e": 6026,
"s": 5968,
"text": "Following is the basic syntax of CREATE TABLE statement −"
},
{
"code": null,
"e": 6191,
"s": 6026,
"text": "CREATE TABLE table_name( \n column1 datatype, \n column2 datatype, \n column3 datatype, \n ..... \n columnN datatype, \n PRIMARY KEY( one or more columns ));\n"
},
{
"code": null,
"e": 6563,
"s": 6191,
"text": "CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer to understand with the following example."
},
{
"code": null,
"e": 6750,
"s": 6563,
"text": "A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check complete details at Create Table Using another Table."
},
{
"code": null,
"e": 6934,
"s": 6750,
"text": "In this example, let’s create a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table −"
},
{
"code": null,
"e": 7151,
"s": 6934,
"text": "CREATE TABLE CUSTOMERS( \n ID INT NOT NULL, \n NAME VARCHAR (20) NOT NULL, \n AGE INT NOT NULL, \n ADDRESS CHAR (25) , \n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID));"
},
{
"code": null,
"e": 7311,
"s": 7151,
"text": "You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the following command −"
},
{
"code": null,
"e": 7338,
"s": 7311,
"text": "exec sp_columns CUSTOMERS\n"
},
{
"code": null,
"e": 7387,
"s": 7338,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 8330,
"s": 7387,
"text": "TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME\n PRECISION LENGTH SCALE RADIX NULLABLE REMARKS COLUMN_DEF SQL_DATA_TYPE \n SQL_DATETIME_SUB CHAR_OCTET_LENGTH ORDINAL_POSITION IS_NULLABLE SS_DATA_TYPE\n \nTestDB dbo CUSTOMERS ID 4 int 10 4 0 10 0\n NULL NULL 4 NULL NULL 1 NO 56 \n \nTestDB dbo CUSTOMERS NAME 12 varchar 20 20 NULL NULL 0\n NULL NULL 12 NULL 20 2 NO 39\n \nTestDB dbo CUSTOMERS AGE 4 int 10 4 0 10 0\n NULL NULL 4 NULL NULL 3 NO 56 \n \nTestDB dbo CUSTOMERS ADDRESS 1 char 25 25 NULL NULL 1\n NULL NULL 1 NULL 25 4 YES 39 \n\nTestDB dbo CUSTOMERS SALARY 3 decimal 18 20 2 10 1\n NULL NULL 3 NULL NULL 5 YES 106 \n"
},
{
"code": null,
"e": 8467,
"s": 8330,
"text": "You can now see that CUSTOMERS table is available in your database which you can use to store required information related to customers."
},
{
"code": null,
"e": 8632,
"s": 8467,
"text": "The SQL Server DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table."
},
{
"code": null,
"e": 8795,
"s": 8632,
"text": "Note − You have to be careful while using this command because once a table is deleted then all the information available in the table would also be lost forever."
},
{
"code": null,
"e": 8851,
"s": 8795,
"text": "Following is the basic syntax of DROP TABLE statement −"
},
{
"code": null,
"e": 8875,
"s": 8851,
"text": "DROP TABLE table_name;\n"
},
{
"code": null,
"e": 8958,
"s": 8875,
"text": "Let us first verify CUSTOMERS table and then we will delete it from the database −"
},
{
"code": null,
"e": 8985,
"s": 8958,
"text": "Exec sp_columns CUSTOMERS;"
},
{
"code": null,
"e": 9030,
"s": 8985,
"text": "The above command shows the following table."
},
{
"code": null,
"e": 9992,
"s": 9030,
"text": "TABLE_QUALIFIER TABLE_OWNER TABLE_NAME COLUMN_NAME DATA_TYPE TYPE_NAME\n PRECISION LENGTH SCALE RADIX NULLABLE REMARKS COLUMN_DEF SQL_DATA_TYPE \n SQL_DATETIME_SUB CHAR_OCTET_LENGTH ORDINAL_POSITION IS_NULLABLE SS_DATA_TYPE\n \nTestDB dbo CUSTOMERS ID 4 int 10 4 0 10 0\n NULL NULL 4 NULL NULL 1 NO 56 \n \nTestDB dbo CUSTOMERS NAME 12 varchar 20 20 NULL NULL 0\n NULL NULL 12 NULL 20 2 NO 39\n \nTestDB dbo CUSTOMERS AGE 4 int 10 4 0 10 0\n NULL NULL 4 NULL NULL 3 NO 56 \n \nTestDB dbo CUSTOMERS ADDRESS 1 char 25 25 NULL NULL 1\n NULL NULL 1 NULL 25 4 YES 39 \n\nTestDB dbo CUSTOMERS SALARY 3 decimal 18 20 2 10 1\n NULL NULL 3 NULL NULL 5 YES 106 \n"
},
{
"code": null,
"e": 10096,
"s": 9992,
"text": "CUSTOMERS table is available in the database, so let us drop it. Following is the command for the same."
},
{
"code": null,
"e": 10155,
"s": 10096,
"text": "DROP TABLE CUSTOMERS; \nCommand(s) completed successfully.\n"
},
{
"code": null,
"e": 10206,
"s": 10155,
"text": "With the above command, you will not get any rows."
},
{
"code": null,
"e": 10267,
"s": 10206,
"text": "Exec sp_columns CUSTOMERS; \nNo rows\\data will be displayed \n"
},
{
"code": null,
"e": 10364,
"s": 10267,
"text": "The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database."
},
{
"code": null,
"e": 10427,
"s": 10364,
"text": "Following are the two basic syntaxes of INSERT INTO statement."
},
{
"code": null,
"e": 10539,
"s": 10427,
"text": "INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] \nVALUES (value1, value2, value3,...valueN); \n"
},
{
"code": null,
"e": 10651,
"s": 10539,
"text": "Where column1, column2,...columnN are the names of the columns in the table into which you want to insert data."
},
{
"code": null,
"e": 10897,
"s": 10651,
"text": "You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −"
},
{
"code": null,
"e": 10961,
"s": 10897,
"text": "INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);"
},
{
"code": null,
"e": 11027,
"s": 10961,
"text": "Following statements will create six records in CUSTOMERS table −"
},
{
"code": null,
"e": 11628,
"s": 11027,
"text": "INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );\n \nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (2, 'Khilan', 25, 'Delhi', 1500.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (3, 'kaushik', 23, 'Kota', 2000.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 ); \n \nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 ); \n\nINSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) \nVALUES (6, 'Komal', 22, 'MP', 4500.00 );"
},
{
"code": null,
"e": 11704,
"s": 11628,
"text": "You can create a record in CUSTOMERS table using second syntax as follows −"
},
{
"code": null,
"e": 11773,
"s": 11704,
"text": "INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );\n"
},
{
"code": null,
"e": 11854,
"s": 11773,
"text": "All the above statements will produce the following records in CUSTOMERS table −"
},
{
"code": null,
"e": 12311,
"s": 11854,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 12504,
"s": 12311,
"text": "You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −"
},
{
"code": null,
"e": 12632,
"s": 12504,
"text": "INSERT INTO first_table_name \n SELECT column1, column2, ...columnN \n FROM second_table_name \n [WHERE condition];\n"
},
{
"code": null,
"e": 12800,
"s": 12632,
"text": "SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets."
},
{
"code": null,
"e": 12852,
"s": 12800,
"text": "Following is the basic syntax of SELECT statement −"
},
{
"code": null,
"e": 12903,
"s": 12852,
"text": "SELECT column1, column2, columnN FROM table_name;\n"
},
{
"code": null,
"e": 13087,
"s": 12903,
"text": "Where, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −"
},
{
"code": null,
"e": 13114,
"s": 13087,
"text": "SELECT * FROM table_name;\n"
},
{
"code": null,
"e": 13174,
"s": 13114,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 13607,
"s": 13174,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 13733,
"s": 13607,
"text": "Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table −"
},
{
"code": null,
"e": 13774,
"s": 13733,
"text": "SELECT ID, NAME, SALARY FROM CUSTOMERS; "
},
{
"code": null,
"e": 13827,
"s": 13774,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 14044,
"s": 13827,
"text": "ID NAME SALARY \n1 Ramesh 2000.00 \n2 Khilan 1500.00 \n3 kaushik 2000.00 \n4 Chaitali 6500.00 \n5 Hardik 8500.00 \n6 Komal 4500.00 \n7 Muffy 10000.00 \n"
},
{
"code": null,
"e": 14131,
"s": 14044,
"text": "If you want to fetch all the fields of CUSTOMERS table, then use the following query −"
},
{
"code": null,
"e": 14156,
"s": 14131,
"text": "SELECT * FROM CUSTOMERS;"
},
{
"code": null,
"e": 14201,
"s": 14156,
"text": "The above will produce the following output."
},
{
"code": null,
"e": 14642,
"s": 14201,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 14721,
"s": 14642,
"text": "The SQL Server UPDATE Query is used to modify the existing records in a table."
},
{
"code": null,
"e": 14830,
"s": 14721,
"text": "You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected."
},
{
"code": null,
"e": 14896,
"s": 14830,
"text": "Following is the basic syntax of UPDATE query with WHERE clause −"
},
{
"code": null,
"e": 14997,
"s": 14896,
"text": "UPDATE table_name \nSET column1 = value1, column2 = value2...., columnN = valueN \nWHERE [condition];\n"
},
{
"code": null,
"e": 15063,
"s": 14997,
"text": "You can combine N number of conditions using AND or OR operators."
},
{
"code": null,
"e": 15123,
"s": 15063,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 15556,
"s": 15123,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 15647,
"s": 15556,
"text": "Following command is an example, which would update ADDRESS for a customer whose ID is 6 −"
},
{
"code": null,
"e": 15702,
"s": 15647,
"text": "UPDATE CUSTOMERS \nSET ADDRESS = 'Pune' \nWHERE ID = 6; "
},
{
"code": null,
"e": 15756,
"s": 15702,
"text": "CUSTOMERS table will now have the following records −"
},
{
"code": null,
"e": 16189,
"s": 15756,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 Pune 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 16340,
"s": 16189,
"text": "If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to use WHERE clause. UPDATE query would be as follows −"
},
{
"code": null,
"e": 16398,
"s": 16340,
"text": "UPDATE CUSTOMERS \nSET ADDRESS = 'Pune', SALARY = 1000.00;"
},
{
"code": null,
"e": 16451,
"s": 16398,
"text": "CUSTOMERS table will now have the following records."
},
{
"code": null,
"e": 16859,
"s": 16451,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Pune 1000.00 \n2 Khilan 25 Pune 1000.00 \n3 kaushik 23 Pune 1000.00 \n4 Chaitali 25 Pune 1000.00 \n5 Hardik 27 Pune 1000.00 \n6 Komal 22 Pune 1000.00 \n7 Muffy 24 Pune 1000.00 \n"
},
{
"code": null,
"e": 16940,
"s": 16859,
"text": "The SQL Server DELETE Query is used to delete the existing records from a table."
},
{
"code": null,
"e": 17056,
"s": 16940,
"text": "You have to use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted."
},
{
"code": null,
"e": 17122,
"s": 17056,
"text": "Following is the basic syntax of DELETE query with WHERE clause −"
},
{
"code": null,
"e": 17167,
"s": 17122,
"text": "DELETE FROM table_name \nWHERE [condition]; \n"
},
{
"code": null,
"e": 17233,
"s": 17167,
"text": "You can combine N number of conditions using AND or OR operators."
},
{
"code": null,
"e": 17293,
"s": 17233,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 17718,
"s": 17293,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 17798,
"s": 17718,
"text": "Following command is an example, which would DELETE a customer, whose ID is 6 −"
},
{
"code": null,
"e": 17836,
"s": 17798,
"text": "DELETE FROM CUSTOMERS \nWHERE ID = 6;\n"
},
{
"code": null,
"e": 17889,
"s": 17836,
"text": "CUSTOMERS table will now have the following records."
},
{
"code": null,
"e": 18275,
"s": 17889,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 18407,
"s": 18275,
"text": "If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause. DELETE query would be as follows −"
},
{
"code": null,
"e": 18431,
"s": 18407,
"text": "DELETE FROM CUSTOMERS;\n"
},
{
"code": null,
"e": 18477,
"s": 18431,
"text": "CUSTOMERS table now will not have any record."
},
{
"code": null,
"e": 18614,
"s": 18477,
"text": "The MS SQL Server WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple tables."
},
{
"code": null,
"e": 18795,
"s": 18614,
"text": "If the given condition is satisfied, only then it returns a specific value from the table. You will have to use WHERE clause to filter the records and fetch only necessary records."
},
{
"code": null,
"e": 18952,
"s": 18795,
"text": "The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we would examine in subsequent chapters."
},
{
"code": null,
"e": 19022,
"s": 18952,
"text": "Following is the basic syntax of SELECT statement with WHERE clause −"
},
{
"code": null,
"e": 19093,
"s": 19022,
"text": "SELECT column1, column2, columnN \nFROM table_name \nWHERE [condition]\n"
},
{
"code": null,
"e": 19241,
"s": 19093,
"text": "You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc. The following example will make this concept clear."
},
{
"code": null,
"e": 19301,
"s": 19241,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 19726,
"s": 19301,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 19863,
"s": 19726,
"text": "Following command is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000."
},
{
"code": null,
"e": 19927,
"s": 19863,
"text": "SELECT ID, NAME, SALARY \nFROM CUSTOMERS \nWHERE SALARY > 2000;\n"
},
{
"code": null,
"e": 19980,
"s": 19927,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 20100,
"s": 19980,
"text": "ID NAME SALARY \n4 Chaitali 6500.00 \n5 Hardik 8500.00 \n6 Komal 4500.00 \n7 Muffy 10000.00\n"
},
{
"code": null,
"e": 20412,
"s": 20100,
"text": "Following command is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table for a customer with the name ‘Hardik’. It is important to note that all the strings should be given inside single quotes ('') whereas numeric values should be given without any quote as in the above example −"
},
{
"code": null,
"e": 20478,
"s": 20412,
"text": "SELECT ID, NAME, SALARY \nFROM CUSTOMERS \nWHERE NAME = 'Hardik';\n"
},
{
"code": null,
"e": 20531,
"s": 20478,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 20575,
"s": 20531,
"text": "ID NAME SALARY \n5 Hardik 8500.00 \n"
},
{
"code": null,
"e": 20745,
"s": 20575,
"text": "The MS SQL Server LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator −"
},
{
"code": null,
"e": 20766,
"s": 20745,
"text": "The percent sign (%)"
},
{
"code": null,
"e": 20785,
"s": 20766,
"text": "The underscore (_)"
},
{
"code": null,
"e": 20945,
"s": 20785,
"text": "The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character. The symbols can be used in combinations."
},
{
"code": null,
"e": 20987,
"s": 20945,
"text": "Following is the basic syntax of % and _."
},
{
"code": null,
"e": 21349,
"s": 20987,
"text": "SELECT *\\column-list FROM table_name \nWHERE column LIKE 'XXXX%' \n \nor \n\nSELECT *\\column-list FROM table_name \nWHERE column LIKE '%XXXX%' \n\nor \n\nSELECT *\\column-list FROM table_name \nWHERE column LIKE 'XXXX_' \n\nor \n\nSELECT *\\column-list FROM table_name \nWHERE column LIKE '_XXXX' \n\nor \n\nSELECT *\\column-list FROM table_name \nWHERE column LIKE '_XXXX_' \n"
},
{
"code": null,
"e": 21458,
"s": 21349,
"text": "You can combine N number of conditions using AND or OR operators. XXXX could be any numeric or string value."
},
{
"code": null,
"e": 21569,
"s": 21458,
"text": "Following are a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators."
},
{
"code": null,
"e": 21594,
"s": 21569,
"text": "WHERE SALARY LIKE '200%'"
},
{
"code": null,
"e": 21631,
"s": 21594,
"text": "Finds any values that start with 200"
},
{
"code": null,
"e": 21657,
"s": 21631,
"text": "WHERE SALARY LIKE '%200%'"
},
{
"code": null,
"e": 21704,
"s": 21657,
"text": "Finds any values that have 200 in any position"
},
{
"code": null,
"e": 21729,
"s": 21704,
"text": "WHERE SALARY LIKE '_00%'"
},
{
"code": null,
"e": 21793,
"s": 21729,
"text": "Finds any values that have 00 in the second and third positions"
},
{
"code": null,
"e": 21819,
"s": 21793,
"text": "WHERE SALARY LIKE '2_%_%'"
},
{
"code": null,
"e": 21894,
"s": 21819,
"text": "Finds any values that start with 2 and are at least 3 characters in length"
},
{
"code": null,
"e": 21917,
"s": 21894,
"text": "WHERE SALARY LIKE '%2'"
},
{
"code": null,
"e": 21950,
"s": 21917,
"text": "Finds any values that end with 2"
},
{
"code": null,
"e": 21975,
"s": 21950,
"text": "WHERE SALARY LIKE '_2%3'"
},
{
"code": null,
"e": 22046,
"s": 21975,
"text": "Finds any values that have a 2 in the second position and end with a 3"
},
{
"code": null,
"e": 22072,
"s": 22046,
"text": "WHERE SALARY LIKE '2___3'"
},
{
"code": null,
"e": 22145,
"s": 22072,
"text": "Finds any values in a five-digit number that start with 2 and end with 3"
},
{
"code": null,
"e": 22204,
"s": 22145,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 22629,
"s": 22204,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 22748,
"s": 22629,
"text": "Following command is an example, which will display all the records from CUSTOMERS table where SALARY starts with 200."
},
{
"code": null,
"e": 22800,
"s": 22748,
"text": "SELECT * FROM CUSTOMERS \nWHERE SALARY LIKE '200%'; "
},
{
"code": null,
"e": 22853,
"s": 22800,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 22987,
"s": 22853,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n3 kaushik 23 Kota 2000.00\n"
},
{
"code": null,
"e": 23174,
"s": 22987,
"text": "The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default."
},
{
"code": null,
"e": 23224,
"s": 23174,
"text": "Following is the basic syntax of ORDER BY clause."
},
{
"code": null,
"e": 23338,
"s": 23224,
"text": "SELECT column-list \nFROM table_name \n[WHERE condition] \n[ORDER BY column1, column2, .. columnN] [ASC | DESC];\n"
},
{
"code": null,
"e": 23482,
"s": 23338,
"text": "You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list."
},
{
"code": null,
"e": 23542,
"s": 23482,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 23967,
"s": 23542,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 24067,
"s": 23967,
"text": "Following command is an example, which would sort the result in ascending order by NAME and SALARY."
},
{
"code": null,
"e": 24118,
"s": 24067,
"text": "SELECT * FROM CUSTOMERS \n ORDER BY NAME, SALARY "
},
{
"code": null,
"e": 24171,
"s": 24118,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 24588,
"s": 24171,
"text": "ID NAME AGE ADDRESS SALARY \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n3 kaushik 23 Kota 2000.00 \n2 Khilan 25 Delhi 1500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n1 Ramesh 32 Ahmedabad 2000.00 \n"
},
{
"code": null,
"e": 24678,
"s": 24588,
"text": "Following command is an example, which would sort the result in descending order by NAME."
},
{
"code": null,
"e": 24725,
"s": 24678,
"text": "SELECT * FROM CUSTOMERS \n ORDER BY NAME DESC"
},
{
"code": null,
"e": 24779,
"s": 24725,
"text": "The above command will produce the following result −"
},
{
"code": null,
"e": 25203,
"s": 24779,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00\n7 Muffy 24 Indore 10000.00 \n6 Komal 22 MP 4500.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00\n5 Hardik 27 Bhopal 8500.00\n4 Chaitali 25 Mumbai 6500.00 \n"
},
{
"code": null,
"e": 25324,
"s": 25203,
"text": "The SQL Server GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups."
},
{
"code": null,
"e": 25425,
"s": 25324,
"text": "The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause."
},
{
"code": null,
"e": 25595,
"s": 25425,
"text": "Following is the basic syntax of GROUP BY clause. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used."
},
{
"code": null,
"e": 25714,
"s": 25595,
"text": "SELECT column1, column2 \nFROM table_name \nWHERE [ conditions ] \nGROUP BY column1, column2 \nORDER BY column1, column2 \n"
},
{
"code": null,
"e": 25777,
"s": 25714,
"text": "Consider the CUSTOMERS table is having the following records −"
},
{
"code": null,
"e": 26186,
"s": 25777,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 26294,
"s": 26186,
"text": "If you want to know the total amount of salary on each customer, then following will be the GROUP BY query."
},
{
"code": null,
"e": 26372,
"s": 26294,
"text": "SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS \n GROUP BY NAME;"
},
{
"code": null,
"e": 26425,
"s": 26372,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 26600,
"s": 26425,
"text": "NAME sum of salary \nChaitali 6500.00 \nHardik 8500.00 \nkaushik 2000.00 \nKhilan 1500.00 \nKomal 4500.00 \nMuffy 10000.00 \nRamesh 2000.00\n"
},
{
"code": null,
"e": 26701,
"s": 26600,
"text": "Let us now consider the following CUSTOMERS table having the following records with duplicate names."
},
{
"code": null,
"e": 27118,
"s": 26701,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 27221,
"s": 27118,
"text": "If we want to know the total amount of salary on each customer, then following will be GROUP BY query."
},
{
"code": null,
"e": 27299,
"s": 27221,
"text": "SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS \n GROUP BY NAME "
},
{
"code": null,
"e": 27352,
"s": 27299,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 27486,
"s": 27352,
"text": "NAME sum of salary \nHardik 8500.00 \nkaushik 8500.00 \nKomal 4500.00 \nMuffy 10000.00 \nRamesh 3500.00 \n"
},
{
"code": null,
"e": 27639,
"s": 27486,
"text": "The MS SQL Server DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records."
},
{
"code": null,
"e": 27834,
"s": 27639,
"text": "There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records."
},
{
"code": null,
"e": 27916,
"s": 27834,
"text": "Following is the basic syntax of DISTINCT keyword to eliminate duplicate records."
},
{
"code": null,
"e": 28001,
"s": 27916,
"text": "SELECT DISTINCT column1, column2,.....columnN \nFROM table_name \nWHERE [condition] \n"
},
{
"code": null,
"e": 28060,
"s": 28001,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 28485,
"s": 28060,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 28561,
"s": 28485,
"text": "Let us see how the following SELECT query returns duplicate salary records."
},
{
"code": null,
"e": 28611,
"s": 28561,
"text": "SELECT SALARY FROM CUSTOMERS \n ORDER BY SALARY "
},
{
"code": null,
"e": 28746,
"s": 28611,
"text": "The above command will produce the following output where salary 2000 comes twice which is a duplicate record from the original table."
},
{
"code": null,
"e": 28818,
"s": 28746,
"text": "SALARY \n1500.00 \n2000.00 \n2000.00 \n4500.00 \n6500.00 \n8500.00 \n10000.00\n"
},
{
"code": null,
"e": 28898,
"s": 28818,
"text": "Let us now use DISTINCT keyword with the above SELECT query and see the result."
},
{
"code": null,
"e": 28957,
"s": 28898,
"text": "SELECT DISTINCT SALARY FROM CUSTOMERS \n ORDER BY SALARY "
},
{
"code": null,
"e": 29047,
"s": 28957,
"text": "The above command produces the following output where we do not have any duplicate entry."
},
{
"code": null,
"e": 29111,
"s": 29047,
"text": "SALARY \n1500.00 \n2000.00 \n4500.00 \n6500.00 \n8500.00 \n10000.00 \n"
},
{
"code": null,
"e": 29295,
"s": 29111,
"text": "The MS SQL Server Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each."
},
{
"code": null,
"e": 29366,
"s": 29295,
"text": "Consider the following two tables, (a) CUSTOMERS table is as follows −"
},
{
"code": null,
"e": 29799,
"s": 29366,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 29840,
"s": 29799,
"text": "(b) Another table is ORDERS as follows −"
},
{
"code": null,
"e": 30140,
"s": 29840,
"text": "OID DATE CUSTOMER_ID AMOUNT \n100 2009-10-08 00:00:00.000 3 1500.00 \n101 2009-11-20 00:00:00.000 2 1560.00 \n102 2009-10-08 00:00:00.000 3 3000.00 \n103 2008-05-20 00:00:00.000 4 2060.00 \n"
},
{
"code": null,
"e": 30206,
"s": 30140,
"text": "Let us join these two tables in our SELECT statement as follows −"
},
{
"code": null,
"e": 30416,
"s": 30206,
"text": "SELECT ID, NAME, AGE, AMOUNT \n FROM CUSTOMERS, ORDERS \n WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID \nOR \nSELECT A.ID, A.NAME, A.AGE, B.AMOUNT \n FROM CUSTOMERS A inner join ORDERS B on A.ID = B.Customer_ID "
},
{
"code": null,
"e": 30469,
"s": 30416,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 30624,
"s": 30469,
"text": "ID NAME AGE AMOUNT \n2 Khilan 25 1560.00 \n3 kaushik 23 1500.00 \n3 kaushik 23 3000.00 \n4 Chaitali 25 2060.00 \n"
},
{
"code": null,
"e": 30884,
"s": 30624,
"text": "It is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol."
},
{
"code": null,
"e": 30911,
"s": 30884,
"text": "MS SQL Server Join Types −"
},
{
"code": null,
"e": 30975,
"s": 30911,
"text": "There are different types of joins available in MS SQL Server −"
},
{
"code": null,
"e": 31039,
"s": 30975,
"text": "INNER JOIN − Returns rows when there is a match in both tables."
},
{
"code": null,
"e": 31103,
"s": 31039,
"text": "INNER JOIN − Returns rows when there is a match in both tables."
},
{
"code": null,
"e": 31202,
"s": 31103,
"text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table."
},
{
"code": null,
"e": 31301,
"s": 31202,
"text": "LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table."
},
{
"code": null,
"e": 31401,
"s": 31301,
"text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table."
},
{
"code": null,
"e": 31501,
"s": 31401,
"text": "RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table."
},
{
"code": null,
"e": 31570,
"s": 31501,
"text": "FULL JOIN − Returns rows when there is a match in one of the tables."
},
{
"code": null,
"e": 31639,
"s": 31570,
"text": "FULL JOIN − Returns rows when there is a match in one of the tables."
},
{
"code": null,
"e": 31795,
"s": 31639,
"text": "SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement."
},
{
"code": null,
"e": 31951,
"s": 31795,
"text": "SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement."
},
{
"code": null,
"e": 32057,
"s": 31951,
"text": "CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables."
},
{
"code": null,
"e": 32163,
"s": 32057,
"text": "CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables."
},
{
"code": null,
"e": 32419,
"s": 32163,
"text": "A sub-query or Inner query or Nested query is a query within another SQL Server query and embedded within the WHERE clause. A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved."
},
{
"code": null,
"e": 32563,
"s": 32419,
"text": "Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc."
},
{
"code": null,
"e": 32616,
"s": 32563,
"text": "There are a few rules that sub queries must follow −"
},
{
"code": null,
"e": 32660,
"s": 32616,
"text": "You must enclose a subquery in parenthesis."
},
{
"code": null,
"e": 32704,
"s": 32660,
"text": "You must enclose a subquery in parenthesis."
},
{
"code": null,
"e": 32763,
"s": 32704,
"text": "A subquery must include a SELECT clause and a FROM clause."
},
{
"code": null,
"e": 32822,
"s": 32763,
"text": "A subquery must include a SELECT clause and a FROM clause."
},
{
"code": null,
"e": 32891,
"s": 32822,
"text": "A subquery can include optional WHERE, GROUP BY, and HAVING clauses."
},
{
"code": null,
"e": 32960,
"s": 32891,
"text": "A subquery can include optional WHERE, GROUP BY, and HAVING clauses."
},
{
"code": null,
"e": 33017,
"s": 32960,
"text": "A subquery cannot include COMPUTE or FOR BROWSE clauses."
},
{
"code": null,
"e": 33074,
"s": 33017,
"text": "A subquery cannot include COMPUTE or FOR BROWSE clauses."
},
{
"code": null,
"e": 33145,
"s": 33074,
"text": "You can include an ORDER BY clause only when a TOP clause is included."
},
{
"code": null,
"e": 33216,
"s": 33145,
"text": "You can include an ORDER BY clause only when a TOP clause is included."
},
{
"code": null,
"e": 33258,
"s": 33216,
"text": "You can nest sub queries up to 32 levels."
},
{
"code": null,
"e": 33300,
"s": 33258,
"text": "You can nest sub queries up to 32 levels."
},
{
"code": null,
"e": 33394,
"s": 33300,
"text": "Subqueries are most frequently used with the SELECT statement. Following is the basic syntax."
},
{
"code": null,
"e": 33570,
"s": 33394,
"text": "SELECT column_name [, column_name ] \nFROM table1 [, table2 ] \nWHERE column_name OPERATOR \n (SELECT column_name [, column_name ] \n FROM table1 [, table2 ] \n [WHERE]) \n"
},
{
"code": null,
"e": 33629,
"s": 33570,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 34054,
"s": 33629,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 34113,
"s": 34054,
"text": "Let us apply the following subquery with SELECT statement."
},
{
"code": null,
"e": 34204,
"s": 34113,
"text": "SELECT * \n FROM CUSTOMERS\n WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500)"
},
{
"code": null,
"e": 34257,
"s": 34204,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 34462,
"s": 34257,
"text": "ID NAME AGE ADDRESS SALARY \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 34711,
"s": 34462,
"text": "Sub queries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions."
},
{
"code": null,
"e": 34742,
"s": 34711,
"text": "Following is the basic syntax."
},
{
"code": null,
"e": 34886,
"s": 34742,
"text": "INSERT INTO table_name [ (column1 [, column2 ]) ] \n SELECT [ *|column1 [, column2 ] \n FROM table1 [, table2 ] \n [ WHERE VALUE OPERATOR ]\n"
},
{
"code": null,
"e": 35037,
"s": 34886,
"text": "Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Following is the syntax to copy complete CUSTOMERS table into CUSTOMERS_BKP."
},
{
"code": null,
"e": 35135,
"s": 35037,
"text": "INSERT INTO CUSTOMERS_BKP \n SELECT * FROM CUSTOMERS \n WHERE ID IN (SELECT ID FROM CUSTOMERS)"
},
{
"code": null,
"e": 35311,
"s": 35135,
"text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement."
},
{
"code": null,
"e": 35342,
"s": 35311,
"text": "Following is the basic syntax."
},
{
"code": null,
"e": 35474,
"s": 35342,
"text": "UPDATE table \nSET column_name = new_value \n[ WHERE OPERATOR [ VALUE ] \n (SELECT COLUMN_NAME \n FROM TABLE_NAME) \n [ WHERE) ] \n"
},
{
"code": null,
"e": 35562,
"s": 35474,
"text": "Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table."
},
{
"code": null,
"e": 35700,
"s": 35562,
"text": "Following command example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 35814,
"s": 35700,
"text": "UPDATE CUSTOMERS \n SET SALARY = SALARY * 0.25 \n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 )"
},
{
"code": null,
"e": 35901,
"s": 35814,
"text": "This will impact two rows and finally CUSTOMERS table will have the following records."
},
{
"code": null,
"e": 36333,
"s": 35901,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 500.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 2125.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 36447,
"s": 36333,
"text": "The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above."
},
{
"code": null,
"e": 36478,
"s": 36447,
"text": "Following is the basic syntax."
},
{
"code": null,
"e": 36591,
"s": 36478,
"text": "DELETE FROM TABLE_NAME \n[ WHERE OPERATOR [ VALUE ] \n (SELECT COLUMN_NAME \n FROM TABLE_NAME) \n [ WHERE) ] \n"
},
{
"code": null,
"e": 36679,
"s": 36591,
"text": "Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table."
},
{
"code": null,
"e": 36806,
"s": 36679,
"text": "Following command example deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27."
},
{
"code": null,
"e": 36893,
"s": 36806,
"text": "DELETE FROM CUSTOMERS \n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 )"
},
{
"code": null,
"e": 36981,
"s": 36893,
"text": "This would impact two rows and finally CUSTOMERS table will have the following records."
},
{
"code": null,
"e": 37289,
"s": 36981,
"text": "ID NAME AGE ADDRESS SALARY \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 37463,
"s": 37289,
"text": "The MS SQL Server Stored procedure is used to save time to write code again and again by storing the same in database and also get the required output by passing parameters."
},
{
"code": null,
"e": 37523,
"s": 37463,
"text": "Following is the basic syntax of Stored procedure creation."
},
{
"code": null,
"e": 37595,
"s": 37523,
"text": "Create procedure <procedure_Name> \nAs \nBegin \n<SQL Statement> \nEnd \nGo\n"
},
{
"code": null,
"e": 37654,
"s": 37595,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 38079,
"s": 37654,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 38186,
"s": 38079,
"text": "Following command is an example which would fetch all records from the CUSTOMERS table in Testdb database."
},
{
"code": null,
"e": 38268,
"s": 38186,
"text": "CREATE PROCEDURE SelectCustomerstabledata \nAS \nSELECT * FROM Testdb.Customers \nGO"
},
{
"code": null,
"e": 38321,
"s": 38268,
"text": "The above command will produce the following output."
},
{
"code": null,
"e": 38738,
"s": 38321,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 38976,
"s": 38738,
"text": "A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program."
},
{
"code": null,
"e": 39297,
"s": 38976,
"text": "A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors."
},
{
"code": null,
"e": 39424,
"s": 39297,
"text": "Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction."
},
{
"code": null,
"e": 39524,
"s": 39424,
"text": "Transactions have the following four standard properties, usually referred to by the acronym ACID −"
},
{
"code": null,
"e": 39739,
"s": 39524,
"text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state."
},
{
"code": null,
"e": 39954,
"s": 39739,
"text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state."
},
{
"code": null,
"e": 40060,
"s": 39954,
"text": "Consistency − Ensures that the database properly changes state upon a successfully committed transaction."
},
{
"code": null,
"e": 40166,
"s": 40060,
"text": "Consistency − Ensures that the database properly changes state upon a successfully committed transaction."
},
{
"code": null,
"e": 40258,
"s": 40166,
"text": "Isolation − Enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 40350,
"s": 40258,
"text": "Isolation − Enables transactions to operate independently of and transparent to each other."
},
{
"code": null,
"e": 40462,
"s": 40350,
"text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 40574,
"s": 40462,
"text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure."
},
{
"code": null,
"e": 40634,
"s": 40574,
"text": "There are following commands used to control transactions −"
},
{
"code": null,
"e": 40664,
"s": 40634,
"text": "COMMIT − To save the changes."
},
{
"code": null,
"e": 40694,
"s": 40664,
"text": "COMMIT − To save the changes."
},
{
"code": null,
"e": 40731,
"s": 40694,
"text": "ROLLBACK − To roll back the changes."
},
{
"code": null,
"e": 40768,
"s": 40731,
"text": "ROLLBACK − To roll back the changes."
},
{
"code": null,
"e": 40847,
"s": 40768,
"text": "SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK."
},
{
"code": null,
"e": 40926,
"s": 40847,
"text": "SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK."
},
{
"code": null,
"e": 40976,
"s": 40926,
"text": "SET TRANSACTION − Places a name on a transaction."
},
{
"code": null,
"e": 41026,
"s": 40976,
"text": "SET TRANSACTION − Places a name on a transaction."
},
{
"code": null,
"e": 41254,
"s": 41026,
"text": "Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database."
},
{
"code": null,
"e": 41435,
"s": 41254,
"text": "In order to use transactional control commands in MS SQL Server, we have to begin transaction with ‘begin tran’ or begin transaction command otherwise these commands will not work."
},
{
"code": null,
"e": 41641,
"s": 41435,
"text": "The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. This command saves all transactions to the database since the last COMMIT or ROLLBACK command."
},
{
"code": null,
"e": 41685,
"s": 41641,
"text": "Following is the syntax for COMMIT command."
},
{
"code": null,
"e": 41695,
"s": 41685,
"text": "COMMIT; \n"
},
{
"code": null,
"e": 41754,
"s": 41695,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 42171,
"s": 41754,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 42293,
"s": 42171,
"text": "Following command example will delete records from the table having age = 25 and then COMMIT the changes in the database."
},
{
"code": null,
"e": 42355,
"s": 42293,
"text": "Begin Tran \nDELETE FROM CUSTOMERS \n WHERE AGE = 25 \nCOMMIT "
},
{
"code": null,
"e": 42465,
"s": 42355,
"text": "As a result, two rows from the table would be deleted and SELECT statement will produce the following output."
},
{
"code": null,
"e": 42776,
"s": 42465,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00\n3 kaushik 23 Kota 2000.00\n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 43007,
"s": 42776,
"text": "The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued."
},
{
"code": null,
"e": 43053,
"s": 43007,
"text": "Following is the syntax for ROLLBACK command."
},
{
"code": null,
"e": 43063,
"s": 43053,
"text": "ROLLBACK\n"
},
{
"code": null,
"e": 43122,
"s": 43063,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 43547,
"s": 43122,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 43671,
"s": 43547,
"text": "Following command example will delete records from the table having age = 25 and then ROLLBACK the changes in the database."
},
{
"code": null,
"e": 43735,
"s": 43671,
"text": "Begin Tran \nDELETE FROM CUSTOMERS \n WHERE AGE = 25; \nROLLBACK"
},
{
"code": null,
"e": 43847,
"s": 43735,
"text": "As a result, delete operation will not impact the table and SELECT statement will produce the following result."
},
{
"code": null,
"e": 44256,
"s": 43847,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 44397,
"s": 44256,
"text": "SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction."
},
{
"code": null,
"e": 44444,
"s": 44397,
"text": "Following is the syntax for SAVEPOINT command."
},
{
"code": null,
"e": 44477,
"s": 44444,
"text": "SAVE TRANSACTION SAVEPOINT_NAME\n"
},
{
"code": null,
"e": 44627,
"s": 44477,
"text": "This command serves only in the creation of a SAVEPOINT among transactional statements. The ROLLBACK command is used to undo a group of transactions."
},
{
"code": null,
"e": 44684,
"s": 44627,
"text": "Following is the syntax for rolling back to a SAVEPOINT."
},
{
"code": null,
"e": 44712,
"s": 44684,
"text": "ROLLBACK TO SAVEPOINT_NAME\n"
},
{
"code": null,
"e": 44965,
"s": 44712,
"text": "In the following example, we will delete three different records from the CUSTOMERS table. We will have to create a SAVEPOINT before each delete, so that we can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state."
},
{
"code": null,
"e": 45025,
"s": 44965,
"text": "Consider the CUSTOMERS table having the following records −"
},
{
"code": null,
"e": 45434,
"s": 45025,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 45475,
"s": 45434,
"text": "Following are the series of operations −"
},
{
"code": null,
"e": 45769,
"s": 45475,
"text": "Begin Tran \nSAVE Transaction SP1 \nSavepoint created. \nDELETE FROM CUSTOMERS WHERE ID = 1 \n1 row deleted. \nSAVE Transaction SP2 \nSavepoint created. \nDELETE FROM CUSTOMERS WHERE ID = 2 \n1 row deleted.\nSAVE Transaction SP3 \nSavepoint created. \nDELETE FROM CUSTOMERS WHERE ID = 3 \n1 row deleted.\n"
},
{
"code": null,
"e": 45994,
"s": 45769,
"text": "The three deletions have taken place, however, we have changed our mind and decide to ROLLBACK to the SAVEPOINT that we identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −"
},
{
"code": null,
"e": 46041,
"s": 45994,
"text": "ROLLBACK Transaction SP2 \nRollback complete. \n"
},
{
"code": null,
"e": 46117,
"s": 46041,
"text": "Notice that only the first deletion took place since we rolled back to SP2."
},
{
"code": null,
"e": 46143,
"s": 46117,
"text": "SELECT * FROM CUSTOMERS \n"
},
{
"code": null,
"e": 46160,
"s": 46143,
"text": "6 rows selected."
},
{
"code": null,
"e": 46514,
"s": 46160,
"text": "ID NAME AGE ADDRESS SALARY \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 46668,
"s": 46514,
"text": "SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows."
},
{
"code": null,
"e": 46713,
"s": 46668,
"text": "Following is the syntax for SET TRANSACTION."
},
{
"code": null,
"e": 46768,
"s": 46713,
"text": "SET TRANSACTION ISOLATION LEVEL <Isolationlevel_name>\n"
},
{
"code": null,
"e": 46997,
"s": 46768,
"text": "Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index at the end of a book."
},
{
"code": null,
"e": 47217,
"s": 46997,
"text": "For example, if you want to reference all the pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers."
},
{
"code": null,
"e": 47402,
"s": 47217,
"text": "An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data."
},
{
"code": null,
"e": 47623,
"s": 47402,
"text": "Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in ascending or descending order."
},
{
"code": null,
"e": 47797,
"s": 47623,
"text": "Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there's an index."
},
{
"code": null,
"e": 47844,
"s": 47797,
"text": "Following is the basic syntax of CREATE INDEX."
},
{
"code": null,
"e": 47883,
"s": 47844,
"text": "CREATE INDEX index_name ON table_name\n"
},
{
"code": null,
"e": 47991,
"s": 47883,
"text": "A single-column index is one that is created based on only one table column. Following is the basic syntax."
},
{
"code": null,
"e": 48045,
"s": 47991,
"text": "CREATE INDEX index_name \nON table_name (column_name)\n"
},
{
"code": null,
"e": 48095,
"s": 48045,
"text": "CREATE INDEX singlecolumnindex \nON customers (ID)"
},
{
"code": null,
"e": 48287,
"s": 48095,
"text": "Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. Following is the basic syntax."
},
{
"code": null,
"e": 48348,
"s": 48287,
"text": "CREATE UNIQUE INDEX index_name \non table_name (column_name)\n"
},
{
"code": null,
"e": 48401,
"s": 48348,
"text": "CREATE UNIQUE INDEX uniqueindex \non customers (NAME)"
},
{
"code": null,
"e": 48497,
"s": 48401,
"text": "A composite index is an index on two or more columns of a table. Following is the basic syntax."
},
{
"code": null,
"e": 48556,
"s": 48497,
"text": "CREATE INDEX index_name on table_name (column1, column2) \n"
},
{
"code": null,
"e": 48609,
"s": 48556,
"text": "CREATE INDEX compositeindex \non customers (NAME, ID)"
},
{
"code": null,
"e": 48790,
"s": 48609,
"text": "Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query's WHERE clause as filter conditions."
},
{
"code": null,
"e": 49011,
"s": 48790,
"text": "Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice."
},
{
"code": null,
"e": 49207,
"s": 49011,
"text": "Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints."
},
{
"code": null,
"e": 49356,
"s": 49207,
"text": "An index can be dropped using MS SQL SERVER DROP command. Care should be taken when dropping an index because performance may be slowed or improved."
},
{
"code": null,
"e": 49387,
"s": 49356,
"text": "Following is the basic syntax."
},
{
"code": null,
"e": 49420,
"s": 49387,
"text": "DROP INDEX tablename.index_name\n"
},
{
"code": null,
"e": 49620,
"s": 49420,
"text": "Although indexes are intended to enhance the performance of databases, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered −"
},
{
"code": null,
"e": 49664,
"s": 49620,
"text": "Indexes should not be used on small tables."
},
{
"code": null,
"e": 49708,
"s": 49664,
"text": "Indexes should not be used on small tables."
},
{
"code": null,
"e": 49798,
"s": 49708,
"text": "Tables that have frequent, large batch update or insert operations should not be indexed."
},
{
"code": null,
"e": 49888,
"s": 49798,
"text": "Tables that have frequent, large batch update or insert operations should not be indexed."
},
{
"code": null,
"e": 49969,
"s": 49888,
"text": "Indexes should not be used on columns that contain a high number of NULL values."
},
{
"code": null,
"e": 50050,
"s": 49969,
"text": "Indexes should not be used on columns that contain a high number of NULL values."
},
{
"code": null,
"e": 50113,
"s": 50050,
"text": "Columns that are frequently manipulated should not be indexed."
},
{
"code": null,
"e": 50176,
"s": 50113,
"text": "Columns that are frequently manipulated should not be indexed."
},
{
"code": null,
"e": 50328,
"s": 50176,
"text": "MS SQL Server has many built-in functions to perform processing on string or numeric data. Following is the list of all useful SQL built-in functions −"
},
{
"code": null,
"e": 50453,
"s": 50328,
"text": "SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table."
},
{
"code": null,
"e": 50578,
"s": 50453,
"text": "SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table."
},
{
"code": null,
"e": 50709,
"s": 50578,
"text": "SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column."
},
{
"code": null,
"e": 50840,
"s": 50709,
"text": "SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column."
},
{
"code": null,
"e": 50970,
"s": 50840,
"text": "SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column."
},
{
"code": null,
"e": 51100,
"s": 50970,
"text": "SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column."
},
{
"code": null,
"e": 51216,
"s": 51100,
"text": "SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column."
},
{
"code": null,
"e": 51332,
"s": 51216,
"text": "SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column."
},
{
"code": null,
"e": 51445,
"s": 51332,
"text": "SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column."
},
{
"code": null,
"e": 51558,
"s": 51445,
"text": "SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column."
},
{
"code": null,
"e": 51643,
"s": 51558,
"text": "SQL Server SQRT Function − This is used to generate a square root of a given number."
},
{
"code": null,
"e": 51728,
"s": 51643,
"text": "SQL Server SQRT Function − This is used to generate a square root of a given number."
},
{
"code": null,
"e": 51815,
"s": 51728,
"text": "SQL Server RAND Function − This is used to generate a random number using SQL command."
},
{
"code": null,
"e": 51902,
"s": 51815,
"text": "SQL Server RAND Function − This is used to generate a random number using SQL command."
},
{
"code": null,
"e": 52002,
"s": 51902,
"text": "SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter."
},
{
"code": null,
"e": 52102,
"s": 52002,
"text": "SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter."
},
{
"code": null,
"e": 52203,
"s": 52102,
"text": "SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL."
},
{
"code": null,
"e": 52304,
"s": 52203,
"text": "SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL."
},
{
"code": null,
"e": 52404,
"s": 52304,
"text": "SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL."
},
{
"code": null,
"e": 52504,
"s": 52404,
"text": "SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL."
},
{
"code": null,
"e": 52611,
"s": 52504,
"text": "MS SQL Server String functions can be applied on string value or will return string value or numeric data."
},
{
"code": null,
"e": 52668,
"s": 52611,
"text": "Following is the list of String functions with examples."
},
{
"code": null,
"e": 52733,
"s": 52668,
"text": "Ascii code value will come as output for a character expression."
},
{
"code": null,
"e": 52806,
"s": 52733,
"text": "The following query will give the Ascii code value of a given character."
},
{
"code": null,
"e": 52830,
"s": 52806,
"text": "Select ASCII ('word') \n"
},
{
"code": null,
"e": 52893,
"s": 52830,
"text": "Character will come as output for given Ascii code or integer."
},
{
"code": null,
"e": 52958,
"s": 52893,
"text": "The following query will give the character for a given integer."
},
{
"code": null,
"e": 52975,
"s": 52958,
"text": "Select CHAR(97)\n"
},
{
"code": null,
"e": 53034,
"s": 52975,
"text": "Unicode character will come as output for a given integer."
},
{
"code": null,
"e": 53107,
"s": 53034,
"text": "The following query will give the Unicode character for a given integer."
},
{
"code": null,
"e": 53126,
"s": 53107,
"text": "Select NCHAR(300)\n"
},
{
"code": null,
"e": 53222,
"s": 53126,
"text": "Starting position for given search expression will come as output in a given string expression."
},
{
"code": null,
"e": 53327,
"s": 53222,
"text": "The following query will give the starting position of 'G' character for given string expression 'KING'."
},
{
"code": null,
"e": 53358,
"s": 53327,
"text": "Select CHARINDEX('G', 'KING')\n"
},
{
"code": null,
"e": 53468,
"s": 53358,
"text": "Left part of the given string till the specified number of characters will come as output for a given string."
},
{
"code": null,
"e": 53578,
"s": 53468,
"text": "The following query will give the 'WORL' string as mentioned 4 number of characters for given string 'WORLD'."
},
{
"code": null,
"e": 53603,
"s": 53578,
"text": "Select LEFT('WORLD', 4)\n"
},
{
"code": null,
"e": 53714,
"s": 53603,
"text": "Right part of the given string till the specified number of characters will come as output for a given string."
},
{
"code": null,
"e": 53823,
"s": 53714,
"text": "The following query will give the 'DIA' string as mentioned 3 number of characters for given string 'INDIA'."
},
{
"code": null,
"e": 53849,
"s": 53823,
"text": "Select RIGHT('INDIA', 3)\n"
},
{
"code": null,
"e": 53957,
"s": 53849,
"text": "Part of a string based on the start position value and length value will come as output for a given string."
},
{
"code": null,
"e": 54147,
"s": 53957,
"text": "The following queries will give the 'WOR', 'DIA', 'ING' strings as we mentioned (1,3), (3,3) and (2,3) as start and length values respectively for given strings 'WORLD', 'INDIA' and 'KING'."
},
{
"code": null,
"e": 54245,
"s": 54147,
"text": "Select SUBSTRING ('WORLD', 1,3) \nSelect SUBSTRING ('INDIA', 3,3) \nSelect SUBSTRING ('KING', 2,3)\n"
},
{
"code": null,
"e": 54317,
"s": 54245,
"text": "Number of characters will come as output for a given string expression."
},
{
"code": null,
"e": 54388,
"s": 54317,
"text": "The following query will give the 5 for the 'HELLO' string expression."
},
{
"code": null,
"e": 54410,
"s": 54388,
"text": "Select LEN('HELLO') \n"
},
{
"code": null,
"e": 54472,
"s": 54410,
"text": "Lowercase string will come as output for a given string data."
},
{
"code": null,
"e": 54554,
"s": 54472,
"text": "The following query will give the 'sqlserver' for the 'SQLServer' character data."
},
{
"code": null,
"e": 54582,
"s": 54554,
"text": "Select LOWER('SQLServer') \n"
},
{
"code": null,
"e": 54644,
"s": 54582,
"text": "Uppercase string will come as output for a given string data."
},
{
"code": null,
"e": 54726,
"s": 54644,
"text": "The following query will give the 'SQLSERVER' for the 'SqlServer' character data."
},
{
"code": null,
"e": 54753,
"s": 54726,
"text": "Select UPPER('SqlServer')\n"
},
{
"code": null,
"e": 54846,
"s": 54753,
"text": "String expression will come as output for a given string data after removing leading blanks."
},
{
"code": null,
"e": 54923,
"s": 54846,
"text": "The following query will give the 'WORLD' for the ' WORLD' character data."
},
{
"code": null,
"e": 54949,
"s": 54923,
"text": "Select LTRIM(' WORLD')\n"
},
{
"code": null,
"e": 55043,
"s": 54949,
"text": "String expression will come as output for a given string data after removing trailing blanks."
},
{
"code": null,
"e": 55120,
"s": 55043,
"text": "The following query will give the 'INDIA' for the 'INDIA ' character data."
},
{
"code": null,
"e": 55147,
"s": 55120,
"text": "Select RTRIM('INDIA ') \n"
},
{
"code": null,
"e": 55290,
"s": 55147,
"text": "String expression will come as output for a given string data after replacing all occurrences of specified character with specified character."
},
{
"code": null,
"e": 55368,
"s": 55290,
"text": "The following query will give the 'KNDKA' string for the 'INDIA' string data."
},
{
"code": null,
"e": 55403,
"s": 55368,
"text": "Select REPLACE('INDIA', 'I', 'K')\n"
},
{
"code": null,
"e": 55504,
"s": 55403,
"text": "Repeat string expression will come as output for a given string data with specified number of times."
},
{
"code": null,
"e": 55587,
"s": 55504,
"text": "The following query will give the 'WORLDWORLD' string for the 'WORLD' string data."
},
{
"code": null,
"e": 55617,
"s": 55587,
"text": "Select REPLICATE('WORLD', 2)\n"
},
{
"code": null,
"e": 55688,
"s": 55617,
"text": "Reverse string expression will come as output for a given string data."
},
{
"code": null,
"e": 55766,
"s": 55688,
"text": "The following query will give the 'DLROW' string for the 'WORLD' string data."
},
{
"code": null,
"e": 55791,
"s": 55766,
"text": "Select REVERSE('WORLD')\n"
},
{
"code": null,
"e": 55878,
"s": 55791,
"text": "Returns four-character (SOUNDEX) code to evaluate the similarity of two given strings."
},
{
"code": null,
"e": 55953,
"s": 55878,
"text": "The following query will give the 'S530' for the 'Smith', 'Smyth' strings."
},
{
"code": null,
"e": 55996,
"s": 55953,
"text": "Select SOUNDEX('Smith'), SOUNDEX('Smyth')\n"
},
{
"code": null,
"e": 56056,
"s": 55996,
"text": "Integer value will come as output of given two expressions."
},
{
"code": null,
"e": 56130,
"s": 56056,
"text": "The following query will give the 4 for the 'Smith', 'Smyth' expressions."
},
{
"code": null,
"e": 56167,
"s": 56130,
"text": "Select Difference('Smith','Smyth') \n"
},
{
"code": null,
"e": 56262,
"s": 56167,
"text": "Note − If the output value is 0 it indicates weak or no similarity between give 2 expressions."
},
{
"code": null,
"e": 56326,
"s": 56262,
"text": "String will come as output with the specified number of spaces."
},
{
"code": null,
"e": 56376,
"s": 56326,
"text": "The following query will give the 'I LOVE INDIA'."
},
{
"code": null,
"e": 56421,
"s": 56376,
"text": "Select 'I'+space(1)+'LOVE'+space(1)+'INDIA'\n"
},
{
"code": null,
"e": 56575,
"s": 56421,
"text": "String expression will come as output for a given string data after replacing from starting character till the specified length with specified character."
},
{
"code": null,
"e": 56762,
"s": 56575,
"text": "The following query will give the 'AIJKFGH' string for the 'ABCDEFGH' string data as per given starting character and length as 2 and 4 respectively and 'IJK' as specified target string."
},
{
"code": null,
"e": 56800,
"s": 56762,
"text": "Select STUFF('ABCDEFGH', 2,4,'IJK') \n"
},
{
"code": null,
"e": 56863,
"s": 56800,
"text": "Character data will come as output for the given numeric data."
},
{
"code": null,
"e": 56975,
"s": 56863,
"text": "The following query will give the 187.37 for the given 187.369 based on specified length as 6 and decimal as 2."
},
{
"code": null,
"e": 57001,
"s": 56975,
"text": "Select STR(187.369,6,2) \n"
},
{
"code": null,
"e": 57080,
"s": 57001,
"text": "Integer value will come as output for the first character of given expression."
},
{
"code": null,
"e": 57144,
"s": 57080,
"text": "The following query will give the 82 for the 'RAMA' expression."
},
{
"code": null,
"e": 57169,
"s": 57144,
"text": "Select UNICODE('RAMA') \n"
},
{
"code": null,
"e": 57232,
"s": 57169,
"text": "Given string will come as output with the specified delimiter."
},
{
"code": null,
"e": 57344,
"s": 57232,
"text": "The following query will give the \"RAMA\" for the given 'RAMA' string as we specified double quote as delimiter."
},
{
"code": null,
"e": 57375,
"s": 57344,
"text": "Select QUOTENAME('RAMA','\"') \n"
},
{
"code": null,
"e": 57485,
"s": 57375,
"text": "Starting position of the first occurrence from the given expression as we specified 'I' position is required."
},
{
"code": null,
"e": 57538,
"s": 57485,
"text": "The following query will give the 1 for the 'INDIA'."
},
{
"code": null,
"e": 57570,
"s": 57538,
"text": "Select PATINDEX('I%','INDIA') \n"
},
{
"code": null,
"e": 57634,
"s": 57570,
"text": "Given expression will come as output with the specified format."
},
{
"code": null,
"e": 57776,
"s": 57634,
"text": "The following query will give the ' Monday, November 16, 2015' for the getdate function as per specified format with 'D' refers weekday name."
},
{
"code": null,
"e": 57810,
"s": 57776,
"text": "SELECT FORMAT ( getdate(), 'D') \n"
},
{
"code": null,
"e": 57892,
"s": 57810,
"text": "Single string will come as output after concatenating the given parameter values."
},
{
"code": null,
"e": 57960,
"s": 57892,
"text": "The following query will give the 'A,B,C' for the given parameters."
},
{
"code": null,
"e": 57997,
"s": 57960,
"text": "Select CONCAT('A',',','B',',','C') \n"
},
{
"code": null,
"e": 58055,
"s": 57997,
"text": "Following is the list of date functions in MS SQL Server."
},
{
"code": null,
"e": 58104,
"s": 58055,
"text": "It will return the current date along with time."
},
{
"code": null,
"e": 58136,
"s": 58104,
"text": "Syntax for the above function −"
},
{
"code": null,
"e": 58147,
"s": 58136,
"text": "GETDATE()\n"
},
{
"code": null,
"e": 58230,
"s": 58147,
"text": "The following query will return the current date along with time in MS SQL Server."
},
{
"code": null,
"e": 58266,
"s": 58230,
"text": "Select getdate() as currentdatetime"
},
{
"code": null,
"e": 58307,
"s": 58266,
"text": "It will return the part of date or time."
},
{
"code": null,
"e": 58339,
"s": 58307,
"text": "Syntax for the above function −"
},
{
"code": null,
"e": 58375,
"s": 58339,
"text": "DATEPART(datepart, datecolumnname)\n"
},
{
"code": null,
"e": 58462,
"s": 58375,
"text": "Example 1 − The following query will return the part of current date in MS SQL Server."
},
{
"code": null,
"e": 58509,
"s": 58462,
"text": "Select datepart(day, getdate()) as currentdate"
},
{
"code": null,
"e": 58597,
"s": 58509,
"text": "Example 2 − The following query will return the part of current month in MS SQL Server."
},
{
"code": null,
"e": 58647,
"s": 58597,
"text": "Select datepart(month, getdate()) as currentmonth"
},
{
"code": null,
"e": 58724,
"s": 58647,
"text": "It will display the date and time by add or subtract date and time interval."
},
{
"code": null,
"e": 58756,
"s": 58724,
"text": "Syntax for the above function −"
},
{
"code": null,
"e": 58799,
"s": 58756,
"text": "DATEADD(datepart, number, datecolumnname)\n"
},
{
"code": null,
"e": 58912,
"s": 58799,
"text": "The following query will return the after 10 days date and time from the current date and time in MS SQL Server."
},
{
"code": null,
"e": 58990,
"s": 58912,
"text": "Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime "
},
{
"code": null,
"e": 59043,
"s": 58990,
"text": "It will display the date and time between two dates."
},
{
"code": null,
"e": 59075,
"s": 59043,
"text": "Syntax for the above function −"
},
{
"code": null,
"e": 59115,
"s": 59075,
"text": "DATEDIFF(datepart, startdate, enddate)\n"
},
{
"code": null,
"e": 59229,
"s": 59115,
"text": "The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server."
},
{
"code": null,
"e": 59322,
"s": 59229,
"text": "Select datediff(hour, 2015-11-16, 2015-11-11) as \ndifferencehoursbetween20151116and20151111 "
},
{
"code": null,
"e": 59378,
"s": 59322,
"text": "It will display the date and time in different formats."
},
{
"code": null,
"e": 59410,
"s": 59378,
"text": "Syntax for the above function −"
},
{
"code": null,
"e": 59448,
"s": 59410,
"text": "CONVERT(datatype, expression, style)\n"
},
{
"code": null,
"e": 59538,
"s": 59448,
"text": "The following queries will return the date and time in different format in MS SQL Server."
},
{
"code": null,
"e": 59661,
"s": 59538,
"text": "SELECT CONVERT(VARCHAR(19),GETDATE()) \nSELECT CONVERT(VARCHAR(10),GETDATE(),10) \nSELECT CONVERT(VARCHAR(10),GETDATE(),110)"
},
{
"code": null,
"e": 59754,
"s": 59661,
"text": "MS SQL Server numeric functions can be applied on numeric data and will return numeric data."
},
{
"code": null,
"e": 59812,
"s": 59754,
"text": "Following is the list of Numeric functions with examples."
},
{
"code": null,
"e": 59871,
"s": 59812,
"text": "Absolute value will come as output for numeric expression."
},
{
"code": null,
"e": 59921,
"s": 59871,
"text": "The following query will give the absolute value."
},
{
"code": null,
"e": 59939,
"s": 59921,
"text": "Select ABS(-22) \n"
},
{
"code": null,
"e": 60014,
"s": 59939,
"text": "Arc cosine value will come as output for the specified numeric expression."
},
{
"code": null,
"e": 60071,
"s": 60014,
"text": "The following query will give the arc cosine value of 0."
},
{
"code": null,
"e": 60088,
"s": 60071,
"text": "Select ACOS(0) \n"
},
{
"code": null,
"e": 60161,
"s": 60088,
"text": "Arc sine value will come as output for the specified numeric expression."
},
{
"code": null,
"e": 60216,
"s": 60161,
"text": "The following query will give the arc sine value of 0."
},
{
"code": null,
"e": 60232,
"s": 60216,
"text": "Select ASIN(0)\n"
},
{
"code": null,
"e": 60308,
"s": 60232,
"text": "Arc tangent value will come as output for the specified numeric expression."
},
{
"code": null,
"e": 60366,
"s": 60308,
"text": "The following query will give the arc tangent value of 0."
},
{
"code": null,
"e": 60383,
"s": 60366,
"text": "Select ATAN(0) \n"
},
{
"code": null,
"e": 60481,
"s": 60383,
"text": "Arc tangent value in all four quadrants will come as output for the specified numeric expression."
},
{
"code": null,
"e": 60561,
"s": 60481,
"text": "The following query will give the arc tangent value in all four quadrants of 0."
},
{
"code": null,
"e": 60582,
"s": 60561,
"text": "Select ATN2(0, -1) \n"
},
{
"code": null,
"e": 60641,
"s": 60582,
"text": "Consider the CUSTOMERS table having the following records."
},
{
"code": null,
"e": 61074,
"s": 60641,
"text": "ID NAME AGE ADDRESS SALARY \n1 Ramesh 32 Ahmedabad 2000.00 \n2 Khilan 25 Delhi 1500.00 \n3 kaushik 23 Kota 2000.00 \n4 Chaitali 25 Mumbai 6500.00 \n5 Hardik 27 Bhopal 8500.00 \n6 Komal 22 MP 4500.00 \n7 Muffy 24 Indore 10000.00 \n"
},
{
"code": null,
"e": 61159,
"s": 61074,
"text": "If the values exist between given two expressions then those will be come as output."
},
{
"code": null,
"e": 61211,
"s": 61159,
"text": "The following query will give the following output."
},
{
"code": null,
"e": 61276,
"s": 61211,
"text": "SELECT salary from customers where salary between 2000 and 8500\n"
},
{
"code": null,
"e": 61329,
"s": 61276,
"text": "salary \n2000.00 \n2000.00 \n6500.00 \n8500.00 \n4500.00\n"
},
{
"code": null,
"e": 61390,
"s": 61329,
"text": "Minimum value will come as output from the given expression."
},
{
"code": null,
"e": 61490,
"s": 61390,
"text": "The following query will give '1500.00' for the given 'salary' expression from the customers table."
},
{
"code": null,
"e": 61524,
"s": 61490,
"text": "Select MIN(salary)from CUSTOMERS\n"
},
{
"code": null,
"e": 61585,
"s": 61524,
"text": "Maximum value will come as output from the given expression."
},
{
"code": null,
"e": 61686,
"s": 61585,
"text": "The following query will give '10000.00' for the given 'salary' expression from the customers table."
},
{
"code": null,
"e": 61720,
"s": 61686,
"text": "Select MAX(salary)from CUSTOMERS\n"
},
{
"code": null,
"e": 61785,
"s": 61720,
"text": "Square root of the given numeric expression will come as output."
},
{
"code": null,
"e": 61853,
"s": 61785,
"text": "The following query will give 2 for the given 4 numeric expression."
},
{
"code": null,
"e": 61870,
"s": 61853,
"text": "Select SQRT(4) \n"
},
{
"code": null,
"e": 61900,
"s": 61870,
"text": "PI value will come as output."
},
{
"code": null,
"e": 61965,
"s": 61900,
"text": "The following query will give 3.14159265358979 for the PI value."
},
{
"code": null,
"e": 61979,
"s": 61965,
"text": "Select PI() \n"
},
{
"code": null,
"e": 62072,
"s": 61979,
"text": "Given value will come as output after rounding the decimals which is the next highest value."
},
{
"code": null,
"e": 62134,
"s": 62072,
"text": "The following query will give 124 for the given 123.25 value."
},
{
"code": null,
"e": 62159,
"s": 62134,
"text": "Select CEILING(123.25) \n"
},
{
"code": null,
"e": 62266,
"s": 62159,
"text": "Given value will come as output after rounding the decimals which is less than or equal to the expression."
},
{
"code": null,
"e": 62328,
"s": 62266,
"text": "The following query will give 123 for the given 123.25 value."
},
{
"code": null,
"e": 62351,
"s": 62328,
"text": "Select FLOOR(123.25) \n"
},
{
"code": null,
"e": 62415,
"s": 62351,
"text": "Natural logarithm of the given expression will come as output."
},
{
"code": null,
"e": 62470,
"s": 62415,
"text": "The following query will give 0 for the given 1 value."
},
{
"code": null,
"e": 62486,
"s": 62470,
"text": "Select LOG(1) \n"
},
{
"code": null,
"e": 62519,
"s": 62486,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 62534,
"s": 62519,
"text": " Nishant Malik"
},
{
"code": null,
"e": 62569,
"s": 62534,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 62584,
"s": 62569,
"text": " Nishant Malik"
},
{
"code": null,
"e": 62619,
"s": 62584,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 62634,
"s": 62619,
"text": " Nishant Malik"
},
{
"code": null,
"e": 62667,
"s": 62634,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 62681,
"s": 62667,
"text": " Asif Hussain"
},
{
"code": null,
"e": 62716,
"s": 62681,
"text": "\n 10 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 62731,
"s": 62716,
"text": " Nishant Malik"
},
{
"code": null,
"e": 62766,
"s": 62731,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 62780,
"s": 62766,
"text": " Asif Hussain"
},
{
"code": null,
"e": 62787,
"s": 62780,
"text": " Print"
},
{
"code": null,
"e": 62798,
"s": 62787,
"text": " Add Notes"
}
] |
Finding Donors: Classification Project With PySpark | by Victor Roman | Towards Data Science
|
The aim of this article is to make a gentle introduction to Classification problems in Machine Learning and go through a comprehensive guide to develop succesfully a class prediction using PySpark.
So without further a do, let’s jump into it!
If you want to a deep explanation about Classification problems, its main algorithms and how to deal with them using machine learning techniques, I strongly suggest you to chek out the following article, where I explain this concepts throughfully.
towardsdatascience.com
Classification is a subcategory of supervised learning where the goal is to predict the categorical class labels (discrete, unoredered values, group membership) of new instances based on past observations.
There are two main types of classification problems:
Binary classification: The typical example is e-mail spam detection, which each e-mail is spam → 1 spam; or isn’t → 0.
Multi-class classification: Like handwritten character recognition (where classes go from 0 to 9).
The following example is very representative to explain binary classification:
There are 2 classes, circles and crosses, and 2 features, X1 and X2. The model is able to find the relationship between the features of each data point and its class, and to set a boundary line between them, so when provided with new data, it can estimate the class where it belongs, given its features.
In this case, the new data point falls into the circle subspace and, therefore, the model will predict its class to be a circle.
In order to predict the class of certain samples, there are several classification algorithms that can be used. In fact, when developing our machine learning models, we will train and evaluate a certain number of them, and we will keep those with better predicting performance.
A non-exhaustive list of some of the most used algorithms are:
Logistic Regression
Decision Trees
Random Forests
Support Vector Machines
K-Nearest Neighbors (KNN)
When making predictions on events we can get four type of results:
True Positives: TP
True Negatives: TN
False Positives: FP
False Negatives: FN
All of these are represented in the following classification matrix:
Accuracy measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points).
Precision tells us what proportion of events we classified as a certain class, actually were that class. It is a ratio of true positives to all positives.
Recall (sensitivity) tells us what proportion of events that actually were the of a certain class were classified by us as that class. It is a ratio of true positives to all the positives.
Specifity is the proportion of classes that were correctly identified as negative upon the total of negative classes.
For classification problems that are skewed in their classification distributions , accuracy by itself is not an appropiate metric. Instead, precision and recall are much more representative.
These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios).
Finally, the metric that we will use in our project is the Reciever Operation Characteristic or ROC.
The ROC curve tells us about how good the model can distinguish between two classes. It can get values from 0 to 1 ( €[0,1] ). The better the model is, the closer to 1 value it will be.
As can be seen in the image of above, our classification model will draw a separation boundary between the classes and:
Every sample that falls at the left of the threshod, will be classified as negative class.
Every sample that falls at the right of the threshod, will be classified as positive class,
And the distribution of predictions will be the following:
Trade off Between Sensitivity & Specifity
When we decrease the threshold, we end up predicting more positive values and increasing sensitivity. Therefore, specifity decreases.
When we increase the threshold, we end up predicting more negative values and increasing specifity. Therefore, decreasing sensitivity.
As Sensitivity ⬇️ Specificity ⬆️
As Specificity ⬇️ Sensitivity ⬆️
In order to optimize the classification performance,we consider (1- specifity) instead specificity. So, when sensitivity increases, (1-specificity) will also increase. And that is how we calculate the ROC.
As stated before, the closer to 1 gets the evaluator, the better predictive performance the model will be, and the smaller the overlapping area between classes will be.
A complete walkthrough of the project can be found in the following article:
towardsdatascience.com
In the present article we will focus on the PySpark implementation of the project.
As a summary, throughout the project, we will use a number of different supervised algorithms to precisely predict individuals’ income using data collected from the 1994 U.S. Census.
We will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data.
Our goal with this implementation is to build a model that accurately predicts whether an individual makes more than $50,000. As from our previous research we have found out that the individuals who are most likely to donate money to a charity are the ones that make more than $50,000.
Therefore, we are facing a binary classification problem, where we want to determine wether an individual makes more than $50K a year (class 1) or do not (class 0).
The dataset for this project originates from the UCI Machine Learning Repository.
The census dataset consists of approximately 45222 data points, with each datapoint having 13 features.
Features
age: Age
workclass: Working Class (Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked)
education_level: Level of Education (Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool)
education-num: Number of educational years completed
marital-status: Marital status (Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse)
occupation: Work Occupation (Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces)
relationship: Relationship Status (Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried)
race: Race (White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black)
sex: Sex (Female, Male)
capital-gain: Monetary Capital Gains
capital-loss: Monetary Capital Losses
hours-per-week: Average Hours Per Week Worked
native-country: Native Country (United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands)
Target Variable
income: Income Class (<=50K, >50K)
We will start by importing the dataset and displaying the firsts rows of the data to make a first approximation to an exploratory data analysis.
# File location and typefile_location = "/FileStore/tables/census.csv"file_type = "csv"# CSV optionsinfer_schema = "true"first_row_is_header = "true"delimiter = ","# The applied options are for CSV files. For other file types, these will be ignored.df = spark.read.format(file_type) \ .option("inferSchema", infer_schema) \ .option("header", first_row_is_header) \ .option("sep", delimiter) \ .load(file_location)display(df)
We will now display a summary of the dataset’s information by using the .describe() method.
# Display Dataset's Summarydisplay(df.describe())
Let’s also find out the dataset’s schema.
# Display Dataset's Schemadisplay(df.describe())
As we want to predict wether or not the individual is earning more of $50K per year, we will substitute the label ‘income’ to ‘>50K’.
To do so, we will create a new column which values will be 1 or 0 depending if the individual makes or not more than $50K per year. We will then drop this income column.
# Import pyspark functionsfrom pyspark.sql import functions as F# Create add new column to the datasetdf = df.withColumn('>50K', F.when(df.income == '<=50K', 0).otherwise(1))# Drop the Income labeldf = df.drop('income')# Show dataset's columnsdf.columns
In order to be processed for the training of the models, features in Apache Spark must be transformed into vectors. This process will be done using certain classes that we will explore now.
First, we will import relevant libraries and methods.
from pyspark.ml import Pipelinefrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssemblerfrom pyspark.ml.classification import (DecisionTreeClassifier, GBTClassifier, RandomForestClassifier, LogisticRegression)from pyspark.ml.evaluation import BinaryClassificationEvaluator
Now, we will select the categorical features.
# Selecting categorical featurescategorical_columns = [ 'workclass', 'education_level', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'hours-per-week', 'native-country', ]
In order to One-Hot encode this categorical features we will first pass them through an indexer and then to an encoder.
# The index of string values multiple columnsindexers = [ StringIndexer(inputCol=c, outputCol="{0}_indexed".format(c)) for c in categorical_columns]# The encode of indexed values multiple columnsencoders = [OneHotEncoder(dropLast=False,inputCol=indexer.getOutputCol(), outputCol="{0}_encoded".format(indexer.getOutputCol())) for indexer in indexers]
Now, we will join the categorical encoded features with the numerical ones and make a vector with both of them.
# Vectorizing encoded valuescategorical_encoded = [encoder.getOutputCol() for encoder in encoders]numerical_columns = ['age', 'education-num', 'capital-gain', 'capital-loss']inputcols = categorical_encoded + numerical_columnsassembler = VectorAssembler(inputCols=inputcols, outputCol="features")
Now, we will set up a pipeline to automatize this stages.
pipeline = Pipeline(stages=indexers + encoders+[assembler])model = pipeline.fit(df)# Transform datatransformed = model.transform(df)display(transformed)
Finally, we will select a dataset only with the relevant features.
# Transform datafinal_data = transformed.select('features', '>50K')
For this project, we will study the predictive performance of three different classification algorithms:
Decision Trees
Random Forests
Gradient Boosted Trees
# Initialize the classification modelsdtc = DecisionTreeClassifier(labelCol='>50K', featuresCol='features')rfc = RandomForestClassifier(numTrees=150, labelCol='>50K', featuresCol='features')gbt = GBTClassifier(labelCol='>50K', featuresCol='features', maxIter=10)
We will perform a classic 80/20 split between training and testing data.
train_data, test_data = final_data.randomSplit([0.8,0.2])
dtc_model = dtc.fit(train_data)rfc_model = rfc.fit(train_data)gbt_model = gbt.fit(train_data)
Obtaining Predictions
dtc_preds = dtc_model.transform(test_data)rfc_preds = rfc_model.transform(test_data)gbt_preds = gbt_model.transform(test_data)
As stated before, our evaluator will be the ROC. We will initialize its class and pass it the predicitons in order to obtain the value.
my_eval = BinaryClassificationEvaluator(labelCol='>50K')# Display Decision Tree evaluation metricprint('DTC')print(my_eval.evaluate(dtc_preds))
# Display Random Forest evaluation metricprint('RFC')print(my_eval.evaluate(rfc_preds))
# Display Gradien Boosting Tree evaluation metricprint('GBT')print(my_eval.evaluate(gbt_preds))
The best predictor is the Gradient Boosting Tree. Actually 0.911 is a pretty good value and when display its predictions we will see the following:
We will try to do this by performing the grid search cross validation technique. With it, we will evaluate the performance of the model with different combinations of previously sets of hyperparameter’s values.
The hyperparameters that we will tune are:
Max Depth
Max Bins
Max Iterations
# Import librariesfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidator# Set the Parameters gridparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [2, 4, 6]) .addGrid(gbt.maxBins, [20, 60]) .addGrid(gbt.maxIter, [10, 20]) .build())# Iinitializing the cross validator classcv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=my_eval, numFolds=5)# Run cross validations. This can take about 6 minutes since it is training over 20 treescvModel = cv.fit(train_data)gbt_predictions_2 = cvModel.transform(test_data)my_eval.evaluate(gbt_predictions_2)
We have obtained a tiny improvement in the predictive performance. And the computation time, went almost to the 20 minutes. So, in these cases we should analyze if the improvement is worth the effort.
Throughout this article we made a machine learning classification project from end-to-end. We also learned and obtained several insights about classification models and the keys to develop one with a good performance, using PySpark, its methods and implementations.
We also have learned how to tune our algorithms once one good-performing model has been identified.
On the next articles we will learn how to develop Regression Models in PySpark. So, if you are interested in the topic I strongly suggest you to stay tuned!
If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here.
If you want to learn more about Machine Learning, Data Science and Artificial Intelligence follow me on Medium, and stay tuned for my next posts!
|
[
{
"code": null,
"e": 370,
"s": 172,
"text": "The aim of this article is to make a gentle introduction to Classification problems in Machine Learning and go through a comprehensive guide to develop succesfully a class prediction using PySpark."
},
{
"code": null,
"e": 415,
"s": 370,
"text": "So without further a do, let’s jump into it!"
},
{
"code": null,
"e": 663,
"s": 415,
"text": "If you want to a deep explanation about Classification problems, its main algorithms and how to deal with them using machine learning techniques, I strongly suggest you to chek out the following article, where I explain this concepts throughfully."
},
{
"code": null,
"e": 686,
"s": 663,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 892,
"s": 686,
"text": "Classification is a subcategory of supervised learning where the goal is to predict the categorical class labels (discrete, unoredered values, group membership) of new instances based on past observations."
},
{
"code": null,
"e": 945,
"s": 892,
"text": "There are two main types of classification problems:"
},
{
"code": null,
"e": 1064,
"s": 945,
"text": "Binary classification: The typical example is e-mail spam detection, which each e-mail is spam → 1 spam; or isn’t → 0."
},
{
"code": null,
"e": 1163,
"s": 1064,
"text": "Multi-class classification: Like handwritten character recognition (where classes go from 0 to 9)."
},
{
"code": null,
"e": 1242,
"s": 1163,
"text": "The following example is very representative to explain binary classification:"
},
{
"code": null,
"e": 1546,
"s": 1242,
"text": "There are 2 classes, circles and crosses, and 2 features, X1 and X2. The model is able to find the relationship between the features of each data point and its class, and to set a boundary line between them, so when provided with new data, it can estimate the class where it belongs, given its features."
},
{
"code": null,
"e": 1675,
"s": 1546,
"text": "In this case, the new data point falls into the circle subspace and, therefore, the model will predict its class to be a circle."
},
{
"code": null,
"e": 1953,
"s": 1675,
"text": "In order to predict the class of certain samples, there are several classification algorithms that can be used. In fact, when developing our machine learning models, we will train and evaluate a certain number of them, and we will keep those with better predicting performance."
},
{
"code": null,
"e": 2016,
"s": 1953,
"text": "A non-exhaustive list of some of the most used algorithms are:"
},
{
"code": null,
"e": 2036,
"s": 2016,
"text": "Logistic Regression"
},
{
"code": null,
"e": 2051,
"s": 2036,
"text": "Decision Trees"
},
{
"code": null,
"e": 2066,
"s": 2051,
"text": "Random Forests"
},
{
"code": null,
"e": 2090,
"s": 2066,
"text": "Support Vector Machines"
},
{
"code": null,
"e": 2116,
"s": 2090,
"text": "K-Nearest Neighbors (KNN)"
},
{
"code": null,
"e": 2183,
"s": 2116,
"text": "When making predictions on events we can get four type of results:"
},
{
"code": null,
"e": 2202,
"s": 2183,
"text": "True Positives: TP"
},
{
"code": null,
"e": 2221,
"s": 2202,
"text": "True Negatives: TN"
},
{
"code": null,
"e": 2241,
"s": 2221,
"text": "False Positives: FP"
},
{
"code": null,
"e": 2261,
"s": 2241,
"text": "False Negatives: FN"
},
{
"code": null,
"e": 2330,
"s": 2261,
"text": "All of these are represented in the following classification matrix:"
},
{
"code": null,
"e": 2524,
"s": 2330,
"text": "Accuracy measures how often the classifier makes the correct prediction. It’s the ratio of the number of correct predictions to the total number of predictions (the number of test data points)."
},
{
"code": null,
"e": 2679,
"s": 2524,
"text": "Precision tells us what proportion of events we classified as a certain class, actually were that class. It is a ratio of true positives to all positives."
},
{
"code": null,
"e": 2868,
"s": 2679,
"text": "Recall (sensitivity) tells us what proportion of events that actually were the of a certain class were classified by us as that class. It is a ratio of true positives to all the positives."
},
{
"code": null,
"e": 2986,
"s": 2868,
"text": "Specifity is the proportion of classes that were correctly identified as negative upon the total of negative classes."
},
{
"code": null,
"e": 3178,
"s": 2986,
"text": "For classification problems that are skewed in their classification distributions , accuracy by itself is not an appropiate metric. Instead, precision and recall are much more representative."
},
{
"code": null,
"e": 3442,
"s": 3178,
"text": "These two metrics can be combined to get the F1 score, which is weighted average(harmonic mean) of the precision and recall scores. This score can range from 0 to 1, with 1 being the best possible F1 score(we take the harmonic mean as we are dealing with ratios)."
},
{
"code": null,
"e": 3543,
"s": 3442,
"text": "Finally, the metric that we will use in our project is the Reciever Operation Characteristic or ROC."
},
{
"code": null,
"e": 3729,
"s": 3543,
"text": "The ROC curve tells us about how good the model can distinguish between two classes. It can get values from 0 to 1 ( €[0,1] ). The better the model is, the closer to 1 value it will be."
},
{
"code": null,
"e": 3849,
"s": 3729,
"text": "As can be seen in the image of above, our classification model will draw a separation boundary between the classes and:"
},
{
"code": null,
"e": 3940,
"s": 3849,
"text": "Every sample that falls at the left of the threshod, will be classified as negative class."
},
{
"code": null,
"e": 4032,
"s": 3940,
"text": "Every sample that falls at the right of the threshod, will be classified as positive class,"
},
{
"code": null,
"e": 4091,
"s": 4032,
"text": "And the distribution of predictions will be the following:"
},
{
"code": null,
"e": 4133,
"s": 4091,
"text": "Trade off Between Sensitivity & Specifity"
},
{
"code": null,
"e": 4267,
"s": 4133,
"text": "When we decrease the threshold, we end up predicting more positive values and increasing sensitivity. Therefore, specifity decreases."
},
{
"code": null,
"e": 4402,
"s": 4267,
"text": "When we increase the threshold, we end up predicting more negative values and increasing specifity. Therefore, decreasing sensitivity."
},
{
"code": null,
"e": 4435,
"s": 4402,
"text": "As Sensitivity ⬇️ Specificity ⬆️"
},
{
"code": null,
"e": 4468,
"s": 4435,
"text": "As Specificity ⬇️ Sensitivity ⬆️"
},
{
"code": null,
"e": 4674,
"s": 4468,
"text": "In order to optimize the classification performance,we consider (1- specifity) instead specificity. So, when sensitivity increases, (1-specificity) will also increase. And that is how we calculate the ROC."
},
{
"code": null,
"e": 4843,
"s": 4674,
"text": "As stated before, the closer to 1 gets the evaluator, the better predictive performance the model will be, and the smaller the overlapping area between classes will be."
},
{
"code": null,
"e": 4920,
"s": 4843,
"text": "A complete walkthrough of the project can be found in the following article:"
},
{
"code": null,
"e": 4943,
"s": 4920,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5026,
"s": 4943,
"text": "In the present article we will focus on the PySpark implementation of the project."
},
{
"code": null,
"e": 5209,
"s": 5026,
"text": "As a summary, throughout the project, we will use a number of different supervised algorithms to precisely predict individuals’ income using data collected from the 1994 U.S. Census."
},
{
"code": null,
"e": 5343,
"s": 5209,
"text": "We will then choose the best candidate algorithm from preliminary results and further optimize this algorithm to best model the data."
},
{
"code": null,
"e": 5629,
"s": 5343,
"text": "Our goal with this implementation is to build a model that accurately predicts whether an individual makes more than $50,000. As from our previous research we have found out that the individuals who are most likely to donate money to a charity are the ones that make more than $50,000."
},
{
"code": null,
"e": 5794,
"s": 5629,
"text": "Therefore, we are facing a binary classification problem, where we want to determine wether an individual makes more than $50K a year (class 1) or do not (class 0)."
},
{
"code": null,
"e": 5876,
"s": 5794,
"text": "The dataset for this project originates from the UCI Machine Learning Repository."
},
{
"code": null,
"e": 5980,
"s": 5876,
"text": "The census dataset consists of approximately 45222 data points, with each datapoint having 13 features."
},
{
"code": null,
"e": 5989,
"s": 5980,
"text": "Features"
},
{
"code": null,
"e": 5998,
"s": 5989,
"text": "age: Age"
},
{
"code": null,
"e": 6127,
"s": 5998,
"text": "workclass: Working Class (Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked)"
},
{
"code": null,
"e": 6315,
"s": 6127,
"text": "education_level: Level of Education (Bachelors, Some-college, 11th, HS-grad, Prof-school, Assoc-acdm, Assoc-voc, 9th, 7th-8th, 12th, Masters, 1st-4th, 10th, Doctorate, 5th-6th, Preschool)"
},
{
"code": null,
"e": 6368,
"s": 6315,
"text": "education-num: Number of educational years completed"
},
{
"code": null,
"e": 6507,
"s": 6368,
"text": "marital-status: Marital status (Married-civ-spouse, Divorced, Never-married, Separated, Widowed, Married-spouse-absent, Married-AF-spouse)"
},
{
"code": null,
"e": 6754,
"s": 6507,
"text": "occupation: Work Occupation (Tech-support, Craft-repair, Other-service, Sales, Exec-managerial, Prof-specialty, Handlers-cleaners, Machine-op-inspct, Adm-clerical, Farming-fishing, Transport-moving, Priv-house-serv, Protective-serv, Armed-Forces)"
},
{
"code": null,
"e": 6857,
"s": 6754,
"text": "relationship: Relationship Status (Wife, Own-child, Husband, Not-in-family, Other-relative, Unmarried)"
},
{
"code": null,
"e": 6930,
"s": 6857,
"text": "race: Race (White, Asian-Pac-Islander, Amer-Indian-Eskimo, Other, Black)"
},
{
"code": null,
"e": 6954,
"s": 6930,
"text": "sex: Sex (Female, Male)"
},
{
"code": null,
"e": 6991,
"s": 6954,
"text": "capital-gain: Monetary Capital Gains"
},
{
"code": null,
"e": 7029,
"s": 6991,
"text": "capital-loss: Monetary Capital Losses"
},
{
"code": null,
"e": 7075,
"s": 7029,
"text": "hours-per-week: Average Hours Per Week Worked"
},
{
"code": null,
"e": 7523,
"s": 7075,
"text": "native-country: Native Country (United-States, Cambodia, England, Puerto-Rico, Canada, Germany, Outlying-US(Guam-USVI-etc), India, Japan, Greece, South, China, Cuba, Iran, Honduras, Philippines, Italy, Poland, Jamaica, Vietnam, Mexico, Portugal, Ireland, France, Dominican-Republic, Laos, Ecuador, Taiwan, Haiti, Columbia, Hungary, Guatemala, Nicaragua, Scotland, Thailand, Yugoslavia, El-Salvador, Trinadad&Tobago, Peru, Hong, Holand-Netherlands)"
},
{
"code": null,
"e": 7539,
"s": 7523,
"text": "Target Variable"
},
{
"code": null,
"e": 7574,
"s": 7539,
"text": "income: Income Class (<=50K, >50K)"
},
{
"code": null,
"e": 7719,
"s": 7574,
"text": "We will start by importing the dataset and displaying the firsts rows of the data to make a first approximation to an exploratory data analysis."
},
{
"code": null,
"e": 8148,
"s": 7719,
"text": "# File location and typefile_location = \"/FileStore/tables/census.csv\"file_type = \"csv\"# CSV optionsinfer_schema = \"true\"first_row_is_header = \"true\"delimiter = \",\"# The applied options are for CSV files. For other file types, these will be ignored.df = spark.read.format(file_type) \\ .option(\"inferSchema\", infer_schema) \\ .option(\"header\", first_row_is_header) \\ .option(\"sep\", delimiter) \\ .load(file_location)display(df)"
},
{
"code": null,
"e": 8240,
"s": 8148,
"text": "We will now display a summary of the dataset’s information by using the .describe() method."
},
{
"code": null,
"e": 8290,
"s": 8240,
"text": "# Display Dataset's Summarydisplay(df.describe())"
},
{
"code": null,
"e": 8332,
"s": 8290,
"text": "Let’s also find out the dataset’s schema."
},
{
"code": null,
"e": 8381,
"s": 8332,
"text": "# Display Dataset's Schemadisplay(df.describe())"
},
{
"code": null,
"e": 8515,
"s": 8381,
"text": "As we want to predict wether or not the individual is earning more of $50K per year, we will substitute the label ‘income’ to ‘>50K’."
},
{
"code": null,
"e": 8685,
"s": 8515,
"text": "To do so, we will create a new column which values will be 1 or 0 depending if the individual makes or not more than $50K per year. We will then drop this income column."
},
{
"code": null,
"e": 8939,
"s": 8685,
"text": "# Import pyspark functionsfrom pyspark.sql import functions as F# Create add new column to the datasetdf = df.withColumn('>50K', F.when(df.income == '<=50K', 0).otherwise(1))# Drop the Income labeldf = df.drop('income')# Show dataset's columnsdf.columns"
},
{
"code": null,
"e": 9129,
"s": 8939,
"text": "In order to be processed for the training of the models, features in Apache Spark must be transformed into vectors. This process will be done using certain classes that we will explore now."
},
{
"code": null,
"e": 9183,
"s": 9129,
"text": "First, we will import relevant libraries and methods."
},
{
"code": null,
"e": 9475,
"s": 9183,
"text": "from pyspark.ml import Pipelinefrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssemblerfrom pyspark.ml.classification import (DecisionTreeClassifier, GBTClassifier, RandomForestClassifier, LogisticRegression)from pyspark.ml.evaluation import BinaryClassificationEvaluator"
},
{
"code": null,
"e": 9521,
"s": 9475,
"text": "Now, we will select the categorical features."
},
{
"code": null,
"e": 9710,
"s": 9521,
"text": "# Selecting categorical featurescategorical_columns = [ 'workclass', 'education_level', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'hours-per-week', 'native-country', ]"
},
{
"code": null,
"e": 9830,
"s": 9710,
"text": "In order to One-Hot encode this categorical features we will first pass them through an indexer and then to an encoder."
},
{
"code": null,
"e": 10201,
"s": 9830,
"text": "# The index of string values multiple columnsindexers = [ StringIndexer(inputCol=c, outputCol=\"{0}_indexed\".format(c)) for c in categorical_columns]# The encode of indexed values multiple columnsencoders = [OneHotEncoder(dropLast=False,inputCol=indexer.getOutputCol(), outputCol=\"{0}_encoded\".format(indexer.getOutputCol())) for indexer in indexers]"
},
{
"code": null,
"e": 10313,
"s": 10201,
"text": "Now, we will join the categorical encoded features with the numerical ones and make a vector with both of them."
},
{
"code": null,
"e": 10609,
"s": 10313,
"text": "# Vectorizing encoded valuescategorical_encoded = [encoder.getOutputCol() for encoder in encoders]numerical_columns = ['age', 'education-num', 'capital-gain', 'capital-loss']inputcols = categorical_encoded + numerical_columnsassembler = VectorAssembler(inputCols=inputcols, outputCol=\"features\")"
},
{
"code": null,
"e": 10667,
"s": 10609,
"text": "Now, we will set up a pipeline to automatize this stages."
},
{
"code": null,
"e": 10820,
"s": 10667,
"text": "pipeline = Pipeline(stages=indexers + encoders+[assembler])model = pipeline.fit(df)# Transform datatransformed = model.transform(df)display(transformed)"
},
{
"code": null,
"e": 10887,
"s": 10820,
"text": "Finally, we will select a dataset only with the relevant features."
},
{
"code": null,
"e": 10955,
"s": 10887,
"text": "# Transform datafinal_data = transformed.select('features', '>50K')"
},
{
"code": null,
"e": 11060,
"s": 10955,
"text": "For this project, we will study the predictive performance of three different classification algorithms:"
},
{
"code": null,
"e": 11075,
"s": 11060,
"text": "Decision Trees"
},
{
"code": null,
"e": 11090,
"s": 11075,
"text": "Random Forests"
},
{
"code": null,
"e": 11113,
"s": 11090,
"text": "Gradient Boosted Trees"
},
{
"code": null,
"e": 11376,
"s": 11113,
"text": "# Initialize the classification modelsdtc = DecisionTreeClassifier(labelCol='>50K', featuresCol='features')rfc = RandomForestClassifier(numTrees=150, labelCol='>50K', featuresCol='features')gbt = GBTClassifier(labelCol='>50K', featuresCol='features', maxIter=10)"
},
{
"code": null,
"e": 11449,
"s": 11376,
"text": "We will perform a classic 80/20 split between training and testing data."
},
{
"code": null,
"e": 11507,
"s": 11449,
"text": "train_data, test_data = final_data.randomSplit([0.8,0.2])"
},
{
"code": null,
"e": 11601,
"s": 11507,
"text": "dtc_model = dtc.fit(train_data)rfc_model = rfc.fit(train_data)gbt_model = gbt.fit(train_data)"
},
{
"code": null,
"e": 11623,
"s": 11601,
"text": "Obtaining Predictions"
},
{
"code": null,
"e": 11750,
"s": 11623,
"text": "dtc_preds = dtc_model.transform(test_data)rfc_preds = rfc_model.transform(test_data)gbt_preds = gbt_model.transform(test_data)"
},
{
"code": null,
"e": 11886,
"s": 11750,
"text": "As stated before, our evaluator will be the ROC. We will initialize its class and pass it the predicitons in order to obtain the value."
},
{
"code": null,
"e": 12030,
"s": 11886,
"text": "my_eval = BinaryClassificationEvaluator(labelCol='>50K')# Display Decision Tree evaluation metricprint('DTC')print(my_eval.evaluate(dtc_preds))"
},
{
"code": null,
"e": 12118,
"s": 12030,
"text": "# Display Random Forest evaluation metricprint('RFC')print(my_eval.evaluate(rfc_preds))"
},
{
"code": null,
"e": 12214,
"s": 12118,
"text": "# Display Gradien Boosting Tree evaluation metricprint('GBT')print(my_eval.evaluate(gbt_preds))"
},
{
"code": null,
"e": 12362,
"s": 12214,
"text": "The best predictor is the Gradient Boosting Tree. Actually 0.911 is a pretty good value and when display its predictions we will see the following:"
},
{
"code": null,
"e": 12573,
"s": 12362,
"text": "We will try to do this by performing the grid search cross validation technique. With it, we will evaluate the performance of the model with different combinations of previously sets of hyperparameter’s values."
},
{
"code": null,
"e": 12616,
"s": 12573,
"text": "The hyperparameters that we will tune are:"
},
{
"code": null,
"e": 12626,
"s": 12616,
"text": "Max Depth"
},
{
"code": null,
"e": 12635,
"s": 12626,
"text": "Max Bins"
},
{
"code": null,
"e": 12650,
"s": 12635,
"text": "Max Iterations"
},
{
"code": null,
"e": 13280,
"s": 12650,
"text": "# Import librariesfrom pyspark.ml.tuning import ParamGridBuilder, CrossValidator# Set the Parameters gridparamGrid = (ParamGridBuilder() .addGrid(gbt.maxDepth, [2, 4, 6]) .addGrid(gbt.maxBins, [20, 60]) .addGrid(gbt.maxIter, [10, 20]) .build())# Iinitializing the cross validator classcv = CrossValidator(estimator=gbt, estimatorParamMaps=paramGrid, evaluator=my_eval, numFolds=5)# Run cross validations. This can take about 6 minutes since it is training over 20 treescvModel = cv.fit(train_data)gbt_predictions_2 = cvModel.transform(test_data)my_eval.evaluate(gbt_predictions_2)"
},
{
"code": null,
"e": 13481,
"s": 13280,
"text": "We have obtained a tiny improvement in the predictive performance. And the computation time, went almost to the 20 minutes. So, in these cases we should analyze if the improvement is worth the effort."
},
{
"code": null,
"e": 13747,
"s": 13481,
"text": "Throughout this article we made a machine learning classification project from end-to-end. We also learned and obtained several insights about classification models and the keys to develop one with a good performance, using PySpark, its methods and implementations."
},
{
"code": null,
"e": 13847,
"s": 13747,
"text": "We also have learned how to tune our algorithms once one good-performing model has been identified."
},
{
"code": null,
"e": 14004,
"s": 13847,
"text": "On the next articles we will learn how to develop Regression Models in PySpark. So, if you are interested in the topic I strongly suggest you to stay tuned!"
},
{
"code": null,
"e": 14113,
"s": 14004,
"text": "If you liked this post then you can take a look at my other posts on Data Science and Machine Learning here."
}
] |
Tryit Editor v3.6 - Show Python
|
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
|
[
{
"code": null,
"e": 57,
"s": 25,
"text": "mydb = mysql.connector.connect("
},
{
"code": null,
"e": 77,
"s": 57,
"text": " host=\"localhost\","
},
{
"code": null,
"e": 98,
"s": 77,
"text": " user=\"myusername\","
},
{
"code": null,
"e": 123,
"s": 98,
"text": " password=\"mypassword\","
},
{
"code": null,
"e": 147,
"s": 123,
"text": " database=\"mydatabase\""
},
{
"code": null,
"e": 149,
"s": 147,
"text": ")"
},
{
"code": null,
"e": 151,
"s": 149,
"text": ""
}
] |
Peewee - Delete Records
|
Running delete_instance() method on a model instance delete corresponding row from the mapped table.
obj=User.get(User.name=="Amar")
obj.delete_instance()
On the other hand, delete() is a class method defined in model class, which generates DELETE query. Executing it effectively deletes rows from the table.
db.create_tables([User])
qry=User.delete().where (User.age==25)
qry.execute()
Concerned table in database shows effect of DELETE query as follows −
('DELETE FROM "User" WHERE ("User"."age" = ?)', [25])
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2485,
"s": 2384,
"text": "Running delete_instance() method on a model instance delete corresponding row from the mapped table."
},
{
"code": null,
"e": 2539,
"s": 2485,
"text": "obj=User.get(User.name==\"Amar\")\nobj.delete_instance()"
},
{
"code": null,
"e": 2693,
"s": 2539,
"text": "On the other hand, delete() is a class method defined in model class, which generates DELETE query. Executing it effectively deletes rows from the table."
},
{
"code": null,
"e": 2771,
"s": 2693,
"text": "db.create_tables([User])\nqry=User.delete().where (User.age==25)\nqry.execute()"
},
{
"code": null,
"e": 2841,
"s": 2771,
"text": "Concerned table in database shows effect of DELETE query as follows −"
},
{
"code": null,
"e": 2896,
"s": 2841,
"text": "('DELETE FROM \"User\" WHERE (\"User\".\"age\" = ?)', [25])\n"
},
{
"code": null,
"e": 2903,
"s": 2896,
"text": " Print"
},
{
"code": null,
"e": 2914,
"s": 2903,
"text": " Add Notes"
}
] |
Program to print pyramid pattern in C
|
A pyramid is a polyhedron formed by connecting a polygonal base and a point, called the apex. Each base edge and apex form a triangle, called a lateral face. It is a conic solid with polygonal base. A pyramid with an n-sided base has n + 1 vertices, n + 1 faces, and 2n edges. All pyramids are self-dual.
Accept the number of rows from the user to form pyramid shape
Iterate the loop till the number of rows specified by the user:
Display 1 star in the first row
Increase the number of stars based on the number of rows.
/*Program to print Pyramid Pattern*/
#include<stdio.h>
int main() {
int r, s, rows=0;
int t=0;
clrscr();
printf("Enter number of rows to print the pyramid: ");
scanf("%d", &rows);
printf("\n");
printf("The Pyramid Pattern for the number of rows are:");
printf("\n\n");
for(r=1;r<=rows;++r,t=0) {
for(s=1; s<=rows-r; ++s){
printf(" ");
}
while (t!=2*r-1) {
printf("* ");
++t;
}
printf("\n");
}
getch();
return 0;
}
|
[
{
"code": null,
"e": 1367,
"s": 1062,
"text": "A pyramid is a polyhedron formed by connecting a polygonal base and a point, called the apex. Each base edge and apex form a triangle, called a lateral face. It is a conic solid with polygonal base. A pyramid with an n-sided base has n + 1 vertices, n + 1 faces, and 2n edges. All pyramids are self-dual."
},
{
"code": null,
"e": 1583,
"s": 1367,
"text": "Accept the number of rows from the user to form pyramid shape\nIterate the loop till the number of rows specified by the user:\nDisplay 1 star in the first row\nIncrease the number of stars based on the number of rows."
},
{
"code": null,
"e": 2090,
"s": 1583,
"text": "/*Program to print Pyramid Pattern*/\n#include<stdio.h>\nint main() {\n int r, s, rows=0;\n int t=0;\n clrscr();\n printf(\"Enter number of rows to print the pyramid: \");\n scanf(\"%d\", &rows);\n printf(\"\\n\");\n printf(\"The Pyramid Pattern for the number of rows are:\");\n printf(\"\\n\\n\");\n for(r=1;r<=rows;++r,t=0) {\n for(s=1; s<=rows-r; ++s){\n printf(\" \");\n }\n while (t!=2*r-1) {\n printf(\"* \");\n ++t;\n }\n printf(\"\\n\");\n }\n getch();\n return 0;\n}"
}
] |
Python Program to Append, Delete and Display Elements of a List Using Classes
|
When it is required to append, delete, and display the elements of a list using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to add elements to the list, delete elements from the list and display the elements of the list using objects.
Below is a demonstration for the same −
Live Demo
class list_class():
def __init__(self):
self.n=[]
def add_val(self,a):
return self.n.append(a)
def remove_val(self,b):
self.n.remove(b)
def display_val(self):
return (self.n)
my_instance = list_class()
choice_val = 1
while choice_val!=0:
print("0. Exit")
print("1. Add elements")
print("2. Delete element")
print("3. Display list")
choice_val=int(input("Enter your choice: "))
if choice_val==1:
n=int(input("Enter element to add to the list... "))
my_instance.add_val(n)
print("List: ",my_instance.display_val())
elif choice_val==2:
n=int(input("Enter number to delete.."))
my_instance.remove_val(n)
print("List: ",my_instance.display_val())
elif choice_val==3:
print("List: ",my_instance.display_val())
elif choice_val==0:
print("Exit")
else:
print("Invalid choice!")
print()
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 1
Enter element to add to the list... 34
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 3
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 2
Enter number to delete..34
List: []
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 0
Exit
A class named ‘list_class’ class is defined, that has functions like ‘add_val’, ‘remove_val’, and ‘display_val’.
These are used to add elements to the list, remove element from the list and display the list respectively.
An instance of this class is created.
The elements of the list are entered and operations are performed on it.
Relevant messages and output is displayed on the console.
|
[
{
"code": null,
"e": 1484,
"s": 1062,
"text": "When it is required to append, delete, and display the elements of a list using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to add elements to the list, delete elements from the list and display the elements of the list using objects."
},
{
"code": null,
"e": 1524,
"s": 1484,
"text": "Below is a demonstration for the same −"
},
{
"code": null,
"e": 1535,
"s": 1524,
"text": " Live Demo"
},
{
"code": null,
"e": 2432,
"s": 1535,
"text": "class list_class():\n def __init__(self):\n self.n=[]\n def add_val(self,a):\n return self.n.append(a)\n def remove_val(self,b):\n self.n.remove(b)\n def display_val(self):\n return (self.n)\nmy_instance = list_class()\nchoice_val = 1\nwhile choice_val!=0:\n print(\"0. Exit\")\n print(\"1. Add elements\")\n print(\"2. Delete element\")\n print(\"3. Display list\")\n choice_val=int(input(\"Enter your choice: \"))\n if choice_val==1:\n n=int(input(\"Enter element to add to the list... \"))\n my_instance.add_val(n)\n print(\"List: \",my_instance.display_val())\n elif choice_val==2:\n n=int(input(\"Enter number to delete..\"))\n my_instance.remove_val(n)\n print(\"List: \",my_instance.display_val())\n elif choice_val==3:\n print(\"List: \",my_instance.display_val())\n elif choice_val==0:\n print(\"Exit\")\n else:\n print(\"Invalid choice!\")\nprint()"
},
{
"code": null,
"e": 2850,
"s": 2432,
"text": "0. Exit\n1. Add elements\n2. Delete element\n3. Display list\nEnter your choice: 1\nEnter element to add to the list... 34\nList: [34]\n0. Exit\n1. Add elements\n2. Delete element\n3. Display list\nEnter your choice: 3\nList: [34]\n0. Exit\n1. Add elements\n2. Delete element\n3. Display list\nEnter your choice: 2\nEnter number to delete..34\nList: []\n0. Exit\n1. Add elements\n2. Delete element\n3. Display list\nEnter your choice: 0\nExit"
},
{
"code": null,
"e": 2963,
"s": 2850,
"text": "A class named ‘list_class’ class is defined, that has functions like ‘add_val’, ‘remove_val’, and ‘display_val’."
},
{
"code": null,
"e": 3109,
"s": 2963,
"text": "These are used to add elements to the list, remove element from the list and display the list respectively.\nAn instance of this class is created."
},
{
"code": null,
"e": 3182,
"s": 3109,
"text": "The elements of the list are entered and operations are performed on it."
},
{
"code": null,
"e": 3240,
"s": 3182,
"text": "Relevant messages and output is displayed on the console."
}
] |
DateTime.AddMinutes() Method in C# - GeeksforGeeks
|
18 Jan, 2019
This method is used to return a new DateTime that adds the specified number of minutes to the value of this instance.
Syntax:
public DateTime AddMinutes (double value);
Here, value is a number of whole and fractional minutes. The value parameter can be negative or positive.
Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of minutes represented by value.
Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue.
Below programs illustrate the use of the above-discussed method:
Example 1:
// C# program to demonstrate the// DateTime.AddMinutes(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object DateTime d1 = new DateTime(2018, 9, 7, 7, 0, 0); // Taking minutes double[] m1 = {.01567, .06743, 12.12347, .89, .6666, 250.0}; foreach(double m2 in m1) { // using the method Console.WriteLine("{0} + {1} minute(s) = {2}", d1, m2, d1.AddMinutes(m2)); } }}
Output:
09/07/2018 07:00:00 + 0.01567 minute(s) = 09/07/2018 07:00:00
09/07/2018 07:00:00 + 0.06743 minute(s) = 09/07/2018 07:00:04
09/07/2018 07:00:00 + 12.12347 minute(s) = 09/07/2018 07:12:07
09/07/2018 07:00:00 + 0.89 minute(s) = 09/07/2018 07:00:53
09/07/2018 07:00:00 + 0.6666 minute(s) = 09/07/2018 07:00:39
09/07/2018 07:00:00 + 250 minute(s) = 09/07/2018 11:10:00
Example 2:
// C# program to demonstrate the// DateTime.AddMinutes(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object // by taking it MaxValue DateTime d1 = DateTime.MaxValue; // Taking minute variable double m1 = 1.7; // Using the Method will error as the // resulting DateTime is greater than // MaxValue Console.WriteLine(d1.AddMinutes(m1));}}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: value
Note:
This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation.
The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks.
The value parameter is rounded to the nearest millisecond.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addminutes?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n18 Jan, 2019"
},
{
"code": null,
"e": 24029,
"s": 23911,
"text": "This method is used to return a new DateTime that adds the specified number of minutes to the value of this instance."
},
{
"code": null,
"e": 24037,
"s": 24029,
"text": "Syntax:"
},
{
"code": null,
"e": 24080,
"s": 24037,
"text": "public DateTime AddMinutes (double value);"
},
{
"code": null,
"e": 24186,
"s": 24080,
"text": "Here, value is a number of whole and fractional minutes. The value parameter can be negative or positive."
},
{
"code": null,
"e": 24351,
"s": 24186,
"text": "Return Value: This method returns an object whose value is the sum of the date and time represented by this instance and the number of minutes represented by value."
},
{
"code": null,
"e": 24487,
"s": 24351,
"text": "Exception: This method will throw ArgumentOutOfRangeException if the resulting DateTime is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 24552,
"s": 24487,
"text": "Below programs illustrate the use of the above-discussed method:"
},
{
"code": null,
"e": 24563,
"s": 24552,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.AddMinutes(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object DateTime d1 = new DateTime(2018, 9, 7, 7, 0, 0); // Taking minutes double[] m1 = {.01567, .06743, 12.12347, .89, .6666, 250.0}; foreach(double m2 in m1) { // using the method Console.WriteLine(\"{0} + {1} minute(s) = {2}\", d1, m2, d1.AddMinutes(m2)); } }}",
"e": 25135,
"s": 24563,
"text": null
},
{
"code": null,
"e": 25143,
"s": 25135,
"text": "Output:"
},
{
"code": null,
"e": 25509,
"s": 25143,
"text": "09/07/2018 07:00:00 + 0.01567 minute(s) = 09/07/2018 07:00:00\n09/07/2018 07:00:00 + 0.06743 minute(s) = 09/07/2018 07:00:04\n09/07/2018 07:00:00 + 12.12347 minute(s) = 09/07/2018 07:12:07\n09/07/2018 07:00:00 + 0.89 minute(s) = 09/07/2018 07:00:53\n09/07/2018 07:00:00 + 0.6666 minute(s) = 09/07/2018 07:00:39\n09/07/2018 07:00:00 + 250 minute(s) = 09/07/2018 11:10:00\n"
},
{
"code": null,
"e": 25520,
"s": 25509,
"text": "Example 2:"
},
{
"code": "// C# program to demonstrate the// DateTime.AddMinutes(Double) Methodusing System; class GFG { // Main Methodpublic static void Main(){ // Creating a DateTime object // by taking it MaxValue DateTime d1 = DateTime.MaxValue; // Taking minute variable double m1 = 1.7; // Using the Method will error as the // resulting DateTime is greater than // MaxValue Console.WriteLine(d1.AddMinutes(m1));}}",
"e": 25951,
"s": 25520,
"text": null
},
{
"code": null,
"e": 25966,
"s": 25951,
"text": "Runtime Error:"
},
{
"code": null,
"e": 26114,
"s": 25966,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: The added or subtracted value results in an un-representable DateTime.Parameter name: value"
},
{
"code": null,
"e": 26120,
"s": 26114,
"text": "Note:"
},
{
"code": null,
"e": 26256,
"s": 26120,
"text": "This method does not change the value of this DateTime. Instead, it returns a new DateTime whose value is the result of this operation."
},
{
"code": null,
"e": 26411,
"s": 26256,
"text": "The fractional part of the value is the fractional part of a minute. For example, 7.5 is equivalent to 7 minutes, 30 seconds, 0 milliseconds, and 0 ticks."
},
{
"code": null,
"e": 26470,
"s": 26411,
"text": "The value parameter is rounded to the nearest millisecond."
},
{
"code": null,
"e": 26481,
"s": 26470,
"text": "Reference:"
},
{
"code": null,
"e": 26576,
"s": 26481,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.addminutes?view=netframework-4.7.2"
},
{
"code": null,
"e": 26599,
"s": 26576,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 26613,
"s": 26599,
"text": "CSharp-method"
},
{
"code": null,
"e": 26616,
"s": 26613,
"text": "C#"
},
{
"code": null,
"e": 26714,
"s": 26616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26723,
"s": 26714,
"text": "Comments"
},
{
"code": null,
"e": 26736,
"s": 26723,
"text": "Old Comments"
},
{
"code": null,
"e": 26776,
"s": 26736,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26799,
"s": 26776,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26827,
"s": 26799,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 26849,
"s": 26827,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 26866,
"s": 26849,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 26906,
"s": 26866,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 26939,
"s": 26906,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 26982,
"s": 26939,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 26998,
"s": 26982,
"text": "C# | List Class"
}
] |
How to format a string to date in as dd-MM-yyyy using java?
|
The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local).
Using the methods of this class you can parse String to Date or, format Date to String.
You can parse a given String to Date object using the parse() method of the SimpleDateFormat class. To this method you need to pass the Date in String format. To parse a String to Date object −
Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.
Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Parse/convert the required String to Date object using the parse() method by passing it as a parameter.
Parse/convert the required String to Date object using the parse() method by passing it as a parameter.
Date date = formatter.parse(dob);
System.out.println("Date object value: "+date);
Following Java program accepts name date of birth from the user in String format, converts/parses the obtained date of birth String to Date object and, calculates the current age and displays the result.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class CalculatingAge {
public static Date StringToDate(String dob) throws ParseException{
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
//Parsing the given String to Date object
Date date = formatter.parse(dob);
System.out.println("Date object value: "+date);
return date;
}
public static void main(String args[]) throws ParseException {
//Reading name and date of birth from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your date of birth (dd-MM-yyyy): ");
String dob = sc.next();
//Converting String to Date
Date date = CalculatingAge.StringToDate(dob);
//Converting obtained Date object to LocalDate object
Instant instant = date.toInstant();
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
LocalDate givenDate = zone.toLocalDate();
//Calculating the difference between given date to current date.
Period period = Period.between(givenDate, LocalDate.now());
System.out.print("Hello "+name+" your current age is: ");
System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
}
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Date object value: Tue Sep 26 00:00:00 IST 1989
Hello Krishna your current age is: 29 years 8 and 5 days
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local)."
},
{
"code": null,
"e": 1280,
"s": 1192,
"text": "Using the methods of this class you can parse String to Date or, format Date to String."
},
{
"code": null,
"e": 1474,
"s": 1280,
"text": "You can parse a given String to Date object using the parse() method of the SimpleDateFormat class. To this method you need to pass the Date in String format. To parse a String to Date object −"
},
{
"code": null,
"e": 1594,
"s": 1474,
"text": "Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor."
},
{
"code": null,
"e": 1714,
"s": 1594,
"text": "Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor."
},
{
"code": null,
"e": 1822,
"s": 1714,
"text": "//Instantiating the SimpleDateFormat class\nSimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");"
},
{
"code": null,
"e": 1926,
"s": 1822,
"text": "Parse/convert the required String to Date object using the parse() method by passing it as a parameter."
},
{
"code": null,
"e": 2030,
"s": 1926,
"text": "Parse/convert the required String to Date object using the parse() method by passing it as a parameter."
},
{
"code": null,
"e": 2112,
"s": 2030,
"text": "Date date = formatter.parse(dob);\nSystem.out.println(\"Date object value: \"+date);"
},
{
"code": null,
"e": 2316,
"s": 2112,
"text": "Following Java program accepts name date of birth from the user in String format, converts/parses the obtained date of birth String to Date object and, calculates the current age and displays the result."
},
{
"code": null,
"e": 2327,
"s": 2316,
"text": " Live Demo"
},
{
"code": null,
"e": 3921,
"s": 2327,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.time.Instant;\nimport java.time.LocalDate;\nimport java.time.Period;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.util.Date;\nimport java.util.Scanner;\npublic class CalculatingAge {\n public static Date StringToDate(String dob) throws ParseException{\n //Instantiating the SimpleDateFormat class\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n //Parsing the given String to Date object\n Date date = formatter.parse(dob);\n System.out.println(\"Date object value: \"+date);\n return date;\n }\n public static void main(String args[]) throws ParseException {\n //Reading name and date of birth from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your date of birth (dd-MM-yyyy): \");\n String dob = sc.next();\n //Converting String to Date\n Date date = CalculatingAge.StringToDate(dob);\n //Converting obtained Date object to LocalDate object\n Instant instant = date.toInstant();\n ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());\n LocalDate givenDate = zone.toLocalDate();\n //Calculating the difference between given date to current date.\n Period period = Period.between(givenDate, LocalDate.now());\n System.out.print(\"Hello \"+name+\" your current age is: \");\n System.out.print(period.getYears()+\" years \"+period.getMonths()+\" and \"+period.getDays()+\" days\");\n }\n}"
},
{
"code": null,
"e": 4101,
"s": 3921,
"text": "Enter your name:\nKrishna\nEnter your date of birth (dd-MM-yyyy):\n26-09-1989\nDate object value: Tue Sep 26 00:00:00 IST 1989\nHello Krishna your current age is: 29 years 8 and 5 days"
}
] |
Total coverage of all zeros in a binary matrix
|
06 Jul, 2022
Given a binary matrix that is, it contains 0s and 1s only, we need to find sum of coverage of all zeros of the matrix where coverage for a particular 0 is defined as total number of ones around a zero in left, right, up and bottom directions. The ones can be anywhere till corner point in a direction.
Examples:
Input : mat[][] = {0 0 0 0
1 0 0 1
0 1 1 0
0 1 0 0}
Output : 20
First four zeros are surrounded by only
one 1. So coverage for zeros in first
row is 1 + 1 + 1 + 1
Zeros in second row are surrounded by
three 1's. Note that there is no 1 above.
There are 1's in all other three directions.
Coverage of zeros in second row = 3 + 3.
Similarly counting for others also, we get
overall count as below.
1 + 1 + 1 + 1 + 3 + 3 + 2 + 2 + 2 + 2 + 2 = 20
Input : mat[][] = {1 1 1 0
1 0 0 1}
Output : 8
Coverage of first zero is 2
Coverages of other two zeros is 3
Total coverage = 2 + 3 + 3 = 8
A simple solution to solve this problem is by counting ones around zeros independently i.e. we run loop four times in each direction for each cell for the given matrix. Whenever we find a 1 in any loop, we break the loop and increment result by 1.
An efficient solution is to do following.
Traverse all rows from left to right, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all rows from right to left, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all columns from top to bottom, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all columns from bottom to top, increment result if a 1 is already seen (in current traversal) and current element is 0.
Traverse all rows from left to right, increment result if a 1 is already seen (in current traversal) and current element is 0.
Traverse all rows from right to left, increment result if a 1 is already seen (in current traversal) and current element is 0.
Traverse all columns from top to bottom, increment result if a 1 is already seen (in current traversal) and current element is 0.
Traverse all columns from bottom to top, increment result if a 1 is already seen (in current traversal) and current element is 0.
In below code a Boolean variable isOne is taken, which is made true as soon as a one is encountered in current traversal, for all zeros after that iteration, result is incremented by one, same procedure is applied in all four directions to get final answer. We reset isOne to false after every traversal.
C++
Java
Python3
C#
Javascript
// C++ program to get total coverage of all zeros in// a binary matrix#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // Returns total coverage of all zeros in mat[][]int getTotalCoverageOfMatrix(int mat[R][C]){ int res = 0; // looping for all rows of matrix for (int i = 0; i < R; i++) { bool isOne = false; // 1 is not seen yet // looping in columns from left to right // direction to get left ones for (int j = 0; j < C; j++) { // If one is found from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we have found // a 1 before. else if (isOne) res++; } // Repeat the above process for right to // left direction. isOne = false; for (int j = C-1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns for up and down // directions. for (int j = 0; j < C; j++) { bool isOne = false; // 1 is not seen yet for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R-1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver code to test above methodsint main(){ int mat[R][C] = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0} }; cout << getTotalCoverageOfMatrix(mat); return 0;}
// Java program to get total// coverage of all zeros in// a binary matriximport java .io.*; class GFG{static int R = 4;static int C = 4; // Returns total coverage// of all zeros in mat[][]static int getTotalCoverageOfMatrix(int [][]mat){ int res = 0; // looping for all // rows of matrix for (int i = 0; i < R; i++) { // 1 is not seen yet boolean isOne = false; // looping in columns from // left to right direction // to get left ones for (int j = 0; j < C; j++) { // If one is found // from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above // process for right // to left direction. isOne = false; for (int j = C - 1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (int j = 0; j < C; j++) { // 1 is not seen yet boolean isOne = false; for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R - 1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver codestatic public void main (String[] args){ int [][]mat = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}}; System.out.println( getTotalCoverageOfMatrix(mat));}} // This code is contributed by anuj_67.
# Python3 program to get total coverage of all zeros in# a binary matrixR = 4C = 4 # Returns total coverage of all zeros in mat[][]def getTotalCoverageOfMatrix(mat): res = 0 # looping for all rows of matrix for i in range(R): isOne = False # 1 is not seen yet # looping in columns from left to right # direction to get left ones for j in range(C): # If one is found from left if (mat[i][j] == 1): isOne = True # If 0 is found and we have found # a 1 before. else if (isOne): res += 1 # Repeat the above process for right to # left direction. isOne = False for j in range(C - 1, -1, -1): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 # Traversing across columns for up and down # directions. for j in range(C): isOne = False # 1 is not seen yet for i in range(R): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 isOne = False for i in range(R - 1, -1, -1): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 return res # Driver codemat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]]print(getTotalCoverageOfMatrix(mat)) # This code is contributed by shubhamsingh10
// C# program to get total coverage// of all zeros in a binary matrixusing System; class GFG { static int R = 4;static int C = 4; // Returns total coverage of all zeros in mat[][]static int getTotalCoverageOfMatrix(int [,]mat){ int res = 0; // looping for all rows of matrix for (int i = 0; i < R; i++) { // 1 is not seen yet bool isOne = false; // looping in columns from left to // right direction to get left ones for (int j = 0; j < C; j++) { // If one is found from left if (mat[i,j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above process for // right to left direction. isOne = false; for (int j = C-1; j >= 0; j--) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (int j = 0; j < C; j++) { // 1 is not seen yet bool isOne = false; for (int i = 0; i < R; i++) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R-1; i >= 0; i--) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver code to test above methods static public void Main () { int [,]mat = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}}; Console.WriteLine(getTotalCoverageOfMatrix(mat)); }} // This code is contributed by vt_m.
<script> // Javascript program to get total // coverage of all zeros in // a binary matrix let R = 4; let C = 4; // Returns total coverage // of all zeros in mat[][] function getTotalCoverageOfMatrix(mat) { let res = 0; // looping for all // rows of matrix for (let i = 0; i < R; i++) { // 1 is not seen yet let isOne = false; // looping in columns from // left to right direction // to get left ones for (let j = 0; j < C; j++) { // If one is found // from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above // process for right // to left direction. isOne = false; for (let j = C - 1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (let j = 0; j < C; j++) { // 1 is not seen yet let isOne = false; for (let i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (let i = R - 1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res; } let mat = [[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 0]]; document.write(getTotalCoverageOfMatrix(mat)); </script>
20
Time Complexity: O(n2) Auxiliary Space: O(1)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
vt_m
SHUBHAMSINGH10
decode2207
sweetyty
surinderdawra388
hardikkoriintern
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sudoku | Backtracking-7
The Celebrity Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
Maximum size square sub-matrix with all 1s
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Inplace rotate square matrix by 90 degrees | Set 1
Unique paths in a Grid with Obstacles
Printing all solutions in N-Queen Problem
Min Cost Path | DP-6
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 356,
"s": 53,
"text": "Given a binary matrix that is, it contains 0s and 1s only, we need to find sum of coverage of all zeros of the matrix where coverage for a particular 0 is defined as total number of ones around a zero in left, right, up and bottom directions. The ones can be anywhere till corner point in a direction. "
},
{
"code": null,
"e": 367,
"s": 356,
"text": "Examples: "
},
{
"code": null,
"e": 1031,
"s": 367,
"text": "Input : mat[][] = {0 0 0 0\n 1 0 0 1\n 0 1 1 0\n 0 1 0 0}\nOutput : 20\nFirst four zeros are surrounded by only \none 1. So coverage for zeros in first \nrow is 1 + 1 + 1 + 1\nZeros in second row are surrounded by\nthree 1's. Note that there is no 1 above.\nThere are 1's in all other three directions.\nCoverage of zeros in second row = 3 + 3. \nSimilarly counting for others also, we get\noverall count as below.\n1 + 1 + 1 + 1 + 3 + 3 + 2 + 2 + 2 + 2 + 2 = 20\n\nInput : mat[][] = {1 1 1 0\n 1 0 0 1}\nOutput : 8\nCoverage of first zero is 2\nCoverages of other two zeros is 3\nTotal coverage = 2 + 3 + 3 = 8"
},
{
"code": null,
"e": 1279,
"s": 1031,
"text": "A simple solution to solve this problem is by counting ones around zeros independently i.e. we run loop four times in each direction for each cell for the given matrix. Whenever we find a 1 in any loop, we break the loop and increment result by 1."
},
{
"code": null,
"e": 1322,
"s": 1279,
"text": "An efficient solution is to do following. "
},
{
"code": null,
"e": 1833,
"s": 1322,
"text": "Traverse all rows from left to right, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all rows from right to left, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all columns from top to bottom, increment result if a 1 is already seen (in current traversal) and current element is 0.Traverse all columns from bottom to top, increment result if a 1 is already seen (in current traversal) and current element is 0."
},
{
"code": null,
"e": 1960,
"s": 1833,
"text": "Traverse all rows from left to right, increment result if a 1 is already seen (in current traversal) and current element is 0."
},
{
"code": null,
"e": 2087,
"s": 1960,
"text": "Traverse all rows from right to left, increment result if a 1 is already seen (in current traversal) and current element is 0."
},
{
"code": null,
"e": 2217,
"s": 2087,
"text": "Traverse all columns from top to bottom, increment result if a 1 is already seen (in current traversal) and current element is 0."
},
{
"code": null,
"e": 2347,
"s": 2217,
"text": "Traverse all columns from bottom to top, increment result if a 1 is already seen (in current traversal) and current element is 0."
},
{
"code": null,
"e": 2652,
"s": 2347,
"text": "In below code a Boolean variable isOne is taken, which is made true as soon as a one is encountered in current traversal, for all zeros after that iteration, result is incremented by one, same procedure is applied in all four directions to get final answer. We reset isOne to false after every traversal."
},
{
"code": null,
"e": 2656,
"s": 2652,
"text": "C++"
},
{
"code": null,
"e": 2661,
"s": 2656,
"text": "Java"
},
{
"code": null,
"e": 2669,
"s": 2661,
"text": "Python3"
},
{
"code": null,
"e": 2672,
"s": 2669,
"text": "C#"
},
{
"code": null,
"e": 2683,
"s": 2672,
"text": "Javascript"
},
{
"code": "// C++ program to get total coverage of all zeros in// a binary matrix#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // Returns total coverage of all zeros in mat[][]int getTotalCoverageOfMatrix(int mat[R][C]){ int res = 0; // looping for all rows of matrix for (int i = 0; i < R; i++) { bool isOne = false; // 1 is not seen yet // looping in columns from left to right // direction to get left ones for (int j = 0; j < C; j++) { // If one is found from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we have found // a 1 before. else if (isOne) res++; } // Repeat the above process for right to // left direction. isOne = false; for (int j = C-1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns for up and down // directions. for (int j = 0; j < C; j++) { bool isOne = false; // 1 is not seen yet for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R-1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver code to test above methodsint main(){ int mat[R][C] = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0} }; cout << getTotalCoverageOfMatrix(mat); return 0;}",
"e": 4415,
"s": 2683,
"text": null
},
{
"code": "// Java program to get total// coverage of all zeros in// a binary matriximport java .io.*; class GFG{static int R = 4;static int C = 4; // Returns total coverage// of all zeros in mat[][]static int getTotalCoverageOfMatrix(int [][]mat){ int res = 0; // looping for all // rows of matrix for (int i = 0; i < R; i++) { // 1 is not seen yet boolean isOne = false; // looping in columns from // left to right direction // to get left ones for (int j = 0; j < C; j++) { // If one is found // from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above // process for right // to left direction. isOne = false; for (int j = C - 1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (int j = 0; j < C; j++) { // 1 is not seen yet boolean isOne = false; for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R - 1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver codestatic public void main (String[] args){ int [][]mat = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}}; System.out.println( getTotalCoverageOfMatrix(mat));}} // This code is contributed by anuj_67.",
"e": 6293,
"s": 4415,
"text": null
},
{
"code": "# Python3 program to get total coverage of all zeros in# a binary matrixR = 4C = 4 # Returns total coverage of all zeros in mat[][]def getTotalCoverageOfMatrix(mat): res = 0 # looping for all rows of matrix for i in range(R): isOne = False # 1 is not seen yet # looping in columns from left to right # direction to get left ones for j in range(C): # If one is found from left if (mat[i][j] == 1): isOne = True # If 0 is found and we have found # a 1 before. else if (isOne): res += 1 # Repeat the above process for right to # left direction. isOne = False for j in range(C - 1, -1, -1): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 # Traversing across columns for up and down # directions. for j in range(C): isOne = False # 1 is not seen yet for i in range(R): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 isOne = False for i in range(R - 1, -1, -1): if (mat[i][j] == 1): isOne = True else if (isOne): res += 1 return res # Driver codemat = [[0, 0, 0, 0],[1, 0, 0, 1],[0, 1, 1, 0],[0, 1, 0, 0]]print(getTotalCoverageOfMatrix(mat)) # This code is contributed by shubhamsingh10",
"e": 7856,
"s": 6293,
"text": null
},
{
"code": "// C# program to get total coverage// of all zeros in a binary matrixusing System; class GFG { static int R = 4;static int C = 4; // Returns total coverage of all zeros in mat[][]static int getTotalCoverageOfMatrix(int [,]mat){ int res = 0; // looping for all rows of matrix for (int i = 0; i < R; i++) { // 1 is not seen yet bool isOne = false; // looping in columns from left to // right direction to get left ones for (int j = 0; j < C; j++) { // If one is found from left if (mat[i,j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above process for // right to left direction. isOne = false; for (int j = C-1; j >= 0; j--) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (int j = 0; j < C; j++) { // 1 is not seen yet bool isOne = false; for (int i = 0; i < R; i++) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R-1; i >= 0; i--) { if (mat[i,j] == 1) isOne = true; else if (isOne) res++; } } return res;} // Driver code to test above methods static public void Main () { int [,]mat = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0}}; Console.WriteLine(getTotalCoverageOfMatrix(mat)); }} // This code is contributed by vt_m.",
"e": 9696,
"s": 7856,
"text": null
},
{
"code": "<script> // Javascript program to get total // coverage of all zeros in // a binary matrix let R = 4; let C = 4; // Returns total coverage // of all zeros in mat[][] function getTotalCoverageOfMatrix(mat) { let res = 0; // looping for all // rows of matrix for (let i = 0; i < R; i++) { // 1 is not seen yet let isOne = false; // looping in columns from // left to right direction // to get left ones for (let j = 0; j < C; j++) { // If one is found // from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we // have found a 1 before. else if (isOne) res++; } // Repeat the above // process for right // to left direction. isOne = false; for (let j = C - 1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns // for up and down directions. for (let j = 0; j < C; j++) { // 1 is not seen yet let isOne = false; for (let i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (let i = R - 1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res; } let mat = [[0, 0, 0, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 0]]; document.write(getTotalCoverageOfMatrix(mat)); </script>",
"e": 11689,
"s": 9696,
"text": null
},
{
"code": null,
"e": 11692,
"s": 11689,
"text": "20"
},
{
"code": null,
"e": 11737,
"s": 11692,
"text": "Time Complexity: O(n2) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12037,
"s": 11737,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 12042,
"s": 12037,
"text": "vt_m"
},
{
"code": null,
"e": 12057,
"s": 12042,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 12068,
"s": 12057,
"text": "decode2207"
},
{
"code": null,
"e": 12077,
"s": 12068,
"text": "sweetyty"
},
{
"code": null,
"e": 12094,
"s": 12077,
"text": "surinderdawra388"
},
{
"code": null,
"e": 12111,
"s": 12094,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 12118,
"s": 12111,
"text": "Matrix"
},
{
"code": null,
"e": 12125,
"s": 12118,
"text": "Matrix"
},
{
"code": null,
"e": 12223,
"s": 12125,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12247,
"s": 12223,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 12269,
"s": 12247,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 12351,
"s": 12269,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 12394,
"s": 12351,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 12465,
"s": 12394,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 12518,
"s": 12465,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 12569,
"s": 12518,
"text": "Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 12607,
"s": 12569,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 12649,
"s": 12607,
"text": "Printing all solutions in N-Queen Problem"
}
] |
Python | os.rmdir() method
|
29 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.rmdir() method in Python is used to remove or delete a empty directory. OSError will be raised if the specified path is not an empty directory.
Syntax: os.rmdir(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
# Python program to explain os.rmdir() method # importing os module import os # Directory namedirectory = "ihritik" # Parent Directoryparent = "/home/User/Documents" # Pathpath = os.path.join(parent, directory) # Remove the Directory# "ihritik"os.rmdir(path)print("Directory '%s' has been removed successfully" %directory)
Directory 'ihritik' has been removed successfully
# Python program to explain os.rmdir() method # importing os module import os # Directory namedirectory = "ihritik" # Parent Directoryparent = "/home/User/Documents" # Pathpath = os.path.join(parent, directory) # Remove the Directory# "ihritik"try: os.rmdir(path) print("Directory '%s' has been removed successfully" %directory)except OSError as error: print(error) print("Directory '%s' can not be removed" %directory) # if the specified path # is not an empty directory# then permission error will# be raised # similarly if specified path# is invalid or is not a # directory then corresponding# OSError will be raised
[Errno 13] Permission denied: '/home/User/Documents/ihritik'
Directory 'ihritik' can not be removed
Reference: https://docs.python.org/3/library/os.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 247,
"s": 28,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 442,
"s": 247,
"text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system."
},
{
"code": null,
"e": 589,
"s": 442,
"text": "os.rmdir() method in Python is used to remove or delete a empty directory. OSError will be raised if the specified path is not an empty directory."
},
{
"code": null,
"e": 630,
"s": 589,
"text": "Syntax: os.rmdir(path, *, dir_fd = None)"
},
{
"code": null,
"e": 931,
"s": 630,
"text": "Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored."
},
{
"code": null,
"e": 1131,
"s": 931,
"text": "Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter."
},
{
"code": null,
"e": 1183,
"s": 1131,
"text": "Return Type: This method does not return any value."
},
{
"code": "# Python program to explain os.rmdir() method # importing os module import os # Directory namedirectory = \"ihritik\" # Parent Directoryparent = \"/home/User/Documents\" # Pathpath = os.path.join(parent, directory) # Remove the Directory# \"ihritik\"os.rmdir(path)print(\"Directory '%s' has been removed successfully\" %directory)",
"e": 1514,
"s": 1183,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1514,
"text": "Directory 'ihritik' has been removed successfully\n"
},
{
"code": "# Python program to explain os.rmdir() method # importing os module import os # Directory namedirectory = \"ihritik\" # Parent Directoryparent = \"/home/User/Documents\" # Pathpath = os.path.join(parent, directory) # Remove the Directory# \"ihritik\"try: os.rmdir(path) print(\"Directory '%s' has been removed successfully\" %directory)except OSError as error: print(error) print(\"Directory '%s' can not be removed\" %directory) # if the specified path # is not an empty directory# then permission error will# be raised # similarly if specified path# is invalid or is not a # directory then corresponding# OSError will be raised",
"e": 2211,
"s": 1565,
"text": null
},
{
"code": null,
"e": 2312,
"s": 2211,
"text": "[Errno 13] Permission denied: '/home/User/Documents/ihritik'\nDirectory 'ihritik' can not be removed\n"
},
{
"code": null,
"e": 2365,
"s": 2312,
"text": "Reference: https://docs.python.org/3/library/os.html"
},
{
"code": null,
"e": 2387,
"s": 2365,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 2404,
"s": 2387,
"text": "python-os-module"
},
{
"code": null,
"e": 2411,
"s": 2404,
"text": "Python"
}
] |
How to Add Title to Subplots in Matplotlib?
|
03 Jan, 2021
In this article, we will see how to add a title to subplots in Matplotlib? Let’s discuss some concepts :
Matplotlib : 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. It was introduced by John Hunter in the year 2002.
Subplots : The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots. Subplots are required when we want to show two or more plots in same figure.
Title of a plot : The title() method in matplotlib module is used to specify title of the visualization depicted and displays the title using various attributes.
Import Libraries
Create/ Load data
Make subplot
Plot subplot
Set title to subplots.
Example 1: (Using set_title() method)
We use matplotlib.axes._axes.Axes.set_title(label) method to set title (string label) for the current subplot Axes.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plotax[0, 0].plot(x, x)ax[0, 1].plot(x, x*2)ax[1, 0].plot(x, x*x)ax[1, 1].plot(x, x*x*x) # set the title to subplotsax[0, 0].set_title("Linear")ax[0, 1].set_title("Double")ax[1, 0].set_title("Square")ax[1, 1].set_title("Cube") # set spacingfig.tight_layout()plt.show()
Output:
Example 2: (Using title.set_text() method)
We can also add title to subplots in Matplotlib using title.set_text() method, in similar way to set_title() method.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plotax[0, 0].plot(x, x)ax[0, 1].plot(x, x*2)ax[1, 0].plot(x, x*x)ax[1, 1].plot(x, x*x*x) # set the title to subplotsax[0, 0].title.set_text("Linear")ax[0, 1].title.set_text("Double")ax[1, 0].title.set_text("Square")ax[1, 1].title.set_text("Cube") # set spacingfig.tight_layout()plt.show()
Output:
Example 3: (Using plt.gca().set_title() method)
If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the reference of the current axes of the subplot and combine set_title() method to set title to the subplots in Matplotlib.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plottitle = ["Linear", "Double", "Square", "Cube"]y = [x, x*2, x*x, x*x*x] for i in range(4): # subplots plt.subplot(2, 2, i+1) # ploting (x,y) plt.plot(x, y[i]) # set the title to subplots plt.gca().set_title(title[i]) # set spacingfig.tight_layout()plt.show()
Output :
Example 4: (Using plt.gca().title.set_text() method)
If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the reference of the current axes of the subplot and combine title.set_text() method to set title to the subplots in Matplotlib.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plottitle = ["Linear","Double","Square","Cube"]y = [x, x*2, x*x, x*x*x] for i in range(4): # subplots plt.subplot(2, 2, i+1) # ploting (x,y) plt.plot(x, y[i]) # set the title to subplots plt.gca().title.set_text(title[i]) # set spacingfig.tight_layout()plt.show()
Output :
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 157,
"s": 52,
"text": "In this article, we will see how to add a title to subplots in Matplotlib? Let’s discuss some concepts :"
},
{
"code": null,
"e": 433,
"s": 157,
"text": "Matplotlib : 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. It was introduced by John Hunter in the year 2002."
},
{
"code": null,
"e": 634,
"s": 433,
"text": "Subplots : The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots. Subplots are required when we want to show two or more plots in same figure."
},
{
"code": null,
"e": 796,
"s": 634,
"text": "Title of a plot : The title() method in matplotlib module is used to specify title of the visualization depicted and displays the title using various attributes."
},
{
"code": null,
"e": 813,
"s": 796,
"text": "Import Libraries"
},
{
"code": null,
"e": 831,
"s": 813,
"text": "Create/ Load data"
},
{
"code": null,
"e": 844,
"s": 831,
"text": "Make subplot"
},
{
"code": null,
"e": 857,
"s": 844,
"text": "Plot subplot"
},
{
"code": null,
"e": 880,
"s": 857,
"text": "Set title to subplots."
},
{
"code": null,
"e": 918,
"s": 880,
"text": "Example 1: (Using set_title() method)"
},
{
"code": null,
"e": 1034,
"s": 918,
"text": "We use matplotlib.axes._axes.Axes.set_title(label) method to set title (string label) for the current subplot Axes."
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Python3"
},
{
"code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plotax[0, 0].plot(x, x)ax[0, 1].plot(x, x*2)ax[1, 0].plot(x, x*x)ax[1, 1].plot(x, x*x*x) # set the title to subplotsax[0, 0].set_title(\"Linear\")ax[0, 1].set_title(\"Double\")ax[1, 0].set_title(\"Square\")ax[1, 1].set_title(\"Cube\") # set spacingfig.tight_layout()plt.show()",
"e": 1502,
"s": 1042,
"text": null
},
{
"code": null,
"e": 1510,
"s": 1502,
"text": "Output:"
},
{
"code": null,
"e": 1553,
"s": 1510,
"text": "Example 2: (Using title.set_text() method)"
},
{
"code": null,
"e": 1670,
"s": 1553,
"text": "We can also add title to subplots in Matplotlib using title.set_text() method, in similar way to set_title() method."
},
{
"code": null,
"e": 1678,
"s": 1670,
"text": "Python3"
},
{
"code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plotax[0, 0].plot(x, x)ax[0, 1].plot(x, x*2)ax[1, 0].plot(x, x*x)ax[1, 1].plot(x, x*x*x) # set the title to subplotsax[0, 0].title.set_text(\"Linear\")ax[0, 1].title.set_text(\"Double\")ax[1, 0].title.set_text(\"Square\")ax[1, 1].title.set_text(\"Cube\") # set spacingfig.tight_layout()plt.show()",
"e": 2158,
"s": 1678,
"text": null
},
{
"code": null,
"e": 2166,
"s": 2158,
"text": "Output:"
},
{
"code": null,
"e": 2214,
"s": 2166,
"text": "Example 3: (Using plt.gca().set_title() method)"
},
{
"code": null,
"e": 2432,
"s": 2214,
"text": "If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the reference of the current axes of the subplot and combine set_title() method to set title to the subplots in Matplotlib."
},
{
"code": null,
"e": 2440,
"s": 2432,
"text": "Python3"
},
{
"code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plottitle = [\"Linear\", \"Double\", \"Square\", \"Cube\"]y = [x, x*2, x*x, x*x*x] for i in range(4): # subplots plt.subplot(2, 2, i+1) # ploting (x,y) plt.plot(x, y[i]) # set the title to subplots plt.gca().set_title(title[i]) # set spacingfig.tight_layout()plt.show()",
"e": 2934,
"s": 2440,
"text": null
},
{
"code": null,
"e": 2943,
"s": 2934,
"text": "Output :"
},
{
"code": null,
"e": 2996,
"s": 2943,
"text": "Example 4: (Using plt.gca().title.set_text() method)"
},
{
"code": null,
"e": 3219,
"s": 2996,
"text": "If you use Matlab-like style in the interactive plotting, then you could use plt.gca() to get the reference of the current axes of the subplot and combine title.set_text() method to set title to the subplots in Matplotlib."
},
{
"code": null,
"e": 3227,
"s": 3219,
"text": "Python3"
},
{
"code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax=np.array([1, 2, 3, 4, 5]) # making subplotsfig, ax = plt.subplots(2, 2) # set data with subplots and plottitle = [\"Linear\",\"Double\",\"Square\",\"Cube\"]y = [x, x*2, x*x, x*x*x] for i in range(4): # subplots plt.subplot(2, 2, i+1) # ploting (x,y) plt.plot(x, y[i]) # set the title to subplots plt.gca().title.set_text(title[i]) # set spacingfig.tight_layout()plt.show()",
"e": 3721,
"s": 3227,
"text": null
},
{
"code": null,
"e": 3730,
"s": 3721,
"text": "Output :"
},
{
"code": null,
"e": 3737,
"s": 3730,
"text": "Picked"
},
{
"code": null,
"e": 3755,
"s": 3737,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3762,
"s": 3755,
"text": "Python"
},
{
"code": null,
"e": 3860,
"s": 3762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3888,
"s": 3860,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3910,
"s": 3888,
"text": "Python map() function"
},
{
"code": null,
"e": 3960,
"s": 3910,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3978,
"s": 3960,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4022,
"s": 3978,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 4064,
"s": 4022,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4087,
"s": 4064,
"text": "Taking input in Python"
},
{
"code": null,
"e": 4109,
"s": 4087,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4144,
"s": 4109,
"text": "Read a file line by line in Python"
}
] |
Python | Add leading Zeros to string
|
25 Jun, 2022
Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading zeroes to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns out to be handy in many situations. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using rjust() function offers a single-line way to perform this particular task. Hence can easily be employed on any string whose padding we need to be done. We can specify the amount of padding required.
Python3
# Python3 code to demonstrate# adding leading zeros# using rjust() # initializing stringtest_string = 'GFG' # printing original stringprint(& quot The original string : & quot + str(test_string)) # No. of zeros requiredN = 4 # using rjust()# adding leading zerores = test_string.rjust(N + len(test_string), '0') # print resultprint(& quot The string after adding leading zeros : & quot + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
Method #2: Using zfill() This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended.
Python3
# Python3 code to demonstrate# adding leading zeros# using zfill() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using zfill()# adding leading zerores = test_string.zfill(N + len(test_string)) # print resultprint("The string after adding leading zeros : " + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
Method #3: Without any built-in methods.
Python3
# Python3 code to demonstrate# adding leading zeros # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # adding leading zerox = '0'*Nres = x+test_string # print resultprint("The string after adding leading zeros : " + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2022"
},
{
"code": null,
"e": 365,
"s": 28,
"text": "Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading zeroes to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns out to be handy in many situations. Let’s discuss certain ways in which this problem can be solved. "
},
{
"code": null,
"e": 582,
"s": 365,
"text": "Method #1: Using rjust() function offers a single-line way to perform this particular task. Hence can easily be employed on any string whose padding we need to be done. We can specify the amount of padding required. "
},
{
"code": null,
"e": 590,
"s": 582,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# adding leading zeros# using rjust() # initializing stringtest_string = 'GFG' # printing original stringprint(& quot The original string : & quot + str(test_string)) # No. of zeros requiredN = 4 # using rjust()# adding leading zerores = test_string.rjust(N + len(test_string), '0') # print resultprint(& quot The string after adding leading zeros : & quot + str(res))",
"e": 1012,
"s": 590,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1012,
"text": "The original string : GFG\nThe string after adding leading zeros : 0000GFG"
},
{
"code": null,
"e": 1324,
"s": 1086,
"text": "Method #2: Using zfill() This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended. "
},
{
"code": null,
"e": 1332,
"s": 1324,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# adding leading zeros# using zfill() # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # using zfill()# adding leading zerores = test_string.zfill(N + len(test_string)) # print resultprint(\"The string after adding leading zeros : \" + str(res))",
"e": 1703,
"s": 1332,
"text": null
},
{
"code": null,
"e": 1777,
"s": 1703,
"text": "The original string : GFG\nThe string after adding leading zeros : 0000GFG"
},
{
"code": null,
"e": 1818,
"s": 1777,
"text": "Method #3: Without any built-in methods."
},
{
"code": null,
"e": 1826,
"s": 1818,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# adding leading zeros # initializing stringtest_string = 'GFG' # printing original stringprint(\"The original string : \" + str(test_string)) # No. of zeros requiredN = 4 # adding leading zerox = '0'*Nres = x+test_string # print resultprint(\"The string after adding leading zeros : \" + str(res))",
"e": 2151,
"s": 1826,
"text": null
},
{
"code": null,
"e": 2225,
"s": 2151,
"text": "The original string : GFG\nThe string after adding leading zeros : 0000GFG"
},
{
"code": null,
"e": 2239,
"s": 2225,
"text": "kogantibhavya"
},
{
"code": null,
"e": 2262,
"s": 2239,
"text": "Python string-programs"
},
{
"code": null,
"e": 2269,
"s": 2262,
"text": "Python"
},
{
"code": null,
"e": 2285,
"s": 2269,
"text": "Python Programs"
},
{
"code": null,
"e": 2383,
"s": 2285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2401,
"s": 2383,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2443,
"s": 2401,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2465,
"s": 2443,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2500,
"s": 2465,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2526,
"s": 2500,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2569,
"s": 2526,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2591,
"s": 2569,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2630,
"s": 2591,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2668,
"s": 2630,
"text": "Python | Convert a list to dictionary"
}
] |
PHP | ctype_digit() (Checks for numeric value)
|
05 Jun, 2018
A ctype_digit() function in PHP used to check each and every character of text are numeric or not. It returns TRUE if all characters of the string are numeric otherwise return FALSE.
Syntax :
ctype_digit(string text)
Parameter Used:The ctype_digit() function in PHP accepts only one parameter.
text : Its mandatory parameter which specifies the tested string.
Return Values:It returns TRUE if all characters of the string are numeric otherwise return FALSE.
Errors and Exceptions:
Gives Expected result when passing string not gives desired output when passing an integer.The function returns true on empty string previous versions of PHP 5.1.0
Gives Expected result when passing string not gives desired output when passing an integer.
The function returns true on empty string previous versions of PHP 5.1.0
Examples:
Input :789495001
Output : Yes
Explanation : All digits, return True
Input : 789.0877
Output : No
Explanation: String contains floating point,
return false.
Below programs illustrate the ctype_digit() function.
Program: 1 Checking ctype_digit() function for a single string which contains all digits.
<?php// PHP program to check given string is // control character $string = '123456789'; // Checking above given string // by using of ctype_digit() function. if ( ctype_digit($string)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; } ?>
Yes
Program: 2Drive a code ctype_digit() function where input will be array of string which contains special characters, integers, strings.
<?php// PHP program to check is given string// contains all digits using ctype_digit $strings = array( 'Geeks-2018', 'geek@yahoo.com', '10.99999Fe', '12345', 'geeksforgeeks.org'); // Checking above given strings //by used of ctype_digit() function . foreach ($strings as $testcase) { if (ctype_digit($testcase)) { // if true then return Yes echo "Yes\n"; } else { // if False then return No echo "No\n"; }} ?>
No
No
No
Yes
No
ctype_digit() vs is_int()ctype_digit() is basically for string type and is_int() for integer types. ctype_digit() traverses through all characters and checks if every character is digit or not. For example,
<?php// PHP code to demonstrate difference between// ctype_digit() and is_int().$x = "-123";if (ctype_digit($x)) echo "Yes\n";else echo "No\n"; $x = -123;if (is_int($x)) echo "Yes";else echo "No";?>
No
Yes
References :http://php.net/manual/en/function.ctype-digit.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
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": "\n05 Jun, 2018"
},
{
"code": null,
"e": 211,
"s": 28,
"text": "A ctype_digit() function in PHP used to check each and every character of text are numeric or not. It returns TRUE if all characters of the string are numeric otherwise return FALSE."
},
{
"code": null,
"e": 220,
"s": 211,
"text": "Syntax :"
},
{
"code": null,
"e": 246,
"s": 220,
"text": "ctype_digit(string text)\n"
},
{
"code": null,
"e": 323,
"s": 246,
"text": "Parameter Used:The ctype_digit() function in PHP accepts only one parameter."
},
{
"code": null,
"e": 389,
"s": 323,
"text": "text : Its mandatory parameter which specifies the tested string."
},
{
"code": null,
"e": 487,
"s": 389,
"text": "Return Values:It returns TRUE if all characters of the string are numeric otherwise return FALSE."
},
{
"code": null,
"e": 510,
"s": 487,
"text": "Errors and Exceptions:"
},
{
"code": null,
"e": 674,
"s": 510,
"text": "Gives Expected result when passing string not gives desired output when passing an integer.The function returns true on empty string previous versions of PHP 5.1.0"
},
{
"code": null,
"e": 766,
"s": 674,
"text": "Gives Expected result when passing string not gives desired output when passing an integer."
},
{
"code": null,
"e": 839,
"s": 766,
"text": "The function returns true on empty string previous versions of PHP 5.1.0"
},
{
"code": null,
"e": 849,
"s": 839,
"text": "Examples:"
},
{
"code": null,
"e": 1029,
"s": 849,
"text": "Input :789495001\nOutput : Yes\nExplanation : All digits, return True\n\nInput : 789.0877\nOutput : No\nExplanation: String contains floating point, \nreturn false. \n"
},
{
"code": null,
"e": 1083,
"s": 1029,
"text": "Below programs illustrate the ctype_digit() function."
},
{
"code": null,
"e": 1173,
"s": 1083,
"text": "Program: 1 Checking ctype_digit() function for a single string which contains all digits."
},
{
"code": "<?php// PHP program to check given string is // control character $string = '123456789'; // Checking above given string // by using of ctype_digit() function. if ( ctype_digit($string)) { // if true then return Yes echo \"Yes\\n\"; } else { // if False then return No echo \"No\\n\"; } ?>",
"e": 1528,
"s": 1173,
"text": null
},
{
"code": null,
"e": 1533,
"s": 1528,
"text": "Yes\n"
},
{
"code": null,
"e": 1669,
"s": 1533,
"text": "Program: 2Drive a code ctype_digit() function where input will be array of string which contains special characters, integers, strings."
},
{
"code": "<?php// PHP program to check is given string// contains all digits using ctype_digit $strings = array( 'Geeks-2018', 'geek@yahoo.com', '10.99999Fe', '12345', 'geeksforgeeks.org'); // Checking above given strings //by used of ctype_digit() function . foreach ($strings as $testcase) { if (ctype_digit($testcase)) { // if true then return Yes echo \"Yes\\n\"; } else { // if False then return No echo \"No\\n\"; }} ?>",
"e": 2143,
"s": 1669,
"text": null
},
{
"code": null,
"e": 2160,
"s": 2143,
"text": "No\nNo\nNo\nYes\nNo\n"
},
{
"code": null,
"e": 2367,
"s": 2160,
"text": "ctype_digit() vs is_int()ctype_digit() is basically for string type and is_int() for integer types. ctype_digit() traverses through all characters and checks if every character is digit or not. For example,"
},
{
"code": "<?php// PHP code to demonstrate difference between// ctype_digit() and is_int().$x = \"-123\";if (ctype_digit($x)) echo \"Yes\\n\";else echo \"No\\n\"; $x = -123;if (is_int($x)) echo \"Yes\";else echo \"No\";?>",
"e": 2577,
"s": 2367,
"text": null
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "No\nYes\n"
},
{
"code": null,
"e": 2647,
"s": 2585,
"text": "References :http://php.net/manual/en/function.ctype-digit.php"
},
{
"code": null,
"e": 2660,
"s": 2647,
"text": "PHP-function"
},
{
"code": null,
"e": 2664,
"s": 2660,
"text": "PHP"
},
{
"code": null,
"e": 2681,
"s": 2664,
"text": "Web Technologies"
},
{
"code": null,
"e": 2685,
"s": 2681,
"text": "PHP"
},
{
"code": null,
"e": 2783,
"s": 2685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2833,
"s": 2783,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2873,
"s": 2833,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2934,
"s": 2873,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2984,
"s": 2934,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3029,
"s": 2984,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3062,
"s": 3029,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3124,
"s": 3062,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3185,
"s": 3124,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3235,
"s": 3185,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
D3.js axis.ticks() Function
|
07 Aug, 2020
The d3.axis.ticks() Function in D3.js is used to control which ticks are displayed by the axis. This function returns the axis generator
Syntax:
axis.ticks(arguments...)
axis.ticks([count[, specifier]])
axis.ticks([interval[, specifier]])
Parameters: This function accepts the following parameters.
count/interval: This parameter is used to display the number of ticks.
specifier: This parameter is an optional format specifier to customize how the tick values are formatted.
Return Value: This function returns the axis generator.
Below programs illustrate the d3.axis.ticks() function in D3.js:
Example 1:
<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.ticks() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom().scale(xscale).ticks(5); var xAxisTranslate = height / 2; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate + ")") .call(x_axis) </script> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html> <head> <title> D3.js | d3.axis.ticks() Function </title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: end; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft().scale(yscale).ticks(3, "$.2f"); svg.append("g") .attr("transform", "translate(100, 20)") .call(y_axis) </script> </body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
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": "\n07 Aug, 2020"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "The d3.axis.ticks() Function in D3.js is used to control which ticks are displayed by the axis. This function returns the axis generator"
},
{
"code": null,
"e": 173,
"s": 165,
"text": "Syntax:"
},
{
"code": null,
"e": 267,
"s": 173,
"text": "axis.ticks(arguments...)\naxis.ticks([count[, specifier]])\naxis.ticks([interval[, specifier]])"
},
{
"code": null,
"e": 327,
"s": 267,
"text": "Parameters: This function accepts the following parameters."
},
{
"code": null,
"e": 398,
"s": 327,
"text": "count/interval: This parameter is used to display the number of ticks."
},
{
"code": null,
"e": 504,
"s": 398,
"text": "specifier: This parameter is an optional format specifier to customize how the tick values are formatted."
},
{
"code": null,
"e": 560,
"s": 504,
"text": "Return Value: This function returns the axis generator."
},
{
"code": null,
"e": 625,
"s": 560,
"text": "Below programs illustrate the d3.axis.ticks() function in D3.js:"
},
{
"code": null,
"e": 636,
"s": 625,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | D3.axis.ticks() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: center; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var xscale = d3.scaleLinear() .domain([0, 10]) .range([0, width - 60]); var x_axis = d3.axisBottom().scale(xscale).ticks(5); var xAxisTranslate = height / 2; svg.append(\"g\") .attr(\"transform\", \"translate(50, \" + xAxisTranslate + \")\") .call(x_axis) </script> </body> </html>",
"e": 1561,
"s": 636,
"text": null
},
{
"code": null,
"e": 1569,
"s": 1561,
"text": "Output:"
},
{
"code": null,
"e": 1580,
"s": 1569,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> D3.js | d3.axis.ticks() Function </title> <script type=\"text/javascript\" src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> svg text { fill: green; font: 15px sans-serif; text-anchor: end; } </style> </head> <body> <script> var width = 400, height = 400; var svg = d3.select(\"body\") .append(\"svg\") .attr(\"width\", width) .attr(\"height\", height); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height - 50, 0]); var y_axis = d3.axisLeft().scale(yscale).ticks(3, \"$.2f\"); svg.append(\"g\") .attr(\"transform\", \"translate(100, 20)\") .call(y_axis) </script> </body> </html>",
"e": 2436,
"s": 1580,
"text": null
},
{
"code": null,
"e": 2444,
"s": 2436,
"text": "Output:"
},
{
"code": null,
"e": 2450,
"s": 2444,
"text": "D3.js"
},
{
"code": null,
"e": 2461,
"s": 2450,
"text": "JavaScript"
},
{
"code": null,
"e": 2478,
"s": 2461,
"text": "Web Technologies"
},
{
"code": null,
"e": 2576,
"s": 2478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2637,
"s": 2576,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2709,
"s": 2637,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2749,
"s": 2709,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2801,
"s": 2749,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2842,
"s": 2801,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2904,
"s": 2842,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2937,
"s": 2904,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2998,
"s": 2937,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3048,
"s": 2998,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to use JavaScript Fetch API to Get Data ?
|
08 Jan, 2021
The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests.
Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity and few more. However, the most prominent ones we use are method, headers and body.
Method are used to create, read, update and delete data, and hence we have methods like GET, POST, PUT and DELETE.
As an example we would use the API: https://reqres.in/arpi/users which would give us random data about a person, our goal here is to see what is presented in this data.
Syntax:
fetch(URL, options)
Parameters: This method accepts two parameters as shown above and described below:
URL: This is the endpoint of the resource from where you want to fetch data.Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. Body: In this part, we actually pass the data as a JSON.
URL: This is the endpoint of the resource from where you want to fetch data.
Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. Body: In this part, we actually pass the data as a JSON.
Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.
Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc.
Body: In this part, we actually pass the data as a JSON.
Example 1: GET Request demonstration.
Javascript
fetch("https://reqres.in/api/users").then(res => res.json()).then(data => console.log(data))
Output: This is what the API is returning to us, some random data about people.
Example 2: POST Request demonstration. We will, now post some random data by our self, with the help of POST method.
Javascript
fetch("https://reqres.in/api/users", { // Defining method type as POST method: 'POST', // Fetch knows, what type of data are we dealing with headers: { 'Content-Type': 'application/json' }, // Data needs to be parsed into JSON body: JSON.stringify({ name: 'Geeks For Geeks', website: 'https://www.geeksforgeeks.org/', })}).then(res => { return res.json()}).then(data => console.log(data));
Output: Here, we see that we have successfully made a POST request using fetch API.
JavaScript-Misc
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
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": "\n08 Jan, 2021"
},
{
"code": null,
"e": 202,
"s": 52,
"text": "The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests. "
},
{
"code": null,
"e": 418,
"s": 202,
"text": "Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity and few more. However, the most prominent ones we use are method, headers and body."
},
{
"code": null,
"e": 533,
"s": 418,
"text": "Method are used to create, read, update and delete data, and hence we have methods like GET, POST, PUT and DELETE."
},
{
"code": null,
"e": 703,
"s": 533,
"text": "As an example we would use the API: https://reqres.in/arpi/users which would give us random data about a person, our goal here is to see what is presented in this data. "
},
{
"code": null,
"e": 712,
"s": 703,
"text": "Syntax: "
},
{
"code": null,
"e": 732,
"s": 712,
"text": "fetch(URL, options)"
},
{
"code": null,
"e": 815,
"s": 732,
"text": "Parameters: This method accepts two parameters as shown above and described below:"
},
{
"code": null,
"e": 1300,
"s": 815,
"text": "URL: This is the endpoint of the resource from where you want to fetch data.Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. Body: In this part, we actually pass the data as a JSON."
},
{
"code": null,
"e": 1377,
"s": 1300,
"text": "URL: This is the endpoint of the resource from where you want to fetch data."
},
{
"code": null,
"e": 1786,
"s": 1377,
"text": "Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. Body: In this part, we actually pass the data as a JSON."
},
{
"code": null,
"e": 1894,
"s": 1786,
"text": "Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc."
},
{
"code": null,
"e": 2041,
"s": 1894,
"text": "Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc. "
},
{
"code": null,
"e": 2098,
"s": 2041,
"text": "Body: In this part, we actually pass the data as a JSON."
},
{
"code": null,
"e": 2136,
"s": 2098,
"text": "Example 1: GET Request demonstration."
},
{
"code": null,
"e": 2147,
"s": 2136,
"text": "Javascript"
},
{
"code": "fetch(\"https://reqres.in/api/users\").then(res => res.json()).then(data => console.log(data))",
"e": 2240,
"s": 2147,
"text": null
},
{
"code": null,
"e": 2320,
"s": 2240,
"text": "Output: This is what the API is returning to us, some random data about people."
},
{
"code": null,
"e": 2438,
"s": 2320,
"text": "Example 2: POST Request demonstration. We will, now post some random data by our self, with the help of POST method. "
},
{
"code": null,
"e": 2449,
"s": 2438,
"text": "Javascript"
},
{
"code": "fetch(\"https://reqres.in/api/users\", { // Defining method type as POST method: 'POST', // Fetch knows, what type of data are we dealing with headers: { 'Content-Type': 'application/json' }, // Data needs to be parsed into JSON body: JSON.stringify({ name: 'Geeks For Geeks', website: 'https://www.geeksforgeeks.org/', })}).then(res => { return res.json()}).then(data => console.log(data));",
"e": 2860,
"s": 2449,
"text": null
},
{
"code": null,
"e": 2945,
"s": 2860,
"text": "Output: Here, we see that we have successfully made a POST request using fetch API. "
},
{
"code": null,
"e": 2961,
"s": 2945,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2968,
"s": 2961,
"text": "Picked"
},
{
"code": null,
"e": 2992,
"s": 2968,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3003,
"s": 2992,
"text": "JavaScript"
},
{
"code": null,
"e": 3022,
"s": 3003,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3039,
"s": 3022,
"text": "Web Technologies"
}
] |
Ways to filter Pandas DataFrame by column values
|
01 Oct, 2020
In this post, we will see different ways to filter Pandas Dataframe by column values. First, Let’s create a Dataframe:
Python3
# importing pandas import pandas as pd # declare a dictionaryrecord = { 'Name' : ['Ankit', 'Swapnil', 'Aishwarya', 'Priyanka', 'Shivangi', 'Shaurya' ], 'Age' : [22, 20, 21, 19, 18, 22], 'Stream' : ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage' : [90, 90, 96, 75, 70, 80] } # create a dataframe dataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) # show the Dataframeprint("Given Dataframe :\n", dataframe)
Output:
Method 1: Selecting rows of Pandas Dataframe based on particular column value using ‘>’, ‘=’, ‘=’, ‘<=’, ‘!=’ operator.
Example 1: Selecting all the rows from the given Dataframe in which ‘Percentage’ is greater than 75 using [ ].
Python3
# selecting rows based on condition rslt_df = dataframe[dataframe['Percentage'] > 70] print('\nResult dataframe :\n', rslt_df)
Output:
Example 2: Selecting all the rows from the given Dataframe in which ‘Percentage’ is greater than 70 using loc[ ].
Python3
# selecting rows based on condition rslt_df = dataframe.loc[dataframe['Percentage'] > 70] print('\nResult dataframe :\n', rslt_df)
Output:
Method 2: Selecting those rows of Pandas Dataframe whose column value is present in the list using isin() method of the dataframe.
Example 1: Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using [ ].
Python3
options = ['Science', 'Commerce'] # selecting rows based on condition rslt_df = dataframe[dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df)
Output:
Example 2: Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using loc[ ].
Python
options = ['Science', 'Commerce'] # selecting rows based on condition rslt_df = dataframe.loc[dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df)
Output:
Method 3: Selecting rows of Pandas Dataframe based on multiple column conditions using ‘&’ operator.
Example1: Selecting all the rows from the given Dataframe in which ‘Age’ is equal to 22 and ‘Stream’ is present in the options list using [ ].
Python3
options = ['Commerce' ,'Science'] # selecting rows based on condition rslt_df = dataframe[(dataframe['Age'] == 22) & dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df)
Output:
Example 2: Selecting all the rows from the given Dataframe in which ‘Age’ is equal to 22 and ‘Stream’ is present in the options list using loc[ ].
Python3
options = ['Commerce', 'Science'] # selecting rows based on condition rslt_df = dataframe.loc[(dataframe['Age'] == 22) & dataframe['Stream'].isin(options)] print('\nResult dataframe :\n', rslt_df)
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "In this post, we will see different ways to filter Pandas Dataframe by column values. First, Let’s create a Dataframe:"
},
{
"code": null,
"e": 155,
"s": 147,
"text": "Python3"
},
{
"code": "# importing pandas import pandas as pd # declare a dictionaryrecord = { 'Name' : ['Ankit', 'Swapnil', 'Aishwarya', 'Priyanka', 'Shivangi', 'Shaurya' ], 'Age' : [22, 20, 21, 19, 18, 22], 'Stream' : ['Math', 'Commerce', 'Science', 'Math', 'Math', 'Science'], 'Percentage' : [90, 90, 96, 75, 70, 80] } # create a dataframe dataframe = pd.DataFrame(record, columns = ['Name', 'Age', 'Stream', 'Percentage']) # show the Dataframeprint(\"Given Dataframe :\\n\", dataframe)",
"e": 726,
"s": 155,
"text": null
},
{
"code": null,
"e": 734,
"s": 726,
"text": "Output:"
},
{
"code": null,
"e": 854,
"s": 734,
"text": "Method 1: Selecting rows of Pandas Dataframe based on particular column value using ‘>’, ‘=’, ‘=’, ‘<=’, ‘!=’ operator."
},
{
"code": null,
"e": 965,
"s": 854,
"text": "Example 1: Selecting all the rows from the given Dataframe in which ‘Percentage’ is greater than 75 using [ ]."
},
{
"code": null,
"e": 973,
"s": 965,
"text": "Python3"
},
{
"code": "# selecting rows based on condition rslt_df = dataframe[dataframe['Percentage'] > 70] print('\\nResult dataframe :\\n', rslt_df)",
"e": 1104,
"s": 973,
"text": null
},
{
"code": null,
"e": 1112,
"s": 1104,
"text": "Output:"
},
{
"code": null,
"e": 1227,
"s": 1112,
"text": "Example 2: Selecting all the rows from the given Dataframe in which ‘Percentage’ is greater than 70 using loc[ ]. "
},
{
"code": null,
"e": 1235,
"s": 1227,
"text": "Python3"
},
{
"code": "# selecting rows based on condition rslt_df = dataframe.loc[dataframe['Percentage'] > 70] print('\\nResult dataframe :\\n', rslt_df)",
"e": 1376,
"s": 1235,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1515,
"s": 1384,
"text": "Method 2: Selecting those rows of Pandas Dataframe whose column value is present in the list using isin() method of the dataframe."
},
{
"code": null,
"e": 1634,
"s": 1515,
"text": "Example 1: Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using [ ]."
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Python3"
},
{
"code": "options = ['Science', 'Commerce'] # selecting rows based on condition rslt_df = dataframe[dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)",
"e": 1821,
"s": 1642,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1821,
"text": "Output:"
},
{
"code": null,
"e": 1951,
"s": 1829,
"text": "Example 2: Selecting all the rows from the given dataframe in which ‘Stream’ is present in the options list using loc[ ]."
},
{
"code": null,
"e": 1958,
"s": 1951,
"text": "Python"
},
{
"code": "options = ['Science', 'Commerce'] # selecting rows based on condition rslt_df = dataframe.loc[dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)",
"e": 2142,
"s": 1958,
"text": null
},
{
"code": null,
"e": 2150,
"s": 2142,
"text": "Output:"
},
{
"code": null,
"e": 2253,
"s": 2150,
"text": "Method 3: Selecting rows of Pandas Dataframe based on multiple column conditions using ‘&’ operator. "
},
{
"code": null,
"e": 2396,
"s": 2253,
"text": "Example1: Selecting all the rows from the given Dataframe in which ‘Age’ is equal to 22 and ‘Stream’ is present in the options list using [ ]."
},
{
"code": null,
"e": 2404,
"s": 2396,
"text": "Python3"
},
{
"code": "options = ['Commerce' ,'Science'] # selecting rows based on condition rslt_df = dataframe[(dataframe['Age'] == 22) & dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)",
"e": 2620,
"s": 2404,
"text": null
},
{
"code": null,
"e": 2628,
"s": 2620,
"text": "Output:"
},
{
"code": null,
"e": 2775,
"s": 2628,
"text": "Example 2: Selecting all the rows from the given Dataframe in which ‘Age’ is equal to 22 and ‘Stream’ is present in the options list using loc[ ]."
},
{
"code": null,
"e": 2783,
"s": 2775,
"text": "Python3"
},
{
"code": "options = ['Commerce', 'Science'] # selecting rows based on condition rslt_df = dataframe.loc[(dataframe['Age'] == 22) & dataframe['Stream'].isin(options)] print('\\nResult dataframe :\\n', rslt_df)",
"e": 3006,
"s": 2783,
"text": null
},
{
"code": null,
"e": 3014,
"s": 3006,
"text": "Output:"
},
{
"code": null,
"e": 3038,
"s": 3014,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3061,
"s": 3038,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3075,
"s": 3061,
"text": "Python-pandas"
},
{
"code": null,
"e": 3082,
"s": 3075,
"text": "Python"
},
{
"code": null,
"e": 3180,
"s": 3082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3198,
"s": 3180,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3240,
"s": 3198,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3262,
"s": 3240,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3297,
"s": 3262,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3329,
"s": 3297,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3355,
"s": 3329,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3384,
"s": 3355,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3411,
"s": 3384,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3432,
"s": 3411,
"text": "Python OOPs Concepts"
}
] |
Python – Split heterogeneous type list
|
16 Sep, 2021
Sometimes, we might be working with many data types and in these instances, we can have a problem in which list that we receive might be having elements from different data types. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isinstance() The combination of above both functionalities can be used to perform this task. In this, we just extract the similar element types using different list comprehensions and detect the type using isinstance().
Python3
# Python3 code to demonstrate working of# Split heterogeneous type list# using list comprehension + isinstance # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Split heterogeneous type list# using list comprehension + isinstanceres_str = [ele for ele in test_list if isinstance(ele, str)]res_int = [ele for ele in test_list if isinstance(ele, int)] # printing resultprint("Integer list : " + str(res_int))print("String list : " + str(res_str))
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
Method #2 : Using defaultdict() + loop This is yet another way in which this problem can be solved. In this, we initialize the list as data type for defaultdict() and loop through each element and save each datatype list in defaultdict.
Python3
# Python3 code to demonstrate working of# Split heterogeneous type list# using defaultdict() + loopfrom collections import defaultdict # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Split heterogeneous type list# using defaultdict() + loopres = defaultdict(list)for ele in test_list: res[type(ele)].append(ele) # printing resultprint("Integer list : " + str(res[int]))print("String list : " + str(res[str]))
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
akshaysingh98088
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 272,
"s": 28,
"text": "Sometimes, we might be working with many data types and in these instances, we can have a problem in which list that we receive might be having elements from different data types. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 531,
"s": 272,
"text": "Method #1 : Using list comprehension + isinstance() The combination of above both functionalities can be used to perform this task. In this, we just extract the similar element types using different list comprehensions and detect the type using isinstance()."
},
{
"code": null,
"e": 539,
"s": 531,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split heterogeneous type list# using list comprehension + isinstance # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint(\"The original list : \" + str(test_list)) # Split heterogeneous type list# using list comprehension + isinstanceres_str = [ele for ele in test_list if isinstance(ele, str)]res_int = [ele for ele in test_list if isinstance(ele, int)] # printing resultprint(\"Integer list : \" + str(res_int))print(\"String list : \" + str(res_str))",
"e": 1064,
"s": 539,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1064,
"text": "The original list : ['gfg', 1, 2, 'is', 'best']\nInteger list : [1, 2]\nString list : ['gfg', 'is', 'best']"
},
{
"code": null,
"e": 1410,
"s": 1172,
"text": " Method #2 : Using defaultdict() + loop This is yet another way in which this problem can be solved. In this, we initialize the list as data type for defaultdict() and loop through each element and save each datatype list in defaultdict."
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Split heterogeneous type list# using defaultdict() + loopfrom collections import defaultdict # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint(\"The original list : \" + str(test_list)) # Split heterogeneous type list# using defaultdict() + loopres = defaultdict(list)for ele in test_list: res[type(ele)].append(ele) # printing resultprint(\"Integer list : \" + str(res[int]))print(\"String list : \" + str(res[str]))",
"e": 1911,
"s": 1418,
"text": null
},
{
"code": null,
"e": 2017,
"s": 1911,
"text": "The original list : ['gfg', 1, 2, 'is', 'best']\nInteger list : [1, 2]\nString list : ['gfg', 'is', 'best']"
},
{
"code": null,
"e": 2036,
"s": 2019,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2057,
"s": 2036,
"text": "Python list-programs"
},
{
"code": null,
"e": 2064,
"s": 2057,
"text": "Python"
},
{
"code": null,
"e": 2080,
"s": 2064,
"text": "Python Programs"
},
{
"code": null,
"e": 2178,
"s": 2080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2210,
"s": 2178,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2237,
"s": 2210,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2258,
"s": 2237,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2281,
"s": 2258,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2337,
"s": 2281,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2359,
"s": 2337,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2398,
"s": 2359,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2436,
"s": 2398,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2485,
"s": 2436,
"text": "Python | Convert string dictionary to dictionary"
}
] |
How to add Key Value Pair to List in R ?
|
01 Oct, 2021
A key-value pair can be explained as a set of two linked data items where a key uniquely identifies a value or a set of values in the data. Since a list can hold multiple data-types data, we can have a key-value pair stored in the list
We can assign variables to each key and value. Store each key-value pair after building the list using square brackets.
R
rm(list = ls()) # create key value variableskey1 <- "Age"value1 <- 21 key2 <- "Name"value2 <- "Pulkit" # create the listmylist <- list() # Build up key value pairsmylist[[ key1 ]] <- value1mylist[[ key2 ]] <- value2 # Access value using the keyprint(mylist$Age)print(mylist$Name)
Output:
21
Pulkit
Another way of doing this without using any additional variables is to specify the key and the value in the list() function while creating the list.
Example
R
rm(list = ls()) # Creating the listmylist<-list("Name"="Pulkit","Age"=21, "Gender"="Male") # Access value using the keyprint(mylist$Age)print(mylist$Gender)
Output:
21
Male
Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as.list(). Basically what we will have here is a syntax like given below, which will create a list and assign all the keys with their respective values.
Syntax:
variable<-setNames(as.list(values), keys)
Example:
R
rm(list = ls()) # initialize keys and respected valuesstudents <- c("Pulkit", "Ritika", "Parth", "Vishesh", "Dharvik", "krishav", "Reshav") marks <- c(75, 92, 97, 80, 85, 87, 52) # make the listresults <- setNames(as.list(marks), students) # Access value using the keyprint(results$Pulkit)
Output:
75
simmytarika5
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "A key-value pair can be explained as a set of two linked data items where a key uniquely identifies a value or a set of values in the data. Since a list can hold multiple data-types data, we can have a key-value pair stored in the list"
},
{
"code": null,
"e": 384,
"s": 264,
"text": "We can assign variables to each key and value. Store each key-value pair after building the list using square brackets."
},
{
"code": null,
"e": 386,
"s": 384,
"text": "R"
},
{
"code": "rm(list = ls()) # create key value variableskey1 <- \"Age\"value1 <- 21 key2 <- \"Name\"value2 <- \"Pulkit\" # create the listmylist <- list() # Build up key value pairsmylist[[ key1 ]] <- value1mylist[[ key2 ]] <- value2 # Access value using the keyprint(mylist$Age)print(mylist$Name)",
"e": 666,
"s": 386,
"text": null
},
{
"code": null,
"e": 674,
"s": 666,
"text": "Output:"
},
{
"code": null,
"e": 685,
"s": 674,
"text": "21\nPulkit "
},
{
"code": null,
"e": 834,
"s": 685,
"text": "Another way of doing this without using any additional variables is to specify the key and the value in the list() function while creating the list."
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Example"
},
{
"code": null,
"e": 844,
"s": 842,
"text": "R"
},
{
"code": "rm(list = ls()) # Creating the listmylist<-list(\"Name\"=\"Pulkit\",\"Age\"=21, \"Gender\"=\"Male\") # Access value using the keyprint(mylist$Age)print(mylist$Gender)",
"e": 1013,
"s": 844,
"text": null
},
{
"code": null,
"e": 1021,
"s": 1013,
"text": "Output:"
},
{
"code": null,
"e": 1029,
"s": 1021,
"text": "21\nMale"
},
{
"code": null,
"e": 1296,
"s": 1029,
"text": "Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as.list(). Basically what we will have here is a syntax like given below, which will create a list and assign all the keys with their respective values. "
},
{
"code": null,
"e": 1304,
"s": 1296,
"text": "Syntax:"
},
{
"code": null,
"e": 1346,
"s": 1304,
"text": "variable<-setNames(as.list(values), keys)"
},
{
"code": null,
"e": 1355,
"s": 1346,
"text": "Example:"
},
{
"code": null,
"e": 1357,
"s": 1355,
"text": "R"
},
{
"code": "rm(list = ls()) # initialize keys and respected valuesstudents <- c(\"Pulkit\", \"Ritika\", \"Parth\", \"Vishesh\", \"Dharvik\", \"krishav\", \"Reshav\") marks <- c(75, 92, 97, 80, 85, 87, 52) # make the listresults <- setNames(as.list(marks), students) # Access value using the keyprint(results$Pulkit)",
"e": 1673,
"s": 1357,
"text": null
},
{
"code": null,
"e": 1681,
"s": 1673,
"text": "Output:"
},
{
"code": null,
"e": 1685,
"s": 1681,
"text": " 75"
},
{
"code": null,
"e": 1698,
"s": 1685,
"text": "simmytarika5"
},
{
"code": null,
"e": 1705,
"s": 1698,
"text": "Picked"
},
{
"code": null,
"e": 1721,
"s": 1705,
"text": "R List-Programs"
},
{
"code": null,
"e": 1728,
"s": 1721,
"text": "R-List"
},
{
"code": null,
"e": 1739,
"s": 1728,
"text": "R Language"
},
{
"code": null,
"e": 1750,
"s": 1739,
"text": "R Programs"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.